<template>
  <div class="p-2">
    <el-card shadow="never">
      <template #header>
        <div class="flex items-center justify-between">
          <div class="flex items-center gap-4">
            <h3 class="text-lg font-bold">赛事日程安排</h3>
            <el-button type="primary" @click="loadEventData()" :disabled="!defaultEvent.eventId"> 加载赛事数据 </el-button>
          </div>
          <div>
            <el-button type="success" @click="exportSchedule" :disabled="!defaultEvent.eventId || scheduleData.length === 0"> 导出日程表 </el-button>
          </div>
        </div>
      </template>

      <!-- 赛事信息展示 -->
      <el-card v-if="defaultEvent.eventId" class="mb-4" shadow="hover">
        <div class="flex items-center justify-between">
          <div>
            <h3 class="text-lg font-bold">{{ defaultEvent.eventName }}</h3>
            <p class="text-gray-600">比赛时间: {{ parseTime(defaultEvent.startTime) }} 至 {{ parseTime(defaultEvent.endTime) }}</p>
          </div>
          <div>
            <p>赛事地点: {{ defaultEvent.location }}</p>
          </div>
        </div>
      </el-card>

      <!-- 日程安排表单 -->
      <el-card v-if="defaultEvent.eventId && projectGroups.length > 0" class="mb-4" shadow="hover">
        <template #header>
          <span class="font-bold">项目分组与时间安排</span>
        </template>

        <el-tabs v-model="activeGroupTab">
          <el-tab-pane v-for="group in projectGroups" :key="group.type" :label="`${group.type} (${group.projects.length})`" :name="group.type">
            <el-table :data="group.projects" border class="mb-4">
              <el-table-column label="序号" align="center" type="index" />
              <el-table-column label="项目名称" prop="projectName" />
              <!-- <el-table-column label="项目组别" prop="groupType" width="120" /> -->
              <el-table-column label="项目类型">
                <template #default="scope">
                  <dict-tag :options="game_project_type" :value="scope.row.projectType || ''" />
                </template>
              </el-table-column>
              <el-table-column label="比赛日期">
                <template #default="scope">
                  <el-date-picker
                    v-model="scope.row.scheduleDate"
                    type="date"
                    placeholder="选择日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    style="width: 100%"
                  />
                </template>
              </el-table-column>
              <el-table-column label="开始时间">
                <template #default="scope">
                  <el-time-picker v-model="scope.row.startTime" placeholder="开始时间" format="HH:mm" value-format="HH:mm" style="width: 100%" />
                </template>
              </el-table-column>
              <el-table-column label="结束时间">
                <template #default="scope">
                  <el-time-picker v-model="scope.row.endTime" placeholder="结束时间" format="HH:mm" value-format="HH:mm" style="width: 100%" />
                </template>
              </el-table-column>
              <el-table-column label="比赛场地">
                <template #default="scope">
                  <el-input v-model="scope.row.location" placeholder="输入比赛场地" />
                </template>
              </el-table-column>
              <el-table-column label="分组数">
                <template #default="scope">
                  <el-input-number v-model="scope.row.groupNum" :min="1" :max="20" controls-position="right" size="small" />
                </template>
              </el-table-column>
              <el-table-column label="每组人数">
                <template #default="scope">
                  <el-input-number v-model="scope.row.participateNum" :min="1" :max="100" controls-position="right" size="small" />
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>

        <div class="flex justify-end">
          <el-button type="primary" @click="saveSchedule">保存日程安排</el-button>
        </div>
      </el-card>

      <!-- 日程预览表格 -->
      <el-card v-if="scheduleData.length > 0" shadow="hover">
        <template #header>
          <span class="font-bold">日程预览</span>
        </template>

        <el-table :data="scheduleData" border stripe class="schedule-table">
          <el-table-column label="日期" prop="scheduleDate" align="center" />
          <el-table-column label="时间" align="center">
            <template #default="scope"> {{ scope.row.startTime }} - {{ scope.row.endTime }}</template>
          </el-table-column>
          <el-table-column label="项目名称" prop="projectName" align="center" />
          <el-table-column label="项目类型" align="center">
            <template #default="scope">
              <dict-tag :options="game_project_type" :value="scope.row.projectType || ''" />
            </template>
          </el-table-column>
          <!-- <el-table-column label="项目组别" prop="groupType" width="120" /> -->
          <el-table-column label="比赛场地" prop="location" align="center" />
          <el-table-column label="分组数" prop="groupNum" align="center" />
          <el-table-column label="每组人数" prop="participateNum" align="center" />
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button type="danger" size="small" @click="deleteSchedule(scope.row)" v-hasPermi="['system:gameeventproject:remove']">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-card>
  </div>
</template>

<script setup name="GameEventSchedule" lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { listGameEventProject, updateGameEventProject } from '@/api/system/gameEventProject';
import { getDefaultEvent } from '@/api/system/gameEvent';
import { GameEventVO } from '@/api/system/gameEvent/types';
import { GameEventProjectVO } from '@/api/system/gameEventProject/types';
import { parseTime } from '@/utils/ruoyi';
import { ElMessage, ElMessageBox } from 'element-plus';
import DictTag from '@/components/DictTag/index.vue';

const { proxy } = getCurrentInstance() as any;
const { game_project_type } = toRefs<any>(proxy?.useDict('game_project_type'));

// 默认赛事信息
const defaultEvent = ref<GameEventVO>({} as GameEventVO);
// 项目分组（按项目类型分组）
const projectGroups = ref<{ type: string; projects: GameEventProjectVO[] }[]>([]);
// 活动的项目分组标签页
const activeGroupTab = ref('个人');
// 日程数据（用于预览和导出）
const scheduleData = ref<GameEventProjectVO[]>([]);

// 获取默认赛事
const loadDefaultEvent = async () => {
  try {
    const res = await getDefaultEvent();
    defaultEvent.value = res.data;
  } catch (error) {
    ElMessage.error('获取默认赛事失败');
  }
};

// 加载赛事数据
const loadEventData = async () => {
  if (!defaultEvent.value.eventId) {
    ElMessage.warning('请先指定默认赛事');
    return;
  }

  try {
    // 获取赛事项目
    const projectRes = await listGameEventProject({
      eventId: defaultEvent.value.eventId,
      pageNum: 1,
      pageSize: 1000,
      orderByColumn: '',
      isAsc: ''
    });

    // 按项目类型分组
    const groups: { [key: string]: GameEventProjectVO[] } = {};
    projectRes.rows.forEach((project) => {
      // 使用字典标签作为分组键
      const projectTypeDict = game_project_type.value.find((dict: any) => dict.value === project.projectType);
      const type = projectTypeDict ? projectTypeDict.label : '未知类型';
      if (!groups[type]) {
        groups[type] = [];
      }
      // 初始化时间字段
      // 从数据库加载时，将开始时间和结束时间拆分为日期和时间部分
      if (project.startTime) {
        // 提取日期部分
        project.scheduleDate = project.startTime.split(' ')[0];
        // 只保留时间部分
        project.startTime = project.startTime.split(' ')[1]?.substring(0, 5) || '';
      }

      if (project.endTime) {
        // 只保留时间部分（日期部分应该与startTime相同）
        project.endTime = project.endTime.split(' ')[1]?.substring(0, 5) || '';
      }

      if (!project.groupNum) project.groupNum = 1;
      if (!project.participateNum) project.participateNum = 1;
      groups[type].push(project);
    });

    projectGroups.value = Object.keys(groups).map((type) => ({
      type,
      projects: groups[type]
    }));

    // 设置默认活动标签页
    if (projectGroups.value.length > 0) {
      activeGroupTab.value = projectGroups.value[0].type;
    }

    // 更新日程预览数据
    updateScheduleData();

    ElMessage.success('赛事数据加载成功');
  } catch (error) {
    ElMessage.error('加载赛事数据失败');
  }
};

// 更新日程预览数据
const updateScheduleData = () => {
  const allProjects: GameEventProjectVO[] = [];
  projectGroups.value.forEach((group) => {
    group.projects.forEach((project) => {
      // 只添加已安排时间的项目
      if (project.scheduleDate && project.startTime && project.endTime) {
        allProjects.push(project);
      }
    });
  });

  // 按日期和时间排序
  scheduleData.value = allProjects.sort((a, b) => {
    if (a.scheduleDate !== b.scheduleDate) {
      return a.scheduleDate.localeCompare(b.scheduleDate);
    }
    return a.startTime.localeCompare(b.startTime);
  });
};

// 保存日程安排
const saveSchedule = async () => {
  try {
    const allProjects: GameEventProjectVO[] = [];
    projectGroups.value.forEach((group) => {
      allProjects.push(...group.projects);
    });

    // 保存每个项目的时间安排
    for (const project of allProjects) {
      // 组合日期和时间部分为完整的日期时间格式
      const startDateTime = project.scheduleDate && project.startTime ? `${project.scheduleDate} ${project.startTime}:00` : null;

      const endDateTime = project.scheduleDate && project.endTime ? `${project.scheduleDate} ${project.endTime}:00` : null;

      await updateGameEventProject({
        projectId: project.projectId,
        startTime: startDateTime,
        endTime: endDateTime,
        location: project.location,
        groupNum: project.groupNum,
        participateNum: project.participateNum,
        //其他字段
        eventId: defaultEvent.value.eventId,
        projectName: project.projectName,
        projectType: project.projectType,
        // groupType: project.groupType
      } as any);
    }

    ElMessage.success('日程安排保存成功');
    updateScheduleData();
  } catch (error) {
    ElMessage.error('保存日程安排失败');
  }
};

// 删除日程安排
const deleteSchedule = async (project: GameEventProjectVO) => {
  try {
    await ElMessageBox.confirm(`确定要删除项目 "${project.projectName}" 的日程安排吗？`, '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    // 清除该项目的时间安排
    await updateGameEventProject({
      projectId: project.projectId,
      startTime: null,
      endTime: null,
      location: project.location,
      groupNum: project.groupNum,
      participateNum: project.participateNum,
      //其他字段
      eventId: defaultEvent.value.eventId,
      projectName: project.projectName,
      projectType: project.projectType,
      // groupType: project.groupType
    } as any);

    // 更新本地数据
    const group = projectGroups.value.find((g) => {
      const projectTypeDict = game_project_type.value.find((dict: any) => dict.value === project.projectType);
      const type = projectTypeDict ? projectTypeDict.label : '未知类型';
      return g.type === type;
    });
    if (group) {
      const projectItem = group.projects.find((p) => p.projectId === project.projectId);
      if (projectItem) {
        projectItem.scheduleDate = '';
        projectItem.startTime = '';
        projectItem.endTime = '';
      }
    }

    ElMessage.success('日程安排删除成功');
    updateScheduleData();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除日程安排失败');
    }
  }
};

// 根据字典获取项目类型文本
const getProjectTypeLabel = (projectType: string) => {
  const dict = game_project_type.value?.find((item: any) => item.value === projectType);
  return dict ? dict.label : '未知类型';
};

// 导出日程表（使用 HTML 表格转 Excel，支持样式）
const exportSchedule = () => {
  if (scheduleData.value.length === 0) {
    ElMessage.warning('暂无日程安排数据可导出');
    return;
  }

  // 构建带样式的 HTML 表格
  let html = `
    <html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">
    <head>
      <meta charset="UTF-8">
      <!--[if gte mso 9]>
      <xml>
        <x:ExcelWorkbook>
          <x:ExcelWorksheets>
            <x:ExcelWorksheet>
              <x:Name>日程安排</x:Name>
              <x:WorksheetOptions>
                <x:DisplayGridlines/>
              </x:WorksheetOptions>
            </x:ExcelWorksheet>
          </x:ExcelWorksheets>
        </x:ExcelWorkbook>
      </xml>
      <![endif]-->
      <style>
        td, th {
          text-align: center;
          vertical-align: middle;
          border: 1px solid #000;
          padding: 8px;
        }
        th {
          background-color: #E0E0E0;
          font-weight: bold;
        }
      </style>
    </head>
    <body>
      <table>
        <tr>
          <th>日期</th>
          <th>时间</th>
          <th>项目名称</th>
          <th>项目类型</th>
          <th>比赛场地</th>
          <th>分组数</th>
          <th>每组人数</th>
        </tr>
  `;

  scheduleData.value.forEach((item) => {
    html += `
        <tr>
          <td>${item.scheduleDate || ''}</td>
          <td>${item.startTime}-${item.endTime}</td>
          <td>${item.projectName || ''}</td>
          <td>${getProjectTypeLabel(item.projectType)}</td>
          <td>${item.location || ''}</td>
          <td>${item.groupNum || 0}</td>
          <td>${item.participateNum || 0}</td>
        </tr>
    `;
  });

  html += `
      </table>
    </body>
    </html>
  `;

  // 创建 Blob 并下载
  const blob = new Blob([html], { type: 'application/vnd.ms-excel;charset=utf-8' });
  const link = document.createElement('a');
  link.href = URL.createObjectURL(blob);
  link.download = `${defaultEvent.value.eventCode || ''}_赛事日程安排.xls`;
  link.click();
  URL.revokeObjectURL(link.href);
};

onMounted(() => {
  loadDefaultEvent().then(() => {
    // 自动加载默认赛事数据
    if (defaultEvent.value.eventId) {
      loadEventData();
    }
  });
});
</script>

<style scoped>
.flex {
  display: flex;
}

.items-center {
  align-items: center;
}

.justify-between {
  justify-content: space-between;
}

.justify-end {
  justify-content: flex-end;
}

.gap-4 {
  gap: 1rem;
}

.mb-4 {
  margin-bottom: 1rem;
}

.font-bold {
  font-weight: bold;
}

.text-lg {
  font-size: 1.125rem;
}

.text-gray-600 {
  color: #6b7280;
}
</style>
