<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"></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="eventId" /> -->
        <el-table-column label="裁判ID" align="center" prop="refereeId" v-if="true" />
        <el-table-column label="裁判姓名" align="center" prop="name" />
        <el-table-column label="账号" align="center" prop="account" />
        <el-table-column label="密码" align="center" prop="password" />
        <!-- <el-table-column label="组别" align="center" prop="groupList" /> -->
        <el-table-column label="项目" align="center">
          <template #default="scope">
            <span>{{ scope.row.projectNameList || '无' }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="裁判码" align="center" prop="refereeCode" /> -->
        <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="projectList">
          <!-- 赛事项目穿梭框 -->
          <el-transfer
            v-model="form.projectList"
            :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 } from '@/api/system/gameReferee';
import { listGameEventProject } from '@/api/system/gameEventProject';
import { GameRefereeVO, GameRefereeQuery, GameRefereeForm } from '@/api/system/gameReferee/types';
import { toDataURL } from 'qrcode';
import { getDefaultEvent } from '@/api/system/gameEvent';
import { GameEventVO } from '@/api/system/gameEvent/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const defaultEvent = ref<GameEventVO | null>(null); // 默认赛事信息

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 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: ''
});

// 定义表单数据结构，参考athlete.vue的实现方式
const form = reactive({
  refereeId: undefined as string | number | undefined,
  eventId: undefined as string | number | undefined,
  name: '',
  groupName: '',
  account: '',
  password: '',
  projectList: [] as string[], // 存储所负责的项目
  refereeCode: '',
  createTime: '',
  updateTime: ''
});

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

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

// 添加额外的ref用于处理默认事件ID
const defaultEventId = computed(() => defaultEvent.value?.eventId);

// 监听默认事件变化
watchEffect(() => {
  if (defaultEventId.value) {
    form.eventId = defaultEventId.value;
    queryParams.eventId = defaultEventId.value;
  }
});

/** 获取默认赛事 */
const getDefaultEventInfo = async () => {
  try {
    const res = await getDefaultEvent();
    defaultEvent.value = res.data;
  } catch (error) {
    proxy?.$modal.msgError('获取默认赛事信息失败');
  }
};

/** 查询裁判列表 */
const getList = async () => {
  if (!queryParams.eventId) {
    proxy?.$modal.msgWarning('未获取到默认赛事信息');
    loading.value = false;
    return;
  }

  loading.value = true;
  const res = await listGameReferee(queryParams);
  
  // 为每个裁判添加项目名称列表用于展示
  for (const referee of res.rows) {
    if (referee.projectList) {
      // 加载该项目对应的赛事的所有项目信息
      const projectRes = await listGameEventProject({ 
        eventId: referee.eventId,
        pageNum: 1,
        pageSize: 1000
      });
      
      // 获取项目ID数组
      const projectIds = referee.projectList.split(',').filter(id => id);
      
      // 从所有项目中筛选出在projectIds中存在的项目，并提取它们的label值（项目名称）
      const projectNames = projectRes.rows
        .filter(project => projectIds.includes(String(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: '',
    groupName: '',
    account: '',
    password: '',
    projectList: [],
    refereeCode: '',
    createTime: '',
    updateTime: ''
  });
  gameRefereeFormRef.value?.resetFields();
}

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  // 保留默认赛事ID
  queryParams.eventId = defaultEvent.value?.eventId;
  handleQuery();
}

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

/** 获取赛事项目列表 */
const loadProjects = async (eventId: string | number) => {
  // if (!eventId) {
  //   allProjects.value = [];
  //   return;
  // }
  const res = await listGameEventProject({ 
    eventId: eventId,
    pageNum: 1,
    pageSize: 1000
  });
  // 赛事项目穿梭框可选数据拼接
  allProjects.value = res.rows.map(item => ({
    key: String(item.projectId),
    label: `${item.projectName}-${item.groupType}` // 根据规范，只显示项目名称，不拼接组别
  }));

};

/** 新增按钮操作 */
const handleAdd = async () => {
  reset();
  // 监听赛事ID变化，加载对应项目
  watch(() => form.eventId, async (newVal) => {
    await loadProjects(newVal);
  }, { once: true });
  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(form.eventId);
  
  // 处理项目列表数据格式，参考athlete.vue的实现方式
  if (res.data.projectList && typeof res.data.projectList === 'string') {
    form.projectList = res.data.projectList.split(',').filter(id => id);
  } else if (Array.isArray(res.data.projectList)) {
    form.projectList = res.data.projectList;
  } else {
    form.projectList = [];
  }
  
  dialog.visible = true;
  dialog.title = "修改裁判";
}

/** 提交按钮 */
const submitForm = async () => {
  const valid = await gameRefereeFormRef.value?.validate();
  if (valid) {
    buttonLoading.value = true;
    // 提交前处理项目列表数据格式，参考athlete.vue的实现方式
    const submitForm: any = { ...form };
    if (Array.isArray(form.projectList)) {
      submitForm.projectList = form.projectList.join(',');
    }

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

/** 删除按钮操作 */
const handleDelete = async (row?: GameRefereeVO) => {
  const _refereeIds = row?.refereeId || ids.value;
  await proxy?.$modal.confirm('是否确认删除裁判编号为"' + _refereeIds + '"的数据项？').finally(() => loading.value = false);
  await delGameReferee(_refereeIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 生成裁判二维码 */
const handleGenerateQRCode = async (row: GameRefereeVO) => {
  currentReferee.value = row;
  // 生成二维码数据，可以包含裁判的基本信息
  const qrData = {
    eventId: row.eventId,
    refereeId: row.refereeId,
    name: row.name,
    account: row.account,
    password: row.password,
    projectList: row.projectList,
  };
  
  try {
    qrCodeData.value = await toDataURL(JSON.stringify(qrData), { width: 200 });
    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(() => {
  getDefaultEventInfo().then(() => {
    getList();
  });
});
</script>
