<template>
  <el-dialog
    v-model="visible"
    title="选择科目"
    width="1000px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    top="10px"
    append-to-body
    @close="handleClose"
    @open="modalBeforeOpen"
  >
    <el-form :model="searchModel" inline>
      <el-form-item label="科目">
        <el-select
          v-model="searchModel.subjectCode"
          placeholder="请选择科目"
          clearable
          filterable
        >
          <el-option
            v-for="item in subjectList"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search">查询</el-button>
      </el-form-item>
    </el-form>

    <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" />
      <el-table-column prop="objectiveScore" label="客观总分" />
      <el-table-column prop="subjectiveScore" label="主观总分" />
      <el-table-column prop="totalScore" label="试卷总分" />
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <el-tag :type="row.status === 'normal' ? 'success' : 'danger'">
            {{ row.status === 'normal' ? '正常' : '异常' }}
          </el-tag>
        </template>
      </el-table-column>
    </el-table>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          :loading="loading"
          @click="handleConfirmSelection"
          >确定</el-button
        >
      </span>
    </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/base'; // Assuming SubjectItem type exists

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

  interface Props {
    selectIds?: number[];
  }

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

  interface SearchModel {
    subjectCode: string;
  }

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

  const appStore = useAppStore();

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

  // Mock API call for subject list
  const mockSubjectList: SubjectItem[] = [
    {
      id: 1,
      name: '201904516-工程图学2',
      objectiveScore: 0,
      subjectiveScore: 0,
      totalScore: 0,
      status: 'normal',
    },
    {
      id: 2,
      name: '201904516_1-工程图学2',
      objectiveScore: 60,
      subjectiveScore: 40,
      totalScore: 100,
      status: 'normal',
    },
    {
      id: 3,
      name: '语文',
      objectiveScore: 50,
      subjectiveScore: 50,
      totalScore: 100,
      status: 'normal',
    },
    {
      id: 4,
      name: '数学',
      objectiveScore: 70,
      subjectiveScore: 30,
      totalScore: 100,
      status: 'disabled',
    },
  ];

  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);
    }
  };

  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?.toggleAllSelection();
  };

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

  const handleConfirmSelection = () => {
    if (selectedSubjects.value.length === 0) {
      ElMessage.warning('请至少选择一个科目');
      return;
    }
    emit('selected', [...selectedSubjects.value]); // Emit a copy to avoid reactivity issues
    close();
  };

  const handleClose = () => {
    searchModel.name = '';
    selectedSubjects.value = [];
  };

  const modalBeforeOpen = async () => {
    // ceshi
    subjectList.value = mockSubjectList;
    dataList.value = mockSubjectList;

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