<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="项目归类" prop="classification">
              <el-select v-model="queryParams.classification" placeholder="请选择项目归类" clearable @change="handleQuery">
                <el-option v-for="dict in game_project_classification" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:gameEventProject:add']"> 新增 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Collection" @click="handleViewProjectLibrary()"> 项目库 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['system:gameEventProject:edit']"
              >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['system:gameEventProject:remove']"
              >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:gameEventProject:export']">导出 </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" :columns="columns" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="gameEventProjectList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" fixed="left" type="index" />
        <el-table-column label="项目id" align="center" fixed="left" prop="projectId" v-if="columns[0].visible" />
        <el-table-column label="项目名称" align="center" fixed="left" prop="projectName" v-if="columns[1].visible" />
        <el-table-column label="项目类型" align="center" prop="projectType" v-if="columns[2].visible">
          <template #default="scope">
            <dict-tag :options="game_project_type" :value="scope.row.projectType || ''" />
          </template>
        </el-table-column>
        <el-table-column label="项目归类" align="center" prop="classification" v-if="columns[3].visible" >
          <template #default="scope">
            <dict-tag :options="game_project_classification" :value="scope.row.classification || '未知'" />
          </template>
        </el-table-column>
        <el-table-column label="比赛场地" align="center" prop="location" v-if="columns[4].visible" />
        <el-table-column label="计算规则" align="center" prop="scoreRule" v-if="columns[5].visible">
          <template #default="scope">
            <dict-tag :options="game_score_type" :value="scope.row.scoreRule || ''" />
          </template>
        </el-table-column>
        <el-table-column label="开始时间" align="center" prop="startTime" width="180" v-if="columns[6].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结束时间" align="center" prop="endTime" width="180" v-if="columns[7].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="裁判组" align="center" prop="refereeGroup" v-if="columns[8].visible">
          <template #default="scope">
            <el-button
              v-if="scope.row.refereeGroups.size > 0"
              type="primary"
              size="small"
              @click="handleViewRefereeGroup(scope.row.refereeGroups, scope.row.projectName)"
            >
              查看裁判组 ({{ scope.row.refereeGroups.length }}人)
            </el-button>
            <span v-else style="color: #999;">暂无裁判</span>
          </template>
        </el-table-column>
        <el-table-column label="参赛人数" align="center" prop="athleteCount" v-if="columns[14].visible">
          <template #default="scope">
            <el-link type="primary" :underline="false" @click="handleViewStats(scope.row, 'athlete')">
              {{ scope.row.athleteCount || 0 }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="代表队数" align="center" prop="teamCount" v-if="columns[15].visible">
          <template #default="scope">
            <el-link type="primary" :underline="false" @click="handleViewStats(scope.row, 'team')">
              {{ scope.row.teamCount || 0 }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="分组数" align="center" prop="groupCount" v-if="columns[16].visible">
          <template #default="scope">
            <el-link type="primary" :underline="false" @click="handleViewStats(scope.row, 'group')">
              {{ scope.row.groupCount || 0 }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="录取名次" align="center" prop="roundType" v-if="columns[9].visible" />
        <el-table-column label="排序方式" align="center" prop="orderType" v-if="columns[10].visible">
          <template #default="scope">
            {{ scope.row.orderType === '0' ? '升序' : '降序' }}
          </template>
        </el-table-column>
        <el-table-column label="积分分值" align="center" prop="scoreValue" v-if="columns[11].visible" />
        <!-- <el-table-column label="奖项" align="center" prop="award" /> -->
        <el-table-column label="比赛轮次" align="center" prop="gameRound" v-if="columns[12].visible">
          <template #default="scope">
            <dict-tag :options="game_round" :value="scope.row.gameRound || ''" />
          </template>
        </el-table-column>
        <el-table-column label="比赛阶段" align="center" prop="gameStage" v-if="columns[13].visible">
          <template #default="scope">
            <dict-tag :options="game_stage" :value="scope.row.gameStage || ''" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:gameEventProject:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:gameEventProject:remove']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改赛事项目对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="gameEventProjectFormRef" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="form.projectName" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="项目类型" prop="projectType">
          <el-select v-model="form.projectType" placeholder="请选择项目类型">
            <el-option v-for="dict in game_project_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="比赛场地" prop="location">
          <el-input v-model="form.location" placeholder="请输入比赛场地" />
        </el-form-item>
        <el-form-item label="归类" prop="classification">
          <el-radio-group v-model="form.classification" style="width: 100%">
            <el-radio v-for="dict in game_project_classification" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="比赛阶段" prop="gameStage">
          <el-radio-group v-model="form.gameStage" style="width: 100%">
            <el-radio v-for="dict in game_stage" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="比赛轮次" prop="gameRound">
          <el-radio-group v-model="form.gameRound" style="width: 100%">
            <el-radio v-for="dict in game_round" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="计算规则" prop="scoreRule">
          <el-select v-model="form.scoreRule" placeholder="请选择计算规则" style="width: 100%">
            <el-option v-for="dict in game_score_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="排序方式" prop="orderType">
          <el-radio-group v-model="form.orderType">
            <el-radio value="0">升序</el-radio>
            <el-radio value="1">降序</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="限报人数" prop="limitPerson">
          <template #label>
            <span>
              <el-tooltip content="项目限制报名的运动员数量，0表示不限。" placement="top">
                <el-icon>
                  <question-filled />
                </el-icon>
              </el-tooltip>
            限报人数</span>
          </template>
          <el-input-number v-model="form.limitPerson" :min="0" :max="100" size="small" controls-position="right" />
        </el-form-item>
        <el-form-item label="录取名次" prop="roundType">
          <el-input v-model="form.roundType" placeholder="请输入录取名次" />
        </el-form-item>
        <el-form-item label="积分分值" prop="scoreValue">
          <template #label>
            <span>
              <el-tooltip content="各值之间以英文逗号分隔" placement="top">
                <el-icon>
                  <question-filled />
                </el-icon>
              </el-tooltip>
            积分</span>
          </template>
          <el-input v-model="form.scoreValue" placeholder="请输入名次对应的积分" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable v-model="form.startTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker clearable v-model="form.endTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择结束时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm()">确 定</el-button>
          <el-button v-if="!form.projectId" :loading="buttonLoading" type="success" @click="submitForm(true)">保存并继续</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 裁判组查看对话框 -->
    <RefereeGroupDialog ref="refereeGroupDialogRef" />

    <!-- 项目库查看对话框 -->
    <ProjectLibraryDialog ref="projectLibraryDialog" @confirm="handleLibraryConfirm" />

    <!-- 统计详情对话框 -->
    <StatsDetailDialog ref="statsDetailDialogRef" />
  </div>
</template>

<script setup name="GameEventProject" lang="ts">
import {
  listGameEventProject,
  listGameEventProjectWithStats,
  getGameEventProject,
  delGameEventProject,
  addGameEventProject,
  updateGameEventProject,
  BatchAddProject
} from '@/api/system/gameEventProject';
import { listGameEventGroup } from '@/api/system/gameEventGroup';
import { GameEventProjectVO, GameEventProjectQuery, GameEventProjectForm } from '@/api/system/gameEventProject/types';
import RefereeGroupDialog from './RefereeGroupDialog.vue';
import ProjectLibraryDialog from './ProjectLibraryDialog.vue';
import StatsDetailDialog from './StatsDetailDialog.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { game_score_type, game_project_type, game_project_classification, game_round, game_stage } = toRefs<any>(proxy?.useDict('game_score_type', 'game_project_type', 'game_project_classification', 'game_round', 'game_stage'));

const gameEventGroupList = ref<any[]>([]); // ���·����б�

const gameEventProjectList = ref<GameEventProjectVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const gameEventProjectFormRef = ref<ElFormInstance>();

// 定义 RefereeGroupDialog 组件的类型
interface RefereeGroupDialogInstance {
  openDialog: (refereeGroups: string[], projectName: string) => void;
}
// 定义 ProjectLibraryDialog 组件的类型
interface ProjectLibraryDialogInstance {
  openDialog: () => void;
}

const refereeGroupDialogRef = ref<(InstanceType<typeof RefereeGroupDialog> & RefereeGroupDialogInstance) | null>(null);
const projectLibraryDialog = ref<(InstanceType<typeof ProjectLibraryDialog> & ProjectLibraryDialogInstance) | null>(null);
const statsDetailDialogRef = ref<any>(null);

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 列显隐数据
const columns = ref<FieldOption[]>([
  { key: 0, label: '项目id', visible: false },
  { key: 1, label: '项目名称', visible: true },
  { key: 2, label: '项目类型', visible: true },
  { key: 3, label: '归类', visible: true },
  { key: 4, label: '比赛场地', visible: true },
  { key: 5, label: '计算规则', visible: true },
  { key: 6, label: '开始时间', visible: true },
  { key: 7, label: '结束时间', visible: true },
  { key: 8, label: '裁判组', visible: true },
  { key: 9, label: '录取名次', visible: true },
  { key: 10, label: '积分分值', visible: true },
  { key: 11, label: '排序方式', visible: true },
  { key: 12, label: '比赛轮次', visible: true },
  { key: 13, label: '比赛阶段', visible: true },
  { key: 14, label: '参赛人数', visible: true },
  { key: 15, label: '代表队数', visible: true },
  { key: 16, label: '分组数', visible: true }
]);

const initFormData: GameEventProjectForm = {
  projectId: undefined,
  eventId: undefined,
  projectName: undefined,
  projectType: undefined,
  classification: '0',
  refereeGroups: undefined,
  location: undefined,
  startTime: undefined,
  endTime: undefined,
  groupNum: undefined,
  participateNum: undefined,
  limitPerson: 0,
  roundType: undefined,
  orderType: '0',
  scoreRule: undefined,
  scoreValue: undefined,
  award: undefined,
  gameRound: undefined,
  gameStage: undefined,
  status: '0',
  remark: undefined
};
const data = reactive<PageData<GameEventProjectForm, GameEventProjectQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    classification: undefined,
    orderByColumn: undefined,
    isAsc: undefined,
  },
  rules: {
    projectName: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
    projectType: [{ required: true, message: '项目类型不能为空', trigger: 'change' }],
    classification: [{ required: true, message: '归类不能为空', trigger: 'change' }],
    orderType: [{ required: true, message: '排序方式不能为空', trigger: 'change' }],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询赛事项目列表 */
const getList = async () => {
  loading.value = true;
  const res = await listGameEventProjectWithStats(queryParams.value);
  gameEventProjectList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 查询赛事分组列表 */
const getGameEventGroupList = async () => {
  const res = await listGameEventGroup({
    pageNum: 1,
    pageSize: 10,
    orderByColumn: undefined,
    isAsc: undefined,
  });
  gameEventGroupList.value = res.data;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  gameEventProjectFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: any[]) => {
  ids.value = selection.map(item => item.projectId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加赛事项目';
};

/** 修改按钮操作 */
const handleUpdate = (row?: GameEventProjectVO) => {
  reset();
  const projectId = row?.projectId || ids.value.at(0);
  getGameEventProject(projectId).then(response => {
    Object.assign(form.value, response.data);
    dialog.visible = true;
    dialog.title = '修改赛事项目';
  });
};

/** 提交按钮 */
const submitForm = (isContinue = false) => {
  gameEventProjectFormRef.value?.validate(valid => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.projectId !== undefined) {
        updateGameEventProject(form.value).then(response => {
          proxy?.$modal.msgSuccess('修改成功');
          dialog.visible = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        addGameEventProject(form.value).then(response => {
          proxy?.$modal.msgSuccess('新增成功');
          if (isContinue) {
            // 保存并继续：不关闭弹窗，并确保 projectId 为空
            form.value.projectId = undefined;
          } else {
            dialog.visible = false;
          }
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
};

/** 删除按钮操作 */
const handleDelete = (row?: GameEventProjectVO) => {
  const projectIds = row?.projectId || ids.value;
  proxy?.$modal.confirm('是否确认删除赛事项目ID为"' + projectIds + '"的数据项？').then(function () {
    return delGameEventProject(projectIds);
  }).then(() => {
    getList();
    proxy?.$modal.msgSuccess('删除成功');
  }).catch(() => {proxy?.$modal.msgSuccess('删除失败');});
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/gameEventProject/export',
    {
      ...queryParams.value
    },
    `项目详情_${new Date().getTime()}.xlsx`
  );
};

/** 查看裁判组 */
const handleViewRefereeGroup = (refereeGroups: string[], projectName: string) => {
  refereeGroupDialogRef.value?.openDialog(refereeGroups, projectName);
};

/** 查看项目库 */
const handleViewProjectLibrary = () => {
  projectLibraryDialog.value?.openDialog();
};

/** 查看统计详情 */
const handleViewStats = (row: GameEventProjectVO, type: 'athlete' | 'team' | 'group') => {
  statsDetailDialogRef.value?.openDialog(row.projectId, row.projectName, type);
};

/** 处理项目库选择确认 */
const handleLibraryConfirm = async (projects: GameEventProjectVO[]) => {
  try {
      // 调用添加接口
      await BatchAddProject(projects);
    } catch (error) {
      console.error('添加项目失败:', error);
      proxy?.$modal.msgError(`添加项目失败`);
    }
  
  proxy?.$modal.msgSuccess(`成功添加${projects.length}个项目`);
  getList(); // 刷新列表
};

onMounted(() => {
  getList();
  // getGameEventGroupList();
});

</script>
