<template>
  <el-dialog
    v-model="visible"
    title="选择科目"
    width="1000px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    top="0"
    append-to-body
    modal-class="select-subject-dialog"
    @close="handleClose"
    @open="modalBeforeOpen"
  >
    <el-form :model="searchModel" inline>
      <el-form-item label="科目">
        <el-select
          v-model="searchModel.subjectCode"
          placeholder="请选择科目"
          clearable
          filterable
          default-first-option
        >
          <el-option
            v-for="item in subjectList"
            :key="item.code"
            :label="`${item.code}-${item.name}`"
            :value="item.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search">查询</el-button>
        <el-button
          type="primary"
          :loading="loading"
          @click="handleConfirmSelection"
          >确定</el-button
        >
        <el-button @click="close">取消</el-button>
      </el-form-item>
    </el-form>

    <div class="subject-table">
      <el-table
        ref="tableRef"
        :data="dataList"
        row-key="code"
        :loading="loading"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          :reserve-selection="true"
        />
        <el-table-column prop="name" label="科目名称" min-width="200">
          <template #default="scope">
            {{ scope.row.code }}-{{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column prop="objectiveScore" label="客观总分" />
        <el-table-column prop="subjectiveScore" label="主观总分" />
        <el-table-column prop="totalScore" label="试卷总分" />
        <el-table-column prop="status" label="状态"> 正常 </el-table-column>
      </el-table>
    </div>

    <template #footer> </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import { ref, reactive, nextTick } from 'vue';
  import { ElMessage, ElTable } from 'element-plus';
  import type { TableInstance } from 'element-plus';
  import useLoading from '@/hooks/loading';
  import useModal from '@/hooks/modal';
  import { subjectQuery } from '@/api/base'; // Assuming API for subjects exists
  import { useAppStore } from '@/store';

  import type { SubjectItem } from '@/api/types/subject';

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

  interface Props {
    selectCodes?: string[];
  }

  const props = withDefaults(defineProps<Props>(), {
    selectCodes: () => [],
  });

  interface SearchModel {
    subjectCode: string;
  }

  /* modal */
  const { visible, open, close } = useModal();
  defineExpose({ open, close, getSubjectCount });

  const appStore = useAppStore();

  const emit = defineEmits(['selected']);

  const { loading, setLoading } = useLoading();
  const searchModel = reactive<SearchModel>({ subjectCode: undefined });
  const subjectList = ref<SubjectItem[]>([]);
  const dataList = ref<SubjectItem[]>([]);
  const selectedSubjects = ref<SubjectItem[]>([]);
  const tableRef = ref<TableInstance>();

  const fetchSubjectList = async () => {
    setLoading(true);
    try {
      if (!appStore.curExam?.id) return;

      const res = await subjectQuery(appStore.curExam?.id);
      subjectList.value = res || [];
      dataList.value = res || [];
      await nextTick();
      tableRef.value?.toggleAllSelection();
    } catch (error) {
      subjectList.value = [];
    } finally {
      setLoading(false);
    }
  };

  function getSubjectCount() {
    return subjectList.value.length;
  }

  const search = async () => {
    if (!searchModel.subjectCode) {
      dataList.value = subjectList.value;
    } else {
      dataList.value = subjectList.value.filter((item) => {
        return item.code === searchModel.subjectCode;
      });
    }

    await nextTick();
    tableRef.value?.clearSelection();
    tableRef.value?.toggleAllSelection();
  };

  const handleSelectionChange = (selection: SubjectItem[]) => {
    selectedSubjects.value = selection;
  };

  const handleConfirmSelection = () => {
    if (selectedSubjects.value.length === 0) {
      ElMessage.warning('请至少选择一个科目');
      return;
    }
    emit(
      'selected',
      [...selectedSubjects.value].map((item) => item.code)
    );
    close();
  };

  const handleClose = () => {
    tableRef.value?.clearSelection();
    searchModel.subjectCode = '';
    selectedSubjects.value = [];
  };

  const modalBeforeOpen = async () => {
    await fetchSubjectList();
    if (props.selectCodes.length > 0) {
      await nextTick();
      selectedSubjects.value = dataList.value.filter((item) => {
        return props.selectCodes.includes(item.code);
      });
      if (selectedSubjects.value.length > 0) {
        selectedSubjects.value.forEach((item) => {
          tableRef.value?.toggleRowSelection(item, true);
        });
      } else {
        tableRef.value?.toggleAllSelection();
      }
    } else {
      tableRef.value?.toggleAllSelection();
    }
  };
</script>
