<template>
  <div class="check-action">
    <a-collapse
      v-model:activeKey="panelKey"
      :bordered="false"
      expandIconPosition="end"
    >
      <a-collapse-panel key="1">
        <template #header><FilterFilled />搜索条件 </template>
        <a-form :label-col="{ style: { width: '76px' } }">
          <a-form-item label="科目">
            <select-course
              v-model:value="searchModel.subjectCode"
              :exam-id="userStore.curExam.id"
              style="width: 150px"
              allow-clear
            ></select-course>
          </a-form-item>
          <a-form-item label="查找条件">
            <a-select
              v-model:value="searchDataCheckType"
              placeholder="请选择"
              :options="absentCheckOptions"
              allow-clear
              @change="absentCheckTypeChange"
            ></a-select>
          </a-form-item>
          <a-form-item label="准考证号">
            <div class="exam-number">
              <a-textarea
                v-model:value="searchModel.examNumber"
                placeholder="请输入"
                :auto-size="{ minRows: 1, maxRows: 1 }"
              ></a-textarea>
              <div class="number-suffix">{{ examNumberCountCont }}</div>
            </div>
            <a-button class="ant-simple m-l-8px" type="link">查看全部</a-button>
          </a-form-item>

          <a-row>
            <a-col :span="15">
              <a-form-item label="姓名">
                <a-input
                  v-model:value="searchModel.name"
                  placeholder="请输入"
                  style="width: 140px"
                ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="9">
              <a-form-item style="text-align: right">
                <a-button class="m-r-8px" type="primary" @click="onSearch"
                  >查询</a-button
                >
                <a-button @click="onExport">导出</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-collapse-panel>
      <a-collapse-panel key="2">
        <template #header><PictureFilled />图片类别 </template>

        <a-radio-group v-model:value="imageType" @change="onImageTypeChange">
          <a-radio
            v-for="item in imageTypeOptions"
            :key="item.value"
            :value="item.value"
            >{{ item.label }}</a-radio
          >
        </a-radio-group>
      </a-collapse-panel>
      <a-collapse-panel key="3">
        <template #header><IdcardFilled />题卡信息 </template>

        <QuestionPanel
          v-model:questions="questions"
          :info="questionInfo"
          :simple="isSliceImage"
          @change="onQuestionsChange"
          @exam-status-change="onExamStatusChange"
        />
      </a-collapse-panel>
      <a-collapse-panel key="4">
        <template #header><SettingFilled />缺考数据设置 </template>

        <a-button
          class="m-r-10px"
          type="primary"
          :rotate="90"
          @click="onImport"
        >
          <template #icon><SelectOutlined /></template>导入缺考名单
        </a-button>
        <a-button @click="onReset">
          <template #icon><RedoOutlined :rotate="270" /></template
          >重新生成缺考数据
        </a-button>
      </a-collapse-panel>
    </a-collapse>
  </div>

  <!-- ExportTypeDialog -->
  <ExportTypeDialog ref="exportTypeDialogRef" @confirm="onExportConfirm" />
  <!-- ResetDialog -->
  <ResetDialog ref="resetDialogRef" />
  <!-- ImportTypeDialog -->
  <ImportTypeDialog ref="importTypeDialogRef" />
</template>

<script setup lang="ts">
import { computed, reactive, ref, watch } from "vue";
import {
  FilterFilled,
  PictureFilled,
  IdcardFilled,
  SettingFilled,
  SelectOutlined,
  RedoOutlined,
} from "@ant-design/icons-vue";
import { message } from "ant-design-vue";

import { useUserStore, useDataCheckStore } from "@/store";
import { AbsentCheckListFilter, ImportType } from "@/ap/types/absentCheck";
import { ExamStatus } from "@/ap/types/dataCheck";
import { ReviewExportType } from "@/ap/types/review";

import {
  absentCheckStudentExport,
  absentCheckRoomExport,
  examStatusSave,
} from "@/ap/absentCheck";
import useDictOption from "@/hooks/dictOption";
import useLoading from "@/hooks/useLoading";

import ExportTypeDialog from "../Review/ExportTypeDialog.vue";
import ResetDialog from "./ResetDialog.vue";
import ImportTypeDialog from "./ImportTypeDialog.vue";
import QuestionPanel from "../DataCheck/QuestionPanel.vue";

defineOptions({
  name: "CheckAction",
});

const emit = defineEmits(["search"]);

const userStore = useUserStore();
const dataCheckStore = useDataCheckStore();

const { optionList: absentCheckOptions } = useDictOption("ABSENT_CHECK_TYPE");
const { optionList: imageTypeOptions } = useDictOption("IMAGE_TYPE");
const panelKey = ref(["1", "2", "3", "4"]);

// search
const initSearchModel = {
  examId: userStore.curExam.id,
  examNumber: "",
  studentCode: "",
  name: "",
  subjectCode: "",
  examStatus: [],
};
const searchModel = reactive<AbsentCheckListFilter>({ ...initSearchModel });
const searchDataCheckType = ref();
const imageType = ref(dataCheckStore.imageType);
const actionType = ref("common");

// imageType
const isSliceImage = computed(() => {
  return dataCheckStore.imageType === "SLICE";
});

const examNumberCountCont = computed(() => {
  const examNumbers = (searchModel.examNumber || "")
    .split("\n")
    .filter((item) => item);
  return `${examNumbers.length}/100`;
});

function absentCheckTypeChange() {
  switch (searchDataCheckType.value) {
    // 缺考
    case "1":
      searchModel.examStatus = ["ABSENT"];
      break;
    // 正常
    case "2":
      searchModel.examStatus = ["OK"];
      break;

    default:
      searchModel.examStatus = [];
      break;
  }
}

function onSearch() {
  emit("search", searchModel);
}

function onImageTypeChange() {
  dataCheckStore.setInfo({
    imageType: imageType.value,
  });
}

// question panel
const questionInfo = computed(() => {
  return {
    examNumber: dataCheckStore.curStudent?.examNumber,
    name: dataCheckStore.curStudent?.name,
    examSite: dataCheckStore.curStudent?.examSite,
    seatNumber: dataCheckStore.curStudent?.seatNumber,
    paperType: dataCheckStore.curStudent?.paperType,
  };
});

const questions = ref([]);
watch(
  () => dataCheckStore.curPageIndex,
  (val, oldval) => {
    if (val !== oldval) {
      if (!dataCheckStore.curPage || !dataCheckStore.curPage.question) return;
      questions.value = [...dataCheckStore.curPage.question.result];
    }
  }
);

async function onQuestionsChange() {
  if (!dataCheckStore.curPage) return;
  dataCheckStore.curPage.question = [...questions.value];

  await dataCheckStore
    .updateField({
      field: "QUESTION",
      value: questions.value,
    })
    .catch(() => {});
}

async function onExamStatusChange(val: ExamStatus) {
  if (!dataCheckStore.curStudent) return;

  await examStatusSave({ id: dataCheckStore.curStudent.id, examStatus: val });
  dataCheckStore.curStudent.examStatus = val;
}

// 导出
const { loading: downloading, setLoading } = useLoading();
const exportTypeDialogRef = ref();
function onExport(type: string) {
  if (downloading.value) return;
  actionType.value = type;
  exportTypeDialogRef.value?.open();
}

async function onExportConfirm(type: ReviewExportType) {
  if (downloading.value) return;

  setLoading(true);
  const func =
    type === "STUDENT_CODE" ? absentCheckStudentExport : absentCheckRoomExport;

  const res = await func(searchModel).catch((e: Error) => {
    message.error(e.message || "下载失败，请重新尝试！");
  });
  setLoading(false);

  if (!res) return;
  message.success("导出成功！");
}

// 导入
const importTypeDialogRef = ref();
function onImport() {
  importTypeDialogRef.value?.open();
}

// 重置
const resetDialogRef = ref();
function onReset() {
  resetDialogRef.value?.open();
}
</script>
