<template>
  <el-dialog :title="dialog.title" v-model="dialog.visible" width="800px" append-to-body>
    <el-form ref="refereeFormRef" :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 type="password" v-model="form.password" placeholder="请输入密码" show-password />
      </el-form-item>
      <el-form-item label="赛事项目" prop="projectList2">
        <!-- 合并为一个 el-transfer -->
        <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 @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="RefereeForm" lang="ts">
import { reactive, ref, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { listGameEventProject, updateGameEventProject, getGameEventProject } from '@/api/system/gameEventProject';
import { addGameReferee, updateGameReferee, getGameReferee } from '@/api/system/gameReferee';

const dialog = reactive({
  visible: false,
  title: '添加裁判'
});

const form = reactive({
  refereeId: undefined as string | number | undefined,
  eventId: undefined as string | number | undefined,
  name: undefined,
  account: undefined,
  password: undefined,
  projectList2: [] as number[]
});

const rules = {
  name: [
    { required: true, message: '请输入裁判姓名', trigger: 'blur' }
  ],
  account: [
    { required: true, message: '请输入账号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
};

const refereeFormRef = ref<any>(null);
const allProjects = ref<{key: string, label: string }[]>([]);
const eventId = ref<string>(''); // 新增：用于存储赛事ID

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

const loadProjects = async () => {
  try {
    const res = await listGameEventProject({
      eventId: eventId.value, // 使用传递进来的赛事ID
      pageNum: 1,
      pageSize: 1000, // 增加页面大小，确保获取所有项目
      orderByColumn: undefined,
      isAsc: undefined,
    });
    
    allProjects.value = res.rows.map(item => ({
      key: String(item.projectId),
      label: item.projectName || '未命名项目' // 只显示项目名称，不拼接组别
    }));
    
  } catch (error) {
    console.error('加载项目失败:', error);
    ElMessage.error('加载项目失败');
  }
};

const openDialog = async (eventIdParam: string, refereeId?: string | number) => {
  try {
    
    if (!eventIdParam) {
      ElMessage.error('赛事ID不能为空');
      return;
    }
    
    eventId.value = eventIdParam; // 接收并设置赛事ID
    
    // 重置表单数据
    reset();
    
    // 如果是编辑模式，加载裁判数据
    if (refereeId) {
      const res = await getGameReferee(refereeId);
      Object.assign(form, res.data);
      
      // 处理项目列表数据格式
      if (Array.isArray(res.data.projectList2)) {
        form.projectList2 = res.data.projectList2.map(id => id);
      } else {
        form.projectList2 = [];
      }
      
      dialog.title = '修改裁判';
    } else {
      dialog.title = '添加裁判';
    }
    
    await loadProjects();
    dialog.visible = true;
  } catch (error) {
    console.error('打开对话框失败:', error);
    ElMessage.error('打开对话框失败');
  }
};

const reset = () => {
  Object.assign(form, {
    refereeId: undefined,
    eventId: undefined,
    name: undefined,
    account: undefined,
    password: undefined,
    projectList2: []
  });
  refereeFormRef.value?.resetFields();
};

const cancel = () => {
  dialog.visible = false;
};

const submitForm = async () => {
  const valid = await refereeFormRef.value?.validate();
  if (valid) {
    try {
      const submitForm: any = { ...form, eventId: eventId.value };
      
      if (form.refereeId) {
        // 编辑模式
        await updateGameReferee(submitForm);
        ElMessage.success('修改成功');
      } else {
        // 添加模式
        const refereeResult = await addGameReferee(submitForm);
        
        // 获取新添加的裁判ID
        const newRefereeId = refereeResult.data?.refereeId || null;
        
        // 更新所选项目的裁判组字段
        if (newRefereeId && form.projectList2.length > 0) {
          for (const projectId of form.projectList2) {
            // 获取当前项目信息
            const projectRes = await getGameEventProject(projectId);
            
            if (projectRes) {
              const project = projectRes.data;
              // 直接使用 refereeGroups 字段（字符串数组）
              let currentRefereeGroups = project.refereeGroups || [];
              // 检查是否已存在该裁判ID，避免重复添加
              if (!currentRefereeGroups.includes(newRefereeId)) {
                currentRefereeGroups.push(newRefereeId);
              }
              
              // 更新项目表中的裁判组字段
              await updateGameEventProject({
                ...project,
                refereeGroups: currentRefereeGroups
              });
            }
          }
        }
        
        ElMessage.success('添加成功');
      }
      
      dialog.visible = false;
    } catch (error) {
      console.error('操作失败:', error);
      ElMessage.error('操作失败');
    }
  }
};

defineExpose({ openDialog });
</script>

<!-- 添加默认导出以解决导入问题 -->
<script lang="ts">
import { defineComponent } from 'vue';

export default defineComponent({
  name: 'RefereeForm'
});
</script>