<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="groupType">
              <el-select v-model="queryParams.groupType" placeholder="请选择项目组别" clearable @change="handleQuery">
                <el-option v-for="group in gameEventGroupList" :key="group.groupName" :label="group.groupName" :value="group.groupName" />
              </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="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" prop="projectId" v-if="columns[0].visible" />
        <el-table-column label="项目名称" align="center" 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="groupType" v-if="columns[3].visible" /> -->
        <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}') }}</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}') }}</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" 
              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="groupNum" />
        <el-table-column label="参赛人数" align="center" prop="participateNum" /> -->
        <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="timePoint" />
        <el-table-column label="控制盒编号" align="center" prop="boxCode" />
        <el-table-column label="状态" align="center" prop="status" />
        <el-table-column label="备注" align="center" prop="remark" /> -->
        <el-table-column label="操作" align="center" 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="80px">
        <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="groupNum">
          <el-input v-model="form.groupNum" placeholder="请输入参赛组数" />
        </el-form-item>
        <el-form-item label="参赛人数" prop="participateNum">
          <el-input v-model="form.participateNum" placeholder="请输入参赛人数" />
        </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="scoreValue">
          <el-input v-model="form.scoreValue" placeholder="请输入积分分值" />
        </el-form-item>
        <el-form-item label="轮次" prop="roundType">
          <el-input v-model="form.roundType" 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-item label="奖项" prop="award">
          <el-input v-model="form.award" placeholder="请输入奖项" />
        </el-form-item>
        <el-form-item label="计时点名称" prop="timePoint">
          <el-input v-model="form.timePoint" placeholder="请输入计时点名称" />
        </el-form-item>
        <el-form-item label="控制盒编号" prop="boxCode">
          <el-input v-model="form.boxCode" placeholder="请输入控制盒编号" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 裁判组查看对话框 -->
    <RefereeGroupDialog ref="refereeGroupDialogRef" />
  </div>
</template>

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

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

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;
}

const refereeGroupDialogRef = ref<(InstanceType<typeof RefereeGroupDialog> & RefereeGroupDialogInstance) | null>(null);

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

// 列显隐数据
const columns = ref<FieldOption[]>([
  { key: 0, label: '主键', 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 },
]);

const initFormData: GameEventProjectForm = {
  projectId: undefined,
  eventId: undefined,
  projectName: undefined,
  projectType: undefined,
  groupType: undefined,
  refereeGroups: undefined,
  location: undefined,
  startTime: undefined,
  endTime: undefined,
  groupNum: undefined,
  participateNum: undefined,
  roundType: undefined,
  orderType: undefined,
  scoreRule: undefined,
  scoreValue: undefined,
  award: undefined,
  timePoint: undefined,
  boxCode: undefined,
  status: undefined,
  remark: undefined
};
const data = reactive<PageData<GameEventProjectForm, GameEventProjectQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderByColumn: undefined,
    isAsc: undefined,
  },
  rules: {
    projectName: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
    projectType: [{ required: true, message: '项目类型不能为空', trigger: 'change' }],
    groupType: [{ required: true, message: '项目组别不能为空', trigger: 'change' }],
    location: [{ required: true, message: '比赛场地不能为空', trigger: 'blur' }]
  }
});

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

/** 查询赛事项目列表 */
const getList = async () => {
  loading.value = true;
  const res = await listGameEventProject(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 = () => {
  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('新增成功');
          dialog.visible = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
};

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

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

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

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

</script>
