<template>
  <div class="question-panel">
    <a-descriptions v-if="info" class="panel-info" :column="10">
      <a-descriptions-item label="考号" :span="6">
        {{ info.examNumber }}
      </a-descriptions-item>
      <a-descriptions-item label="姓名" :span="4">
        {{ info.name }}
      </a-descriptions-item>
      <a-descriptions-item label="卷袋号" :span="6">
        {{ info.packageCode }}
      </a-descriptions-item>
      <a-descriptions-item label="考点" :span="4">
        {{ info.examSite }}
      </a-descriptions-item>
      <a-descriptions-item label="卷型号" :span="6">
        <template v-if="simple">
          {{ paperTypeDisplay }}
        </template>
        <template v-else>
          <a-button class="ant-gray m-r-4px">{{ paperTypeDisplay }}</a-button>
          <a-button v-if="paperTypeArea && editable" @click="onEditPaperType">
            <template #icon><SwapOutlined /></template>
          </a-button>
        </template>
      </a-descriptions-item>
      <a-descriptions-item v-if="!simple && editable" label="缺考" :span="4">
        <a-radio-group
          v-model:value="examStatus"
          name="examStatus"
          @change="onExamStatusChange"
        >
          <a-radio
            v-for="(item, index) in examStatusOptions"
            :key="index"
            :value="item.value"
            >{{ item.label }}</a-radio
          >
        </a-radio-group>
      </a-descriptions-item>
    </a-descriptions>
    <div
      v-if="!simple && dataCheckStore.curPage?.question"
      ref="panelBodyRef"
      class="panel-body"
    >
      <div class="panel-body-title">
        <h4>客观题</h4>
        <p>多于一个填涂显示>号，未填涂显示#号</p>
      </div>
      <div
        v-for="(item, index) in questionList"
        :key="index"
        :class="['question-item', `question-item-${index}`]"
      >
        <span>{{ getQuestionNo(index) }}:</span>
        <a-button
          v-if="editable || item.length <= 1"
          :class="['ant-gray', { 'is-active': curQuestionIndex === index }]"
          :disabled="!editable"
          @click="onEditQuestion(index)"
          >{{ getQuesionCont(item) }}</a-button
        >
        <a-tooltip v-else placement="top">
          <template #title>
            <span>{{ item.split("").join(",") }}</span>
          </template>
          <a-button disabled>{{ getQuesionCont(item) }}</a-button>
        </a-tooltip>
      </div>

      <div
        v-if="quesionEditShow && editable"
        class="queston-edit"
        :style="quesionEditStyle"
        v-ele-click-outside-directive="hideEditQuestion"
        @keydown.stop
        @keyup.enter="onSaveQuesion"
      >
        <a-input
          v-model:value="curQuestion"
          style="width: 64px"
          @change="toUpperCase"
        ></a-input>
        <a-button class="ant-simple m-l-8px" type="link" @click="onSaveQuesion"
          >保存(Enter)</a-button
        >
      </div>
    </div>
  </div>

  <ModifyPaperType
    ref="modifyPaperTypeRef"
    :area-img="paperTypeImg"
    :area-result="paperTypeResult"
    :ocr-result="paperTypeOrcResult"
    @confirm="paperTypeModified"
  />
</template>

<script setup lang="ts" name="QuestionPanel">
import { computed, ref, watch, onMounted } from "vue";
import { message } from "ant-design-vue";
import { SwapOutlined } from "@ant-design/icons-vue";
import { QuestionInfo } from "./types";
import { parseRecogData } from "@/utils/recog/recog";

import useDictOption from "@/hooks/dictOption";
import ModifyPaperType from "./ModifyPaperType.vue";
import { useDataCheckStore } from "@/store";

import { vEleClickOutsideDirective } from "@/directives/eleClickOutside";
import { getSliceFileUrl } from "@/utils/tool";

// defineOptions({
//   name: "QuestionPanel",
// });

const props = withDefaults(
  defineProps<{
    questions: string[];
    info: QuestionInfo;
    simple: boolean;
    editable?: boolean;
  }>(),
  {
    questions: () => [],
    simple: false,
    editable: true,
  }
);
const emit = defineEmits(["update:questions", "change", "examStatusChange"]);

const dataCheckStore = useDataCheckStore();

const { optionList: examStatusOptions } = useDictOption("EXAM_SIMPLE_STATUS");
const examStatus = ref("");
const questionList = ref([] as string[]);
const curQuestion = ref("");
const curQuestionIndex = ref(-1);

const toUpperCase = () => {
  if ((curQuestion.value || "").includes("#")) {
    if (curQuestion.value.length > 1) {
      curQuestion.value = "#";
    }
  } else {
    curQuestion.value = curQuestion.value.replace(/[^a-zA-Z]/g, "");
  }
  curQuestion.value = curQuestion.value.toUpperCase();
};

function onExamStatusChange() {
  emit("examStatusChange", examStatus.value);
}

function getQuestionNo(index: number) {
  const no = index + 1;
  return no < 10 ? `0${no}` : `${no}`;
}

function getQuesionCont(cont: string) {
  if (!cont) return "#";
  if (cont.length > 1) return ">";
  return cont;
}

// question edit
const quesionEditShow = ref(false);
const quesionEditPos = ref({
  left: 0,
  top: 0,
});
const quesionEditStyle = computed(() => {
  return {
    top: `${quesionEditPos.value.top}px`,
    left: `${quesionEditPos.value.left}px`,
  };
});
const panelBodyRef = ref();
function onEditQuestion(index: number) {
  curQuestionIndex.value = index;
  const qcont = questionList.value[curQuestionIndex.value];
  curQuestion.value = qcont;

  quesionEditShow.value = true;
  updateQuestionEditPos(index);
}

function updateQuestionEditPos(index: number) {
  const panelBodyDom = panelBodyRef.value as HTMLDivElement;
  const itemDom = panelBodyDom.querySelector(
    `.question-item-${index}`
  ) as HTMLDivElement;
  let left = itemDom.offsetLeft + 30;
  left = Math.min(panelBodyDom.clientWidth - 165, left);
  quesionEditPos.value.left = left;
  quesionEditPos.value.top = itemDom.offsetTop - 54;
}

function hideEditQuestion() {
  quesionEditShow.value = false;
  curQuestionIndex.value = -1;
}

function onSaveQuesion() {
  if (!quesionEditShow.value) return;

  if (!curQuestion.value) {
    message.error("请输入答案！");
    return;
  }
  const questionCont = curQuestion.value;

  if (!questionCont) {
    message.error("请输入答案！");
    return;
  }

  questionList.value[curQuestionIndex.value] = questionCont;
  quesionEditShow.value = false;

  emit("update:questions", questionList.value);
  emit("change", questionList.value);
}

// edit paper
const modifyPaperTypeRef = ref();
const paperTypeArea = ref<AreaSize | null>(null);
const paperTypeImg = ref("");
const paperTypeResult = ref("");
const paperTypeOrcResult = ref("");
const paperTypeType = ref("");
const paperTypeDisplay = computed(() => {
  if (paperTypeResult.value === "#") return "空";
  if (paperTypeResult.value === "?") return "异常";
  return paperTypeResult.value;
});
function onEditPaperType() {
  if (!dataCheckStore.curPage) return;
  modifyPaperTypeRef.value?.open();
}
const curPage = computed(() => dataCheckStore.curPage);
async function paperTypeModified(paperType: string) {
  if (!dataCheckStore.curStudent) return;

  await dataCheckStore.updateField({
    field: "PAPER_TYPE",
    value: JSON.stringify({
      type: paperTypeType.value,
      result: paperType || "#",
    }),
  });
  dataCheckStore.modifyPaperType(paperType);
  paperTypeResult.value = paperType;
}

watch(
  () => dataCheckStore.curStudent,
  async (val) => {
    paperTypeArea.value = null;
    if (!val) return;

    // 只取第一张第一页的数据
    const curStudentFirstPage = val.papers[0]?.pages[0];
    if (!curStudentFirstPage) return;

    paperTypeResult.value = curStudentFirstPage.paperType.result;
    paperTypeType.value = curStudentFirstPage.paperType.type;
    const recogData = curStudentFirstPage.recogData;
    const regdata = parseRecogData(recogData);
    if (!regdata) return;

    // console.log(regdata);
    paperTypeOrcResult.value = regdata.paperType.content;
    if (!paperTypeOrcResult.value) paperTypeOrcResult.value = "空";

    const rect = regdata.paperType.rect || null;
    if (!rect) {
      paperTypeArea.value = null;
      paperTypeImg.value = "";
      return;
    }

    const hasArea = rect.some((item) => item);
    paperTypeArea.value = hasArea
      ? {
          x: rect[0],
          y: rect[1],
          w: rect[2],
          h: rect[3],
        }
      : null;

    if (paperTypeArea.value) {
      paperTypeImg.value = await getSliceFileUrl(
        curStudentFirstPage.sheetUri,
        paperTypeArea.value
      );
    } else {
      paperTypeImg.value = "";
    }
  },
  {
    immediate: true,
  }
);

watch(
  () => props.questions,
  (val) => {
    if (!val) return;
    questionList.value = [...val];
  },
  {
    immediate: true,
  }
);

watch(
  () => props.info,
  (val) => {
    examStatus.value = val.examStatus;
  }
);
onMounted(() => {
  if (props.info?.examStatus) {
    examStatus.value = props.info?.examStatus;
  }
});
</script>

<style lang="less" scoped>
.question-panel {
  .panel-body {
    margin: 15px -14px 0;
    padding: 0 14px;
    border-top: 1px solid @border-color1;
    position: relative;
    font-size: 0;

    &-title {
      padding: 12px 0 8px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 14px;

      > p {
        color: @text-color3;
      }
    }

    .question-item {
      display: inline-block;
      vertical-align: middle;
      width: 20%;
      font-size: 14px;
      margin-bottom: 12px;

      > span {
        display: inline-block;
        width: 30px;
        padding-right: 4px;
        text-align: right;
        font-size: 13px;
      }
      .ant-btn {
        padding-left: 10px;
        padding-right: 10px;

        &.is-active {
          border-color: @brand-color;
        }
      }
    }
    .queston-edit {
      position: absolute;
      width: 165px;
      background: #f2f3f5;
      box-shadow: 0px 4px 8px 0px rgba(54, 61, 89, 0.2);
      border-radius: 8px;
      padding: 8px;
      border: 1px solid @border-color1;
      z-index: 9;
    }
  }

  :deep(.ant-descriptions-row) {
    .ant-descriptions-item {
      padding-bottom: 8px;
      .ant-descriptions-item-label {
        display: block;
        color: @text-color2;
      }
      .ant-descriptions-item-label::after {
        margin-inline: 2px 4px;
      }

      &:first-child {
        .ant-descriptions-item-label {
          width: 66px;
          text-align: right;
        }
      }
    }
    .ant-descriptions-item-content {
      align-items: center;
    }

    .ant-radio-wrapper span.ant-radio + * {
      padding-inline-start: 4px;
      padding-inline-end: 4px;
    }
  }

  :deep(.ant-descriptions-row:nth-of-type(2)) {
    .ant-descriptions-item {
      padding-bottom: 4px;
    }
  }

  :deep(.ant-descriptions-row:last-child) {
    .ant-descriptions-item {
      padding-bottom: 0;

      .ant-descriptions-item-container {
        align-items: center;
      }

      .ant-descriptions-item-label {
        line-height: 28px;
      }

      .ant-btn {
        padding: 2px 6px;
        height: 28px;
        min-width: 28px;
      }
    }
  }
}
</style>
