<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="name">
              <el-input v-model="queryParams.name" placeholder="请输入裁判姓名" clearable @keyup.enter="handleQuery" />
            </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:gameReferee:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['system:gameReferee:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['system:gameReferee:remove']">删除</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:gameReferee:export']">导出</el-button>
          </el-col> -->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="gameRefereeList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="裁判ID" align="center" prop="refereeId" v-if="columns[0].visible" />
        <el-table-column label="裁判姓名" align="center" prop="name" v-if="columns[1].visible" />
        <el-table-column label="账号" align="center" prop="account" v-if="columns[2].visible" />
        <el-table-column label="密码" align="center" prop="password" v-if="columns[3].visible" />
        <el-table-column label="项目" align="center" v-if="columns[4].visible">
          <template #default="scope">
            <span>{{ scope.row.projectNameList || '无' }}</span>
          </template>
        </el-table-column>
        <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:gameReferee:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:gameReferee:remove']"></el-button>
            </el-tooltip>
            <el-tooltip content="生成二维码" placement="top">
              <el-button link type="primary" icon="FullScreen" @click="handleGenerateQRCode(scope.row)" v-hasPermi="['system:gameReferee:edit']">
                裁判码
              </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="800px" append-to-body>
      <el-form ref="gameRefereeFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="裁判姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入裁判姓名" />
        </el-form-item>
        <el-form-item label="账号" prop="account">
          <el-input v-model="form.account" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="赛事项目" prop="projectList2">
          <!-- 赛事项目穿梭框 -->
          <el-transfer
            v-model="projectList2Str"
            :data="allProjects"
            :titles="['可选项目', '已选项目']"
            :button-texts="['移除', '添加']"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 二维码对话框 -->
    <el-dialog :title="qrCodeDialog.title" v-model="qrCodeDialog.visible" width="400px" append-to-body>
      <div class="qr-code-container" style="text-align: center; padding: 20px;">
        <img :src="qrCodeData" alt="QR Code" v-if="qrCodeData" style="width: 200px; height: 200px;" />
        <p style="margin-top: 15px;">裁判: {{ currentReferee.name }}</p>
        <p>账号: {{ currentReferee.account }}</p>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleDownloadQRCode">下载二维码</el-button>
          <el-button @click="qrCodeDialog.visible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="GameReferee" lang="ts">
import { listGameReferee, getGameReferee, delGameReferee, addGameReferee, updateGameReferee, generateRefereeQRCode } from '@/api/system/gameReferee';
import { getGameEventProject, listGameEventProject, updateGameEventProject } from '@/api/system/gameEventProject';
import { GameRefereeVO, GameRefereeQuery, GameRefereeForm } from '@/api/system/gameReferee/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const gameRefereeList = ref<GameRefereeVOExt[]>([]);
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 allProjects = ref<{key: string, label: string }[]>([]); // 添加项目数据

// 列显隐数据
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 }
]);

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

const showList = reactive({
  projectNameList: [],
  groupList: []
});

// 二维码对话框数据
const qrCodeDialog = reactive({
  visible: false,
  title: '裁判二维码'
});

const currentReferee = ref<GameRefereeVO>({} as GameRefereeVO);
const qrCodeData = ref('');

// 扩展GameRefereeVO类型，添加用于展示的projectNameList属性
interface GameRefereeVOExt extends GameRefereeVO {
  projectNameList?: string;
}

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

// 定义表单数据结构
const form = reactive({
  refereeId: undefined as string | number | undefined,
  eventId: undefined as string | number | undefined,
  name: undefined,
  groupName: undefined,
  account: undefined,
  password: undefined,
  // projectList: [] as string[], // 存储所负责的项目
  projectList2: [] as number[], // 存储所负责的项目
  refereeCode: undefined,
  createTime: undefined,
  updateTime: undefined,
});

const queryParams = reactive<GameRefereeQuery>({
  pageNum: 1,
  pageSize: 10,
  name: undefined,
  params: {},
  orderByColumn: undefined,
  isAsc: undefined,
});

const rules = {
  account: [
    { required: true, message: "账号不能为空", trigger: "blur" }
  ],
  password: [
    { required: true, message: "密码不能为空", trigger: "blur" }
  ],
}

/** 查询裁判列表 */
const getList = async () => {
  loading.value = true;
  
  // 查询裁判列表
  const res = await listGameReferee(queryParams);
  // 加载所有项目信息
  const projectRes = await listGameEventProject({
        pageNum: 1,
        pageSize: 10,
        orderByColumn: undefined,
        isAsc: undefined,
      });
  
  // 为每个裁判添加项目名称列表用于展示
  for (const referee of res.rows) {
    if (referee.projectList2) {
      // 获取项目ID数组
      // const projectIds = referee.projectList.split(',').filter(id => id);
      const projectIds = referee.projectList2.filter(id => id);
      
      // 从所有项目中筛选出在projectIds中存在的项目，并提取它们的label值（项目名称）
      const projectNames = projectRes.rows
        .filter(project => projectIds.map(id => Number(id)).includes(Number(project.projectId)))
        .map(project => project.projectName);
      
      // 添加projectNameList属性到裁判对象中用于展示
      (referee as any).projectNameList = projectNames.join(', ');
    }
  }
  
  gameRefereeList.value = res.rows as GameRefereeVOExt[];
  total.value = res.total;
  loading.value = false;
}

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

/** 表单重置 */
const reset = () => {
  Object.assign(form, {
    refereeId: undefined,
    eventId: undefined,
    name: undefined,
    groupName: undefined,
    account: undefined,
    password: undefined,
    // projectList: [],
    projectList2: [],
    refereeCode: undefined,
    createTime: undefined,
    updateTime: undefined,
  });
  gameRefereeFormRef.value?.resetFields();
}

// 添加一个计算属性用于处理projectList2的类型转换
const projectList2Str = computed({
  get: () => form.projectList2.map(id => String(id)),
  set: (value) => {
    form.projectList2 = value.map(id => Number(id));
  }
});

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

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

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

/** 获取赛事项目列表 */
const loadProjects = async () => {
  const res = await listGameEventProject({
    pageNum: 1,
    pageSize: 1000,
    orderByColumn: '',
    isAsc: ''
  });
  // 赛事项目穿梭框可选数据拼接
  allProjects.value = res.rows.map(item => ({
    key: String(item.projectId),
    label: `${item.projectName}` 
  }));
};

/** 新增按钮操作 */
const handleAdd = async () => {
  reset();
  await loadProjects();
  dialog.visible = true;
  dialog.title = "添加裁判";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: GameRefereeVO) => {
  reset();
  const _refereeId = row?.refereeId || ids.value[0]
  const res = await getGameReferee(_refereeId);
  Object.assign(form, res.data);

  // 等待项目列表加载完成
  await loadProjects();

  // 处理项目列表数据格式
  if (Array.isArray(res.data.projectList2)) {
    // 将数字数组转换为字符串数组，以匹配 allProjects 的 key 类型
    form.projectList2 = res.data.projectList2.map(id => id);
  } else {
    form.projectList2 = [];
  }

  dialog.visible = true;
  dialog.title = "修改裁判";
}

/** 提交按钮 */
const submitForm = async () => {
  const valid = await gameRefereeFormRef.value?.validate();
  if (valid) {
    buttonLoading.value = true;
    const submitForm: any = { ...form };
    if (form.projectList2) {
      submitForm.projectList2 = form.projectList2;
    }

    try {
      if (form.refereeId) {
        await updateGameReferee(submitForm as GameRefereeForm);
      } else {
        await addGameReferee(submitForm as GameRefereeForm);
      }
      
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    } catch (error) {
      console.error("操作失败:", error);
      proxy?.$modal.msgError("操作失败");
    } finally {
      buttonLoading.value = false;
    }
  }
}

/** 删除按钮操作 */
const handleDelete = async (row?: GameRefereeVO) => {
  const _refereeId = row?.refereeId || ids.value;
  await proxy?.$modal.confirm('是否确认删除裁判编号为"' + _refereeId + '"的数据项？').finally(() => loading.value = false);
  
  try {
    await delGameReferee(_refereeId);
    
    // 如果是单个删除，需要从项目表中移除该裁判
    if (row) {
      const refereeId = row.refereeId;
      if (row.projectList2) {
        const projectIds = row.projectList2.filter(id => id);
        
        for (const projectId of projectIds) {
          // 获取当前项目信息
          const getProject = await getGameEventProject(projectId);
          const project = getProject.data;
          if (project) {
            
            let currentRefereeGroups = project.refereeGroups || [];
            
            // 从裁判组中移除该裁判ID
            if (currentRefereeGroups) {
              const refereeIds = currentRefereeGroups.filter(id => id !== refereeId);
              // 更新项目表中的裁判组字段
              await updateGameEventProject({
                ...project,
                refereeGroups: refereeIds
              });
            }
          }
        }
      }
    }
    
    proxy?.$modal.msgSuccess("删除成功");
    await getList();
  } catch (error) {
    console.error('删除裁判失败:', error);
    proxy?.$modal.msgError("删除失败");
  }
}

/** 生成裁判二维码 */
const handleGenerateQRCode = async (row: GameRefereeVO) => {
  currentReferee.value = row;
  
  try {
    // 生成二维码数据
    const res = await generateRefereeQRCode(row.refereeId);
    qrCodeData.value = res.data;
    console.log('二维码数据:', res);
    qrCodeDialog.visible = true;
  } catch (error) {
    proxy?.$modal.msgError("生成二维码失败");
  }
};

/** 下载二维码 */
const handleDownloadQRCode = () => {
  if (!qrCodeData.value) return;
  
  const link = document.createElement('a');
  link.href = qrCodeData.value;
  link.download = `裁判二维码_${currentReferee.value.name}.png`;
  link.click();
  proxy?.$modal.msgSuccess("二维码下载成功");
};

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

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

</script>
