<template>
  <div class="activity-container">
    <!-- 工具栏 -->
    <el-card shadow="never" class="toolbar-card">
      <div class="toolbar">
        <div class="toolbar-left">
          <el-select
            v-model="selectedCompetition"
            placeholder="请选择赛事"
            filterable
            style="width: 280px"
            @change="handleCompetitionChange"
          >
            <el-option
              v-for="item in competitionList"
              :key="item.id"
              :label="item.competitionName"
              :value="item.id"
            />
          </el-select>
        </div>
        <div class="toolbar-right">
          <el-button type="primary" :icon="Plus" @click="handleAdd">
            添加活动
          </el-button>
          <el-button :icon="Upload" @click="handleImport">
            导入
          </el-button>
          <el-button :icon="Download" @click="handleExport">
            导出
          </el-button>
          <el-button :icon="Refresh" @click="loadActivityData">
            刷新
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="15" class="stats-row">
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-content">
            <div class="stats-icon" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%)">
              <el-icon :size="28"><Calendar /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-value">{{ statistics.totalActivities || 0 }}</div>
              <div class="stats-label">总活动数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-content">
            <div class="stats-icon" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%)">
              <el-icon :size="28"><Clock /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-value">{{ statistics.todayActivities || 0 }}</div>
              <div class="stats-label">今日活动</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-content">
            <div class="stats-icon" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)">
              <el-icon :size="28"><TrophyBase /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-value">{{ statistics.competitions || 0 }}</div>
              <div class="stats-label">比赛场次</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-content">
            <div class="stats-icon" style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%)">
              <el-icon :size="28"><ChatDotRound /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-value">{{ statistics.meetings || 0 }}</div>
              <div class="stats-label">会议数量</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 日历视图 -->
    <el-card shadow="never" class="calendar-card">
      <div class="calendar-header">
        <div class="header-left">
          <el-button-group>
            <el-button
              :type="calendarView === 'month' ? 'primary' : ''"
              @click="calendarView = 'month'"
            >
              月视图
            </el-button>
            <el-button
              :type="calendarView === 'week' ? 'primary' : ''"
              @click="calendarView = 'week'"
            >
              周视图
            </el-button>
            <el-button
              :type="calendarView === 'day' ? 'primary' : ''"
              @click="calendarView = 'day'"
            >
              日视图
            </el-button>
          </el-button-group>
        </div>
        <div class="header-center">
          <el-button :icon="ArrowLeft" @click="handlePrevPeriod" />
          <span class="current-period">{{ currentPeriodText }}</span>
          <el-button :icon="ArrowRight" @click="handleNextPeriod" />
          <el-button style="margin-left: 10px" @click="handleToday">今天</el-button>
        </div>
        <div class="header-right">
          <el-select
            v-model="filterType"
            placeholder="活动类型"
            clearable
            style="width: 150px"
            @change="loadCalendarData"
          >
            <el-option label="开幕式" value="opening_ceremony" />
            <el-option label="闭幕式" value="closing_ceremony" />
            <el-option label="比赛" value="competition" />
            <el-option label="培训" value="training" />
            <el-option label="会议" value="meeting" />
            <el-option label="其他" value="other" />
          </el-select>
        </div>
      </div>

      <!-- 简化的日历视图 -->
      <div v-loading="calendarLoading" class="calendar-content">
        <el-calendar v-model="currentDate">
          <template #date-cell="{ data }">
            <div class="calendar-day">
              <div class="day-number">{{ data.day.split('-')[2] }}</div>
              <div class="day-activities">
                <div
                  v-for="activity in getDayActivities(data.day)"
                  :key="activity.id"
                  :class="['activity-item', `type-${activity.activityType}`]"
                  @click="handleViewActivity(activity)"
                >
                  <el-tooltip :content="activity.activityName" placement="top">
                    <span class="activity-name">{{ activity.activityName }}</span>
                  </el-tooltip>
                </div>
              </div>
            </div>
          </template>
        </el-calendar>
      </div>
    </el-card>

    <!-- 活动列表 -->
    <el-card shadow="never" class="list-card">
      <div class="list-header">
        <h3>活动列表</h3>
        <el-form :inline="true" :model="queryParams">
          <el-form-item label="活动名称">
            <el-input
              v-model="queryParams.activityName"
              placeholder="搜索活动..."
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="loadActivityList">
              搜索
            </el-button>
            <el-button :icon="Refresh" @click="handleResetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table
        v-loading="loading"
        :data="activityList"
        stripe
        border
        @row-click="handleViewActivity"
      >
        <el-table-column prop="id" label="编号" width="80" align="center" />
        <el-table-column prop="activityName" label="活动名称" min-width="200" show-overflow-tooltip />
        <el-table-column prop="activityType" label="活动类型" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getTypeTag(row.activityType)" size="small">
              {{ getTypeText(row.activityType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="160" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="endTime" label="结束时间" width="160" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="location" label="地点" width="150" show-overflow-tooltip />
        <el-table-column prop="organizer" label="组织者" width="120" />
        <el-table-column label="操作" width="260" align="center" fixed="right">
          <template #default="{ row }">
            <el-button link :icon="View" @click.stop="handleViewActivity(row)">
              查看
            </el-button>
            <el-button link type="primary" :icon="Edit" @click.stop="handleEdit(row)">
              编辑
            </el-button>
            <el-button link type="success" :icon="CopyDocument" @click.stop="handleCopy(row)">
              复制
            </el-button>
            <el-button link type="danger" :icon="Delete" @click.stop="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.current"
          v-model:page-size="queryParams.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadActivityList"
          @current-change="loadActivityList"
        />
      </div>
    </el-card>

    <!-- 添加/编辑活动对话框 -->
    <el-dialog
      v-model="formVisible"
      :title="dialogTitle"
      width="900px"
      :close-on-click-modal="false"
      @close="handleFormClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="活动类型" prop="activityType">
              <el-select v-model="form.activityType" placeholder="请选择类型" style="width: 100%">
                <el-option label="开幕式" value="opening_ceremony" />
                <el-option label="闭幕式" value="closing_ceremony" />
                <el-option label="比赛" value="competition" />
                <el-option label="培训" value="training" />
                <el-option label="会议" value="meeting" />
                <el-option label="其他" value="other" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="活动名称" prop="activityName">
              <el-input v-model="form.activityName" placeholder="请输入活动名称" maxlength="100" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker
                v-model="form.startTime"
                type="datetime"
                placeholder="选择开始时间"
                style="width: 100%"
                @change="handleTimeChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker
                v-model="form.endTime"
                type="datetime"
                placeholder="选择结束时间"
                style="width: 100%"
                @change="handleTimeChange"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="活动地点" prop="location">
              <el-input v-model="form.location" placeholder="请输入活动地点" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联场地">
              <el-select v-model="form.venueId" placeholder="选择场地(可选)" clearable style="width: 100%">
                <el-option
                  v-for="item in venueList"
                  :key="item.id"
                  :label="item.venueName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="组织者" prop="organizer">
              <el-input v-model="form.organizer" placeholder="请输入组织者" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="参与人员">
              <el-input v-model="form.participants" placeholder="请输入参与人员(可选)" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="活动描述">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入活动描述"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="form.remarks"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息(可选)"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        <el-alert
          v-if="conflictWarning"
          :title="conflictWarning"
          type="warning"
          :closable="false"
          style="margin-bottom: 15px"
        />
      </el-form>
      <template #footer>
        <el-button @click="formVisible = false">取消</el-button>
        <el-button type="primary" :loading="formLoading" @click="handleSubmit">
          {{ dialogTitle === '添加活动' ? '立即添加' : '保存修改' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 复制活动对话框 -->
    <el-dialog
      v-model="copyVisible"
      title="复制活动"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="copyFormRef"
        :model="copyForm"
        :rules="copyFormRules"
        label-width="120px"
      >
        <el-form-item label="原活动名称">
          <el-input :value="copyForm.sourceName" disabled />
        </el-form-item>
        <el-form-item label="新开始时间" prop="newStartTime">
          <el-date-picker
            v-model="copyForm.newStartTime"
            type="datetime"
            placeholder="选择新开始时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="新结束时间" prop="newEndTime">
          <el-date-picker
            v-model="copyForm.newEndTime"
            type="datetime"
            placeholder="选择新结束时间"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="copyVisible = false">取消</el-button>
        <el-button type="primary" :loading="copyLoading" @click="handleCopySubmit">
          确认复制
        </el-button>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="detailVisible" title="活动详情" width="800px">
      <div class="detail-container">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="编号">{{ detailData.id }}</el-descriptions-item>
          <el-descriptions-item label="活动类型">
            <el-tag :type="getTypeTag(detailData.activityType)" size="small">
              {{ getTypeText(detailData.activityType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="活动名称" :span="2">{{ detailData.activityName }}</el-descriptions-item>
          <el-descriptions-item label="开始时间">
            {{ formatDateTime(detailData.startTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="结束时间">
            {{ formatDateTime(detailData.endTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="活动地点">{{ detailData.location }}</el-descriptions-item>
          <el-descriptions-item label="关联场地">{{ detailData.venueName || '无' }}</el-descriptions-item>
          <el-descriptions-item label="组织者">{{ detailData.organizer }}</el-descriptions-item>
          <el-descriptions-item label="参与人员">{{ detailData.participants || '未填写' }}</el-descriptions-item>
          <el-descriptions-item label="活动描述" :span="2">
            {{ detailData.description || '无' }}
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">
            {{ detailData.remarks || '无' }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatDateTime(detailData.createTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ formatDateTime(detailData.updateTime) }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog
      v-model="importVisible"
      title="导入活动日程"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-upload
        ref="uploadRef"
        :auto-upload="false"
        :on-change="handleFileChange"
        :limit="1"
        accept=".xlsx,.xls"
        drag
      >
        <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处,或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            仅支持xlsx/xls格式文件,大小不超过10MB
          </div>
        </template>
      </el-upload>
      <template #footer>
        <el-button @click="importVisible = false">取消</el-button>
        <el-button type="primary" :loading="importLoading" @click="handleImportSubmit">
          确认导入
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  Plus,
  Delete,
  Edit,
  Download,
  Upload,
  View,
  CopyDocument,
  Calendar,
  Clock,
  TrophyBase,
  ChatDotRound,
  ArrowLeft,
  ArrowRight,
  UploadFilled
} from '@element-plus/icons-vue'
import {
  getActivityScheduleList,
  addActivity,
  updateActivity,
  removeActivity,
  getActivityCalendar,
  checkActivityConflict,
  copyActivity,
  getActivitiesByDate,
  getActivityStatistics,
  exportActivitySchedule,
  importActivitySchedule
} from '@/api/martial/activity'
import { getCompetitionList } from '@/api/martial/competition'
import { getVenueList } from '@/api/martial/venue'
import dayjs from 'dayjs'

// 状态变量
const loading = ref(false)
const calendarLoading = ref(false)
const formLoading = ref(false)
const copyLoading = ref(false)
const importLoading = ref(false)
const activityList = ref([])
const calendarActivities = ref([])
const total = ref(0)
const competitionList = ref([])
const venueList = ref([])
const selectedCompetition = ref('')
const formVisible = ref(false)
const copyVisible = ref(false)
const detailVisible = ref(false)
const importVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const copyFormRef = ref(null)
const uploadRef = ref(null)
const uploadFile = ref(null)
const detailData = ref({})
const conflictWarning = ref('')
const calendarView = ref('month')
const currentDate = ref(new Date())
const filterType = ref('')

// 统计数据
const statistics = ref({
  totalActivities: 0,
  todayActivities: 0,
  competitions: 0,
  meetings: 0
})

// 查询参数
const queryParams = reactive({
  current: 1,
  size: 10,
  competitionId: '',
  activityType: '',
  activityName: '',
  startDate: '',
  endDate: ''
})

// 表单数据
const form = reactive({
  id: null,
  competitionId: '',
  activityType: 'competition',
  activityName: '',
  description: '',
  startTime: null,
  endTime: null,
  location: '',
  venueId: '',
  organizer: '',
  participants: '',
  remarks: ''
})

// 复制表单
const copyForm = reactive({
  sourceId: null,
  sourceName: '',
  newStartTime: null,
  newEndTime: null
})

// 表单验证规则
const formRules = {
  activityType: [
    { required: true, message: '请选择活动类型', trigger: 'change' }
  ],
  activityName: [
    { required: true, message: '请输入活动名称', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  location: [
    { required: true, message: '请输入活动地点', trigger: 'blur' }
  ],
  organizer: [
    { required: true, message: '请输入组织者', trigger: 'blur' }
  ]
}

// 复制表单验证
const copyFormRules = {
  newStartTime: [
    { required: true, message: '请选择新开始时间', trigger: 'change' }
  ],
  newEndTime: [
    { required: true, message: '请选择新结束时间', trigger: 'change' }
  ]
}

// 当前周期文本
const currentPeriodText = computed(() => {
  if (calendarView.value === 'month') {
    return dayjs(currentDate.value).format('YYYY年MM月')
  } else if (calendarView.value === 'week') {
    const start = dayjs(currentDate.value).startOf('week')
    const end = dayjs(currentDate.value).endOf('week')
    return `${start.format('YYYY年MM月DD日')} - ${end.format('MM月DD日')}`
  } else {
    return dayjs(currentDate.value).format('YYYY年MM月DD日')
  }
})

// 加载赛事列表
const loadCompetitionList = async () => {
  try {
    const res = await getCompetitionList(1, 1000, { status: 1 })
    if (res.data && res.data.records) {
      competitionList.value = res.data.records
      if (competitionList.value.length > 0) {
        selectedCompetition.value = competitionList.value[0].id
        handleCompetitionChange(selectedCompetition.value)
      }
    }
  } catch (error) {
    console.error('加载赛事列表失败:', error)
  }
}

// 加载场地列表
const loadVenueList = async () => {
  try {
    const res = await getVenueList(1, 1000, {})
    if (res.data && res.data.records) {
      venueList.value = res.data.records
    }
  } catch (error) {
    console.error('加载场地列表失败:', error)
  }
}

// 赛事变更
const handleCompetitionChange = (competitionId) => {
  queryParams.competitionId = competitionId
  form.competitionId = competitionId
  loadActivityData()
}

// 加载所有活动数据
const loadActivityData = () => {
  loadActivityList()
  loadCalendarData()
  loadStatistics()
}

// 加载活动列表
const loadActivityList = async () => {
  if (!selectedCompetition.value) return

  loading.value = true
  try {
    const res = await getActivityScheduleList(
      queryParams.current,
      queryParams.size,
      queryParams
    )
    if (res.data) {
      activityList.value = res.data.records || []
      total.value = res.data.total || 0
    }
  } catch (error) {
    ElMessage.error('加载数据失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 加载日历数据
const loadCalendarData = async () => {
  if (!selectedCompetition.value) return

  calendarLoading.value = true
  try {
    const month = dayjs(currentDate.value).format('YYYY-MM')
    const res = await getActivityCalendar(selectedCompetition.value, month)
    if (res.data) {
      calendarActivities.value = res.data || []
    }
  } catch (error) {
    console.error('加载日历数据失败:', error)
  } finally {
    calendarLoading.value = false
  }
}

// 加载统计数据
const loadStatistics = async () => {
  if (!selectedCompetition.value) return

  try {
    const res = await getActivityStatistics(selectedCompetition.value)
    if (res.data) {
      statistics.value = res.data
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// 获取指定日期的活动
const getDayActivities = (date) => {
  return calendarActivities.value.filter(activity => {
    const activityDate = dayjs(activity.startTime).format('YYYY-MM-DD')
    return activityDate === date && (!filterType.value || activity.activityType === filterType.value)
  })
}

// 上一周期
const handlePrevPeriod = () => {
  if (calendarView.value === 'month') {
    currentDate.value = dayjs(currentDate.value).subtract(1, 'month').toDate()
  } else if (calendarView.value === 'week') {
    currentDate.value = dayjs(currentDate.value).subtract(1, 'week').toDate()
  } else {
    currentDate.value = dayjs(currentDate.value).subtract(1, 'day').toDate()
  }
  loadCalendarData()
}

// 下一周期
const handleNextPeriod = () => {
  if (calendarView.value === 'month') {
    currentDate.value = dayjs(currentDate.value).add(1, 'month').toDate()
  } else if (calendarView.value === 'week') {
    currentDate.value = dayjs(currentDate.value).add(1, 'week').toDate()
  } else {
    currentDate.value = dayjs(currentDate.value).add(1, 'day').toDate()
  }
  loadCalendarData()
}

// 回到今天
const handleToday = () => {
  currentDate.value = new Date()
  loadCalendarData()
}

// 重置搜索
const handleResetSearch = () => {
  Object.assign(queryParams, {
    current: 1,
    size: 10,
    activityType: '',
    activityName: '',
    startDate: '',
    endDate: ''
  })
  loadActivityList()
}

// 添加活动
const handleAdd = () => {
  dialogTitle.value = '添加活动'
  resetForm()
  formVisible.value = true
}

// 编辑活动
const handleEdit = (row) => {
  dialogTitle.value = '编辑活动'
  Object.assign(form, {
    id: row.id,
    competitionId: row.competitionId,
    activityType: row.activityType,
    activityName: row.activityName,
    description: row.description,
    startTime: row.startTime,
    endTime: row.endTime,
    location: row.location,
    venueId: row.venueId,
    organizer: row.organizer,
    participants: row.participants,
    remarks: row.remarks
  })
  formVisible.value = true
}

// 时间变更检测冲突
const handleTimeChange = async () => {
  if (!form.startTime || !form.endTime) return

  // 验证时间有效性
  if (dayjs(form.endTime).isBefore(dayjs(form.startTime))) {
    ElMessage.warning('结束时间不能早于开始时间')
    return
  }

  // 检查时间冲突
  try {
    const res = await checkActivityConflict({
      competitionId: form.competitionId,
      startTime: form.startTime,
      endTime: form.endTime,
      venueId: form.venueId,
      excludeId: form.id
    })
    if (res.data && res.data.hasConflict) {
      conflictWarning.value = `时间冲突警告: 与活动"${res.data.conflictActivity}"时间冲突`
    } else {
      conflictWarning.value = ''
    }
  } catch (error) {
    console.error('检查时间冲突失败:', error)
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      formLoading.value = true
      try {
        if (form.id) {
          await updateActivity(form)
          ElMessage.success('修改成功')
        } else {
          await addActivity(form)
          ElMessage.success('添加成功')
        }

        formVisible.value = false
        loadActivityData()
      } catch (error) {
        ElMessage.error(form.id ? '修改失败' : '添加失败')
      } finally {
        formLoading.value = false
      }
    }
  })
}

// 关闭表单
const handleFormClose = () => {
  resetForm()
  conflictWarning.value = ''
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: null,
    competitionId: selectedCompetition.value,
    activityType: 'competition',
    activityName: '',
    description: '',
    startTime: null,
    endTime: null,
    location: '',
    venueId: '',
    organizer: '',
    participants: '',
    remarks: ''
  })
}

// 复制活动
const handleCopy = (row) => {
  copyForm.sourceId = row.id
  copyForm.sourceName = row.activityName
  copyForm.newStartTime = null
  copyForm.newEndTime = null
  copyVisible.value = true
}

// 提交复制
const handleCopySubmit = async () => {
  if (!copyFormRef.value) return

  await copyFormRef.value.validate(async (valid) => {
    if (valid) {
      copyLoading.value = true
      try {
        await copyActivity({
          sourceId: copyForm.sourceId,
          newStartTime: copyForm.newStartTime,
          newEndTime: copyForm.newEndTime
        })
        ElMessage.success('复制成功')
        copyVisible.value = false
        loadActivityData()
      } catch (error) {
        ElMessage.error('复制失败')
      } finally {
        copyLoading.value = false
      }
    }
  })
}

// 查看详情
const handleViewActivity = (row) => {
  detailData.value = { ...row }
  detailVisible.value = true
}

// 删除活动
const handleDelete = (row) => {
  ElMessageBox.confirm('确定删除该活动吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        await removeActivity(row.id)
        ElMessage.success('删除成功')
        loadActivityData()
      } catch (error) {
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {})
}

// 导入
const handleImport = () => {
  importVisible.value = true
}

// 文件变更
const handleFileChange = (file) => {
  uploadFile.value = file.raw
}

// 提交导入
const handleImportSubmit = async () => {
  if (!uploadFile.value) {
    ElMessage.warning('请选择文件')
    return
  }

  importLoading.value = true
  try {
    await importActivitySchedule(uploadFile.value, selectedCompetition.value)
    ElMessage.success('导入成功')
    importVisible.value = false
    uploadFile.value = null
    loadActivityData()
  } catch (error) {
    ElMessage.error('导入失败')
  } finally {
    importLoading.value = false
  }
}

// 导出
const handleExport = async () => {
  try {
    const res = await exportActivitySchedule(queryParams)
    const blob = new Blob([res], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = `活动日程_${dayjs().format('YYYYMMDDHHmmss')}.xlsx`
    link.click()
    window.URL.revokeObjectURL(link.href)
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 获取类型标签
const getTypeTag = (type) => {
  const tagMap = {
    'opening_ceremony': 'danger',
    'closing_ceremony': 'warning',
    'competition': 'primary',
    'training': 'success',
    'meeting': 'info',
    'other': ''
  }
  return tagMap[type] || 'info'
}

// 获取类型文本
const getTypeText = (type) => {
  const textMap = {
    'opening_ceremony': '开幕式',
    'closing_ceremony': '闭幕式',
    'competition': '比赛',
    'training': '培训',
    'meeting': '会议',
    'other': '其他'
  }
  return textMap[type] || '未知类型'
}

// 格式化日期时间
const formatDateTime = (date) => {
  if (!date) return '-'
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

// 组件挂载
onMounted(() => {
  loadCompetitionList()
  loadVenueList()
})
</script>

<style scoped lang="scss">
.activity-container {
  padding: 20px;

  .toolbar-card,
  .calendar-card,
  .list-card {
    margin-bottom: 20px;

    .toolbar,
    .calendar-header,
    .list-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .toolbar-left,
      .header-left {
        display: flex;
        gap: 10px;
        align-items: center;
      }

      .toolbar-right,
      .header-right {
        display: flex;
        gap: 10px;
      }

      .header-center {
        display: flex;
        align-items: center;
        gap: 10px;

        .current-period {
          font-size: 16px;
          font-weight: 600;
          color: #303133;
          min-width: 200px;
          text-align: center;
        }
      }
    }
  }

  .stats-row {
    margin-bottom: 20px;

    .stats-card {
      .stats-content {
        display: flex;
        align-items: center;
        padding: 10px 0;

        .stats-icon {
          width: 55px;
          height: 55px;
          border-radius: 10px;
          display: flex;
          align-items: center;
          justify-content: center;
          color: #fff;
          margin-right: 15px;
        }

        .stats-info {
          flex: 1;

          .stats-value {
            font-size: 24px;
            font-weight: bold;
            color: #303133;
            line-height: 1;
            margin-bottom: 6px;
          }

          .stats-label {
            font-size: 13px;
            color: #909399;
          }
        }
      }
    }
  }

  .calendar-card {
    .calendar-header {
      margin-bottom: 20px;
      padding-bottom: 15px;
      border-bottom: 1px solid #e4e7ed;
    }

    .calendar-content {
      min-height: 400px;

      .calendar-day {
        padding: 4px;
        height: 100%;
        overflow: hidden;

        .day-number {
          font-size: 14px;
          font-weight: 600;
          color: #303133;
          margin-bottom: 4px;
        }

        .day-activities {
          display: flex;
          flex-direction: column;
          gap: 2px;

          .activity-item {
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 12px;
            cursor: pointer;
            transition: all 0.3s;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;

            &.type-opening_ceremony {
              background: #f56c6c;
              color: #fff;
            }

            &.type-closing_ceremony {
              background: #e6a23c;
              color: #fff;
            }

            &.type-competition {
              background: #409eff;
              color: #fff;
            }

            &.type-training {
              background: #67c23a;
              color: #fff;
            }

            &.type-meeting {
              background: #909399;
              color: #fff;
            }

            &.type-other {
              background: #dcdfe6;
              color: #606266;
            }

            &:hover {
              opacity: 0.8;
              transform: scale(1.02);
            }

            .activity-name {
              font-size: 12px;
            }
          }
        }
      }
    }
  }

  .list-card {
    .list-header {
      margin-bottom: 20px;
      padding-bottom: 15px;
      border-bottom: 1px solid #e4e7ed;

      h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
      }
    }

    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .detail-container {
    padding: 10px 0;
  }
}

:deep(.el-calendar-table .el-calendar-day) {
  height: 120px;
  padding: 0;
}

:deep(.el-calendar-table td.is-selected) {
  background-color: #f0f9ff;
}

:deep(.el-calendar-table td.is-today) {
  color: #409eff;
  font-weight: 600;
}
</style>
