<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: '83px' } }">
          <a-form-item label="科目">
            <a-select
              v-model:value="searchModel.subjectCode"
              placeholder="请选择"
              :options="courses"
              :field-names="fieldNames"
              filter-option
              allow-clear
              style="width: 150px"
            ></a-select>
          </a-form-item>
          <a-form-item label="查找条件">
            <a-select
              v-model:value="searchDataCheckType"
              placeholder="请选择"
              :options="dataCheckOptions"
              allow-clear
              @change="dataCheckTypeChange"
            ></a-select>
          </a-form-item>
        </a-form>
        <div class="box-justify">
          <div></div>
          <div>
            <a-button class="m-r-8px" type="primary" @click="onSearch"
              >查询</a-button
            >
            <a-button @click="onExport('common')">导出</a-button>
          </div>
        </div>
      </a-collapse-panel>
      <a-collapse-panel key="2">
        <template #header><FilterFilled />搜索条件 (自定义)</template>

        <a-form :label-col="{ style: { width: '83px' } }">
          <a-form-item label="准考证号">
            <div class="exam-number">
              <a-textarea
                v-model:value="customSearchModel.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-form-item label="姓名">
            <a-input
              v-model:value="customSearchModel.name"
              placeholder="请输入"
              style="width: 150px"
            ></a-input>
          </a-form-item>
          <a-form-item label="科目">
            <a-select
              v-model:value="customSearchModel.subjectCode"
              placeholder="请选择"
              :options="courses"
              :field-names="fieldNames"
              filter-option
              allow-clear
              style="width: 150px"
            ></a-select>
          </a-form-item>
          <a-row>
            <a-col :span="12">
              <a-form-item label="客观题作答">
                <a-select
                  v-model:value="customSearchModel.questionFilled"
                  placeholder="请选择"
                  :options="booleanOptions"
                  style="width: 85px"
                  allow-clear
                ></a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="主观题作答">
                <a-select
                  v-model:value="customSearchModel.subjectiveFilled"
                  placeholder="请选择"
                  :options="booleanOptions"
                  style="width: 100%"
                  allow-clear
                ></a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="有作答">
                <a-select
                  v-model:value="customSearchModel.hasFilled"
                  placeholder="请选择"
                  :options="booleanOptions"
                  style="width: 85px"
                  allow-clear
                ></a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="试卷类型">
                <a-select
                  v-model:value="customSearchModel.paperTypeStatus"
                  placeholder="请选择"
                  :options="paperTypeOptions"
                  style="width: 100%"
                  allow-clear
                ></a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="16">
              <a-form-item label="缺考">
                <a-select
                  v-model:value="customExamStatus"
                  placeholder="请选择"
                  :options="examStatusOptions"
                  style="width: 85px"
                  allow-clear
                  @change="customExamStatusChange"
                ></a-select>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item>
                <a-button class="m-r-8px" type="primary" @click="onCustomSearch"
                  >查询</a-button
                >
                <a-button @click="onExport('custom')">导出</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-collapse-panel>
      <a-collapse-panel key="3">
        <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="4">
        <template #header><IdcardFilled />题卡信息 </template>

        <QuestionPanel
          v-model:questions="questions"
          :info="questionInfo"
          :simple="isSliceImage"
          @change="onQuestionsChange"
          @exam-status-change="onExamStatusChange"
        />
      </a-collapse-panel>
    </a-collapse>
  </div>

  <!-- ExportTypeDialog -->
  <ExportTypeDialog ref="exportTypeDialogRef" @confirm="onExportConfirm" />
</template>

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

import { useUserStore, useDataCheckStore } from "@/store";
import { DataCheckListFilter, ExamStatus } from "@/ap/types/dataCheck";
import { SubjectItem } from "@/ap/types/base";
import { ReviewExportType } from "@/ap/types/review";
import { dataCheckStudentExport, dataCheckRoomExport } from "@/ap/dataCheck";
import { examStatusSave } from "@/ap/absentCheck";
import useDictOption from "@/hooks/dictOption";
import useLoading from "@/hooks/useLoading";
import { ImageType, booleanOptionList } from "@/constants/enumerate";

import ExportTypeDialog from "../Review/ExportTypeDialog.vue";
import QuestionPanel from "./QuestionPanel.vue";
import { objModifyAssign } from "@/utils/tool";

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

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

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

const { optionList: dataCheckOptions } = useDictOption("DATA_CHECK_TYPE");
const { optionList: paperTypeOptions } = useDictOption("PAPER_TYPE_STATUS");
const { optionList: imageTypeOptions } = useDictOption("IMAGE_TYPE");
const { optionList: examStatusOptions } = useDictOption("EXAM_STATUS");
const booleanOptions = ref(booleanOptionList);
const panelKey = ref(["1", "2", "3", "4"]);

// course data
const courses = ref<SubjectItem[]>([]);
async function getCourses() {
  const res = await getSubjectList({ examId: userStore.curExam.id });
  courses.value = res || [];
}
getCourses();
const fieldNames = { label: "name", value: "code" };

// search
const initSearchModel = {
  examId: userStore.curExam.id,
  status: "",
  examStatus: [],
  examNumber: "",
  studentCode: "",
  name: "",
  packageCode: "",
  campusCode: "",
  subjectCode: "",
  examSite: "",
  examRoom: "",
  province: "",
  paperTypeStatus: "",
  device: "",
  absentSuspect: null,
  omrAbsent: null,
  assigned: null,
  incomplete: null,
  questionFilled: null,
  subjectiveFilled: null,
  hasFilled: null,
  withOmrDetail: null,
};
const searchModel = reactive<DataCheckListFilter>({ ...initSearchModel });
const customSearchModel = reactive<DataCheckListFilter>({ ...initSearchModel });
const searchDataCheckType = ref();
const customExamStatus = ref<ExamStatus>();
const imageType = ref(dataCheckStore.imageType);
const actionType = ref("common");

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

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

function dataCheckTypeChange() {
  switch (searchDataCheckType.value) {
    // 缺考有作答
    case "1":
      searchModel.examStatus = ["ABSENT"];
      searchModel.hasFilled = true;
      break;
    // 客观题无作答，主观题有作答；
    case "2":
      searchModel.questionFilled = false;
      searchModel.subjectiveFilled = true;
      break;
    // 不缺考，无条码，有作答；(正常或待审核考生，条码为空，有作答)
    case "3":
      searchModel.examStatus = ["OK", "UNCHECK"];
      searchModel.paperTypeStatus = "BLANK";
      searchModel.hasFilled = true;
      break;
    // 不缺考，无条码，无作答；(正常或待审核考生，条码为空，没有作答)
    case "4":
      searchModel.examStatus = ["OK", "UNCHECK"];
      searchModel.paperTypeStatus = "BLANK";
      searchModel.hasFilled = false;
      break;
    // 条码异常(识别的条码没与库中匹配上）
    case "5":
      searchModel.paperTypeStatus = "ERROR";
      break;
    // 缺考有条码
    case "6":
      searchModel.paperTypeStatus = "OK";
      searchModel.examStatus = ["ABSENT"];
      break;

    default:
      objModifyAssign(searchModel, {
        ...initSearchModel,
        subjectCode: searchModel.subjectCode,
      });
      break;
  }
}

function customExamStatusChange() {
  customSearchModel.examStatus = customExamStatus.value
    ? [customExamStatus.value]
    : [];
}

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

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.result = [...questions.value];

  await dataCheckStore
    .updateField({
      field: "QUESTION",
      value: JSON.stringify(dataCheckStore.curPage.question),
    })
    .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" ? dataCheckStudentExport : dataCheckRoomExport;
  const params =
    actionType.value === "common" ? searchModel : customSearchModel;

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

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