<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"
              @click="onEditExamNumber"
              >查看全部</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="客观题作答">
                <SelectBoolean
                  v-model:value="customSearchModel.questionFilled"
                  style="width: 85px"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="主观题作答">
                <SelectBoolean
                  v-model:value="customSearchModel.subjectiveFilled"
                  style="width: 100%"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="有作答">
                <SelectBoolean
                  v-model:value="customSearchModel.hasFilled"
                  style="width: 85px"
                />
              </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="14">
              <a-form-item label="缺考">
                <a-select
                  v-model:value="customSearchModel.examStatus"
                  placeholder="请选择"
                  :options="examStatusOptions"
                  style="width: 85px"
                  allow-clear
                ></a-select>
              </a-form-item>
            </a-col>
            <a-col :span="10">
              <a-form-item style="text-align: right">
                <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, index) in imageTypeOptions"
            :key="index"
            :value="item.value"
            >{{ item.label }}</a-radio
          >
        </a-radio-group>
      </a-collapse-panel>
      <a-collapse-panel key="4">
        <template #header><IdcardFilled />题卡信息 </template>

        <QuestionPanel
          v-if="dataCheckStore.curStudent && dataCheckStore.curPage"
          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" />
  <!-- MoreExamNumberDialog -->
  <MoreExamNumberDialog
    ref="moreExamNumberDialogRef"
    :data="customSearchModel.examNumber"
    @confirm="onExamNumberEdited"
  />
</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,
  DataStatus,
  ExamStatus,
} from "@/ap/types/dataCheck";
import { SubjectItem } from "@/ap/types/base";
import { ReviewExportType } from "@/ap/types/review";
import { QuestionInfo } from "./types";

import { dataCheckStudentExport, dataCheckRoomExport } from "@/ap/dataCheck";
import { examStatusSave } from "@/ap/absentCheck";
import useDictOption from "@/hooks/dictOption";
import useLoading from "@/hooks/useLoading";
import { ImageType } from "@/constants/enumerate";
import { objModifyAssign } from "@/utils/tool";

import ExportTypeDialog from "../Review/ExportTypeDialog.vue";
import QuestionPanel from "./QuestionPanel.vue";
import MoreExamNumberDialog from "./MoreExamNumberDialog.vue";
import { getTextAreaRows } from "@/utils";
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 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 || []).map((item: any) => {
    item.name = item.code + "-" + item.name;
    return item;
  });
}
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 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`;
});
const moreExamNumberDialogRef = ref();
function onEditExamNumber() {
  moreExamNumberDialogRef.value?.open();
}
function onExamNumberEdited(val: string) {
  customSearchModel.examNumber = val;
}

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

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

function onSearch() {
  emit("search", searchModel);
}
function onCustomSearch() {
  // emit("search", customSearchModel);
  emit("search", {
    ...customSearchModel,
    examNumber: (customSearchModel.examNumber || "")
      .split("\n")
      .filter((item) => item)
      .join(","),
  });
}

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

// question panel
const questionInfo = computed(() => {
  if (!dataCheckStore.curStudent) return {} as QuestionInfo;
  return {
    examNumber: dataCheckStore.curStudent.examNumber,
    name: dataCheckStore.curStudent.name,
    examSite: dataCheckStore.curStudent.examSite,
    seatNumber: dataCheckStore.curStudent.seatNumber,
    paperType: dataCheckStore.curStudent.paperType,
    examStatus: dataCheckStore.curStudent.examStatus as string,
    packageCode: dataCheckStore.curStudent.packageCode as string,
  };
});

const questions = ref([] as string[]);
watch(
  () => dataCheckStore.curPage?.question?.result,
  (val) => {
    if (!val) {
      questions.value = [];
      return;
    }
    questions.value = [...val];
  },
  {
    deep: true,
    immediate: true,
  }
);
watch(
  () => dataCheckStore.imageType,
  (val) => {
    imageType.value = val;
  }
);

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("导出成功！");
}

watch(
  () => customSearchModel.examNumber,
  (val, oldVal) => {
    if (getTextAreaRows(val) > 100) {
      window.$message.error("最多只能输入100行");
      customSearchModel.examNumber = oldVal;
    }
  }
);
</script>
