<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="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="projectIds">
        <!-- 合并为一个 el-transfer -->
        <el-transfer
          v-model="form.projectIds"
          :data="allProjects"
          :titles="['可选项目', '已选项目']"
          :button-texts="['移除', '添加']"
        />
      </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 } from 'vue';
import { ElMessage } from 'element-plus';
import { listGameEventProject } from '@/api/system/gameEventProject';
import { addGameReferee } from '@/api/system/gameReferee';

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

const form = reactive({
  account: '',
  password: '',
  projectIds: [] as string[]
});

const rules = {
  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

const loadProjects = async () => {
  const res = await listGameEventProject({
    eventId: eventId.value, // 使用传递进来的赛事ID
    pageNum: 1,
    pageSize: 1000,
    orderByColumn: '',
    isAsc: ''
  });
  allProjects.value = res.rows.map(item => ({
    key: String(item.projectId),
    label: `${item.projectName} - ${item.groupType}`
  }));
};

const openDialog = async (eventIdParam: string) => {
  eventId.value = eventIdParam; // 接收并设置赛事ID
  await loadProjects();
  dialog.visible = true;
};

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

// 修改: 确保 form 在提交时包含 eventId
const submitForm = () => {
  refereeFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 在 form 中添加 eventId
        const formData = { ...form, eventId: eventId.value };
        await addGameReferee(formData);
        ElMessage.success('添加成功');
        dialog.visible = false;
      } catch (error) {
        ElMessage.error('添加失败');
      }
    }
  });
};

defineExpose({ openDialog });
</script>

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

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