<template>
  <el-dialog
    v-model="visible"
    title="项目库"
    width="80%"
    :before-close="handleClose"
    append-to-body
  >
    <div class="project-library">
      <!-- 搜索区域 -->
      <div class="search-area mb-4">
        <el-form :model="searchForm" :inline="true">
          <el-form-item label="来源赛事">
            <el-select
              v-model="searchForm.eventId"
              placeholder="请选择来源赛事"
              filterable
              clearable
              @change="handleSearch"
            >
              <el-option
                v-for="event in eventList"
                :key="event.eventId"
                :label="event.eventName"
                :value="event.eventId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="项目名称">
            <el-input
              v-model="searchForm.projectName"
              placeholder="请输入项目名称"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="项目类型">
            <el-select
              v-model="searchForm.projectType"
              placeholder="请选择项目类型"
              filterable
              clearable
              @change="handleSearch"
            >
              <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="归类">
            <el-select
              v-model="searchForm.classification"
              placeholder="请选择归类"
              filterable
              clearable
              @change="handleSearch"
            >
              <el-option
                v-for="dict in game_project_classification"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item>
            <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
            <el-button icon="Refresh" @click="resetSearch">重置</el-button>
          </el-form-item> -->
        </el-form>
      </div>

      <!-- 项目列表 -->
      <el-table
        v-loading="loading"
        :data="projectList"
        row-key="projectId"
        @selection-change="handleSelectionChange"
        height="400"
        border
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="项目名称" prop="projectName" min-width="120" />
        <el-table-column label="项目类型" prop="projectType" width="100">
          <template #default="scope">
            <dict-tag :options="game_project_type" :value="scope.row.projectType || '-'" />
          </template>
        </el-table-column>
        <el-table-column label="归类" prop="classification" width="100">
          <template #default="scope">
            <dict-tag :options="game_project_classification" :value="scope.row.classification || '未知'" />
          </template>
        </el-table-column>
        <el-table-column label="比赛场地" prop="location" min-width="120" />
        <el-table-column label="参赛性别" align="center" width="80" prop="gender">
          <template #default="scope">
            <dict-tag :options="sys_group_sex" :value="scope.row.gender || '-'" />
          </template>
        </el-table-column>
        <el-table-column label="比赛阶段" prop="gameStage" width="100">
          <template #default="scope">
            <dict-tag :options="game_stage" :value="scope.row.gameStage || '-'" />
          </template>
        </el-table-column>
        <el-table-column label="比赛轮次" prop="gameRound" width="100">
          <template #default="scope">
            <dict-tag :options="game_round" :value="scope.row.gameRound || '-'" />
          </template>
        </el-table-column>
        <el-table-column label="成绩类型" prop="scoreRule" width="100">
          <template #default="scope">
            <dict-tag :options="game_score_type" :value="scope.row.scoreRule || '-'" />
          </template>
        </el-table-column>
        <el-table-column label="排名方式" prop="orderType" :show-overflow-tooltip="true" width="100">
          <template #default="scope">
            <template v-if="scope.row.orderType">
              <dict-tag :options="game_order_type" :value="scope.row.orderType.split(',')" />
            </template>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column label="录取名次" prop="roundType" width="100" />
        <el-table-column label="积分分值" prop="scoreValue" width="120" />
        <el-table-column label="来源赛事" prop="eventName" min-width="120" :show-overflow-tooltip="true" />
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="searchForm.pageNum"
        v-model:limit="searchForm.pageSize"
        @pagination="getProjectList"
      />
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          :disabled="selectedProjects.length === 0"
          @click="handleConfirm"
        >
          确定选择 ({{ selectedProjects.length }})
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="ProjectLibraryDialog" lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { listAllGameEventProject } from '@/api/system/gameEventProject';
import { listGameEvent } from '@/api/system/gameEvent';
import { GameEventProjectVO, GameEventProjectQuery } from '@/api/system/gameEventProject/types';
import { GameEventVO } from '@/api/system/gameEvent/types';

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

const visible = ref(false);
const loading = ref(false);
const projectList = ref<GameEventProjectVO[]>([]);
const selectedProjects = ref<GameEventProjectVO[]>([]);
const total = ref(0);
const eventList = ref<GameEventVO[]>([]);

const searchForm = reactive<GameEventProjectQuery>({
  pageNum: 1,
  pageSize: 10,
  eventId: undefined,
  projectName: undefined,
  projectType: undefined,
  classification: undefined,
  orderByColumn: undefined,
  isAsc: undefined,
});

// 打开对话框
const openDialog = () => {
  visible.value = true;
  resetSearch();
  getProjectList();
};

// 关闭对话框
const handleClose = () => {
  visible.value = false;
  selectedProjects.value = [];
};

// 搜索
const handleSearch = () => {
  searchForm.pageNum = 1;
  getProjectList();
};

// 重置搜索
const resetSearch = () => {
  searchForm.eventId = undefined;
  searchForm.projectName = undefined;
  searchForm.projectType = undefined;
  searchForm.classification = undefined;
  searchForm.pageNum = 1;
  handleSearch();
};

// 获取项目列表
const getProjectList = async () => {
  loading.value = true;
  try {
    const res = await listAllGameEventProject(searchForm);
    projectList.value = res.rows || [];
    total.value = res.total || 0;
  } catch (error) {
    proxy?.$modal.msgError('获取项目列表失败');
  } finally {
    loading.value = false;
  }
};
// 获取赛事列表
const getEventList = async () => {
  try {
    const res = await listGameEvent({
      pageNum: 1,
      pageSize: 10,
      orderByColumn: undefined,
      isAsc: undefined,
    });
    eventList.value = res.rows || [];
  } catch (error) {
    proxy?.$modal.msgError('获取赛事列表失败');
  }
};
// 选择变化
const handleSelectionChange = (selection: GameEventProjectVO[]) => {
  selectedProjects.value = selection;
};

// 确认选择
const handleConfirm = () => {
  if (selectedProjects.value.length === 0) {
    proxy?.$modal.msgWarning('请选择至少一个项目');
    return;
  }
  
  // 触发父组件的确认事件
  emit('confirm', selectedProjects.value);
  handleClose();
};

// 定义事件
const emit = defineEmits<{
  confirm: [projects: GameEventProjectVO[]]
}>();

// 暴露方法给父组件
defineExpose({
  openDialog
});

// 组件挂载时获取赛事列表
onMounted(() => {
  getEventList();
});

</script>

<style scoped lang="scss">
.project-library {
  .search-area {
    background: #f5f5f5;
    padding: 16px;
    border-radius: 4px;
  }
}
</style>
