<template>
  <ele-page>
    <!-- 搜索表单 -->
    <ele-card :body-style="{ paddingTop: '8px' }">
      <!-- 表格 -->
      <ele-pro-table
        ref="tableRef"
        row-key="key"
        :columns="columns"
        :datasource="datasource"
        :show-overflow-tooltip="true"
        v-model:selections="selections"
        :highlight-current-row="true"
        :export-config="{ fileName: '试卷人员分配' }"
        cache-key="systemPersonTable"
      >
        <template #toolbar>
         
          <el-button
            v-permission="'system:person:add'"
            type="primary"
            class="ele-btn-icon"
       
            @click="openEdit()"
          >
            分配场次
          </el-button>
          <el-button
            v-permission="'system:person:remove'"
            type="danger"
            class="ele-btn-icon"
     
            @click="removeBatch()"
          >
            删除
          </el-button>
          <el-button
            v-permission="'system:person:export'"
            class="ele-btn-icon"
       
            @click="exportData"
          >
            导出
          </el-button>
        </template>
        <template #action="{ row }">
          <el-link
            v-permission="'system:person:edit'"
            type="primary"
            :underline="false"
            @click="openEdit(row)"
          >
            修改
          </el-link>
          <el-divider
            v-permission="['system:person:edit', 'system:person:remove']"
            direction="vertical"
          />
          <el-link
            v-permission="'system:person:remove'"
            type="danger"
            :underline="false"
            @click="removeBatch(row)"
          >
            删除
          </el-link>
        </template>
      </ele-pro-table>
    </ele-card>
    <!-- 编辑弹窗 -->
    <person-edit v-model="showEdit"  :task-Id="taskId" @done="reload" />
  </ele-page>
</template>

<script setup>
  import { ref } from 'vue';
  // import {
  //   PlusOutlined,
  //   DeleteOutlined,
  //   DownloadOutlined
  // } from '@/components/icons';
  import PersonEdit from './components/person-edit.vue';
  import { pagePersons, removePersons, exportPersons } from '@/api/system/person';
  import { pageStus, removeStus, exportStus } from '@/api/system/stu';
  const message = useMessage() // 消息弹窗

  defineOptions({ name: 'SystemPerson' });
  const props = defineProps({
  taskId: {
    type: String,
    default: '',
  }
})


const tableRef = ref(null);
const selections = ref([]);
const current = ref(null);
const showEdit = ref(false);
const showSet = ref(false);

/** 班级映射表：deptId => { deptName, teacherName } */
const classMap = ref({});

/** 表格列配置 */
const columns = ref([
  { type: 'selection', columnKey: 'selection', width: 50, align: 'center', fixed: 'left' },
  { type: 'index', columnKey: 'index', width: 50, align: 'center', fixed: 'left' },
  { prop: 'stuCode', label: '学生编码', align: 'center', minWidth: 110 },
  { prop: 'stuUsername', label: '学生账号', align: 'center', minWidth: 110 },


  {
    prop: 'stuClass',
    label: '学生班级',
    align: 'center',
    minWidth: 110,
    slot: 'stuClass' // 👈 使用自定义 slot 显示班级 + 悬浮教师名
  },
  { prop: 'status', label: '帐号状态（0正常 1停用）', align: 'center', minWidth: 110 },
  { prop: 'batch', label: '分配场次', align: 'center', minWidth: 110 }
]);

/** 表格数据源：处理学生 + 班级 */
const datasource = async ({ pages, where }) => {
  // 获取学生和班级信息
  const { examStuList, teacherClassDtos } = await pageStus({ ...where, ...pages });

  // 如果没有数据，直接返回空列表
  if (!examStuList || !teacherClassDtos) {
    message.error('数据加载失败');
    return [];
  }

  console.log("examStuList:", examStuList);
  console.log("teacherClassDtos:", teacherClassDtos);

  // 构建班级映射表，使用 dept_id 作为 key
  const classMap = {};
  teacherClassDtos.forEach(item => {
    classMap[item.dept_id] = {
      deptName: item.dept_name,
      teacherName: item.nick_name || item.user_name || '未知教师'
    };
  });

  // 将映射表存储到 `classMap`，供后续使用
  classMap.value = classMap;

  // 合并学生信息和班级信息
  const processedList = examStuList.map(stu => {
    // 使用 stuClass 匹配 teacherClassDtos 的 dept_id
    const classInfo = classMap[stu.stuClass] || {}; // 如果找不到匹配，返回默认值
    return {
      ...stu,
      deptName: classInfo.deptName || '未知班级', // 如果没有班级信息，显示默认值
      teacherName: classInfo.teacherName || '未知教师' // 如果没有教师信息，显示默认值
    };
  });

  console.log("processedList:", processedList);
  return processedList; // 返回合并后的学生信息
};


/** 搜索 */
const reload = (where) => {
  tableRef.value?.reload?.({ page: 1, where });
};

/** 打开编辑弹窗 */
const openEdit = (row) => {
  current.value = row ?? null;
  showEdit.value = true;
};

/** 打开班级设置弹窗 */
const openSet = (row) => {
  current.value = row ?? null;
  showSet.value = true;
};

/** 删除学生（单条或多条） */
const removeBatch = (row) => {
  const rows = row == null ? selections.value : [row];
  if (!rows.length) {
    message.error('请至少选择一条数据');
    return;
  }
  ElMessageBox.confirm(
    `是否确认删除学生编码为"${rows.map((d) => d.stuCode).join()}"的数据项?`,
    '系统提示',
    { type: 'warning', draggable: true }
  )
    .then(() => {
      const loading = message.loading({ message: '请求中..', plain: true });
      removeStus(rows.map((d) => d.stuId))
        .then(() => {
          loading.close();
          message.success('删除成功');
          reload();
        })
        .catch((e) => {
          loading.close();
          message.error(e.message);
        });
    })
    .catch(() => {});
};

/** 导出数据 */
const exportData = () => {
  const loading = message.loading({ message: '请求中..', plain: true });
  tableRef.value?.fetch?.(({ where }) => {
    exportStus(where)
      .then(() => loading.close())
      .catch((e) => {
        loading.close();
        message.error(e.message);
      });
  });
};

</script>