<template>
  <div class="part-box is-filter">
    <div class="subject-info">
      <span>科目：{{ subjectInfo.code }}-{{ subjectInfo.name }}</span>
      <span style="margin-left: 20px"
        >客观总分：{{ subjectInfo.objectiveTotalScore }}</span
      >
      <span style="margin-left: 20px"
        >主观总分：{{ subjectInfo.subjectiveTotalScore }}</span
      >
      <span style="margin-left: 20px"
        >试卷总分：{{ subjectInfo.paperTotalScore }}</span
      >
    </div>

    <el-form inline>
      <el-form-item label="试卷类型">
        <el-select
          v-model="searchModel.paperType"
          placeholder="不限"
          clearable
          style="width: 120px"
        >
          <el-option label="不限" value="" />
          <el-option label="A" value="A" />
          <el-option label="B" value="B" />
        </el-select>
      </el-form-item>
      <el-form-item label="大题">
        <el-select
          v-model="searchModel.bigQuestionNo"
          placeholder="不限"
          clearable
          style="width: 120px"
        >
          <el-option label="不限" value="" />
          <el-option label="1" :value="1" />
          <el-option label="2" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-space wrap>
          <!-- <el-button type="primary" @click="toPage(1)">查询</el-button> -->
          <el-button @click="onAdd">新增</el-button>
          <el-button
            type="danger"
            :disabled="!hasSelection"
            @click="onBatchDelete"
          >
            删除
          </el-button>
          <el-button @click="onReturn">返回</el-button>
        </el-space>
      </el-form-item>
    </el-form>
  </div>

  <div class="part-box">
    <el-table
      ref="tableRef"
      v-loading="loading"
      :data="dataList"
      class="page-table"
      border
      stripe
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
        :selectable="(row) => !row.grouping"
      />
      <el-table-column prop="paperType" label="试卷类型" width="80" />
      <el-table-column prop="bigQuestionName" label="大题名称" width="120" />
      <el-table-column
        prop="bigQuestionNickname"
        label="大题昵称"
        width="120"
      />
      <el-table-column prop="bigQuestionNo" label="大题号" width="80" />
      <el-table-column prop="smallQuestionNo" label="小题号" width="80" />
      <el-table-column prop="fullScore" label="满分" width="80" />
      <el-table-column prop="giveScoreCount" label="给分次数" width="100" />
      <el-table-column label="是否客观题" width="100">
        <template #default="{ row }">
          <el-tag :type="row.isObjective ? 'success' : 'info'">
            {{ row.isObjective ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="intervalScore" label="间隔分" width="80" />
      <el-table-column prop="questionType" label="题型" width="100" />
      <el-table-column prop="answer" label="答案" width="100" />
      <el-table-column prop="scoringStrategy" label="判分策略" width="100" />
      <el-table-column prop="grouping" label="分组" width="80">
        <template #default="{ row }">
          <span v-if="row.grouping">{{ row.grouping }}</span>
          <span v-else style="color: #999">无</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100" fixed="right">
        <template #default="{ row }">
          <el-button size="small" type="primary" link @click="onEdit(row)">
            编辑
          </el-button>
          <el-button
            v-if="!row.grouping"
            size="small"
            type="danger"
            link
            @click="onDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!-- 新增/编辑试卷结构弹窗 -->
  <ModifyPaperStructure
    ref="modifyPaperStructureRef"
    :row-data="curRow"
    :subject-id="subjectId"
    @modified="getList"
  />
</template>

<script setup lang="ts">
  import { reactive, ref, computed, onMounted, watch } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import {
    getSubjectDetail,
    getPaperStructureList,
    deletePaperStructures,
  } from '@/api/subject';
  import type { PaperStructureItem } from '@/api/types/subject';
  import useLoading from '@/hooks/loading';
  import { modalConfirm } from '@/utils/ui';

  import ModifyPaperStructure from './components/ModifyPaperStructure.vue';

  defineOptions({
    name: 'PaperStructEdit',
  });

  const route = useRoute();
  const router = useRouter();

  // 从路由参数获取科目ID
  const subjectId = computed(() => Number(route.params.subjectId) || 0);

  const subjectInfo = reactive({
    code: '',
    name: '',
    objectiveTotalScore: 0,
    subjectiveTotalScore: 0,
    paperTotalScore: 0,
  });
  // 获取科目详情信息
  const getSubjectDetailInfo = async () => {
    const res = await getSubjectDetail(subjectId.value);
    subjectInfo.code = res.code;
    subjectInfo.name = res.name;
    subjectInfo.objectiveTotalScore = res.objectiveTotalScore;
    subjectInfo.subjectiveTotalScore = res.subjectiveTotalScore;
    subjectInfo.paperTotalScore = res.paperTotalScore;
  };

  interface SearchModel {
    paperType: string;
    bigQuestionNo: number | string;
  }

  const searchModel = reactive<SearchModel>({
    paperType: '',
    bigQuestionNo: '',
  });

  // 获取试卷结构列表
  const { loading, setLoading } = useLoading();
  const structList = ref<PaperStructureItem[]>([]);
  const dataList = ref<PaperStructureItem[]>([]);
  // 更新dataList
  const updateDataList = () => {
    const { paperType, bigQuestionNo } = searchModel;
    dataList.value = structList.value.filter((item) => {
      return (
        (!paperType || item.paperType === paperType) &&
        (!bigQuestionNo || item.bigQuestionNo === bigQuestionNo)
      );
    });
  };
  // 获取试卷结构列表
  const getList = async () => {
    setLoading(true);
    const res = await getPaperStructureList(subjectId.value).catch(() => []);
    setLoading(false);
    structList.value = res || [];
    updateDataList();
  };

  watch(
    () => searchModel,
    () => {
      updateDataList();
    }
  );

  // 表格选择相关
  const selectedRows = ref<PaperStructureItem[]>([]);
  const hasSelection = computed(() => selectedRows.value.length > 0);

  const handleSelectionChange = (selection: PaperStructureItem[]) => {
    selectedRows.value = selection;
  };

  // 新增/编辑相关
  const curRow = ref({} as PaperStructureItem);
  const modifyPaperStructureRef = ref();

  const onAdd = () => {
    curRow.value = {} as PaperStructureItem;
    modifyPaperStructureRef.value?.open();
  };

  const onEdit = (row: PaperStructureItem) => {
    curRow.value = row;
    modifyPaperStructureRef.value?.open();
  };

  // 删除相关
  const onDelete = async (row: PaperStructureItem) => {
    const confirm = await modalConfirm(
      '确定要删除这条试卷结构记录吗？',
      '提示'
    ).catch(() => false);
    if (!confirm) return;

    try {
      await deletePaperStructures([row.id]);
      ElMessage.success('删除成功');
      getList();
    } catch (error) {
      console.error('删除失败:', error);
    }
  };

  const onBatchDelete = async () => {
    const confirm = await modalConfirm(
      `确定要删除选中的 ${selectedRows.value.length} 条记录吗？`,
      '提示'
    ).catch(() => false);
    if (!confirm) return;

    try {
      const ids = selectedRows.value.map((row) => row.id);
      await deletePaperStructures(ids);
      ElMessage.success('批量删除成功');
      selectedRows.value = [];
      getList();
    } catch (error) {
      console.error('批量删除失败:', error);
    }
  };

  const onReturn = () => {
    router.back();
  };

  onMounted(() => {
    if (subjectId.value) {
      getList();
      getSubjectDetailInfo();
    }
  });
</script>

<style scoped>
  .subject-info {
    padding: 16px;
    background-color: #f5f7fa;
    border-radius: 4px;
    margin-bottom: 16px;
    font-size: 14px;
    color: #606266;
  }
</style>
