<template>
  <a-modal
    v-model:open="visible"
    :width="456"
    centered
    wrapClassName="modify-paper-type"
    @ok="confirm"
  >
    <template #title> 更改卷型号 </template>

    <a-form ref="formRef" :label-col="{ style: { width: '90px' } }">
      <a-form-item label="识别结果">
        <a-input
          v-if="editing"
          v-model:value="paperType"
          style="width: 100px"
        />
        <span v-else class="color-brand">{{ areaResult || "#" }}</span>
        <qm-button class="ml-15px" @click="toggleEditing">{{
          editing ? "取消" : "编辑"
        }}</qm-button>
      </a-form-item>
      <a-form-item label="识别图片">
        <div class="paper-type-img">
          <img v-if="areaImg" :src="areaImg" alt="识别图片" />
        </div>
      </a-form-item>
      <a-form-item label="更改卷型">
        <ul class="type-list">
          <li
            :class="['type-item', { 'is-active': paperType === '' }]"
            @click="selectPaperType('')"
          >
            空
          </li>
          <li
            v-for="item in paperTypeBarcodeContent"
            :key="item"
            :class="['type-item', { 'is-active': paperType === item }]"
            @click="selectPaperType(item)"
          >
            {{ item }}
          </li>
        </ul>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import { message } from "ant-design-vue";

import { getBaseDataConfig } from "@/ap/baseDataConfig";
import { useUserStore } from "@/store";
import useModal from "@/hooks/useModal";

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

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

const props = defineProps<{
  areaImg: string;
  areaResult: string;
}>();

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

const paperTypeBarcodeContent = ref<string[]>([]);
const userStore = useUserStore();
const paperType = ref("");

async function getConfig() {
  const res = await getBaseDataConfig({ examId: userStore.curExam.id });
  paperTypeBarcodeContent.value = res.paperTypeBarcodeContent || [];
}

function selectPaperType(val: string) {
  paperType.value = val;
}
let oldPaperType: string = "";
const toggleEditing = () => {
  if (!editing.value) {
    oldPaperType = paperType.value;
  } else {
    paperType.value = oldPaperType;
  }
  editing.value = !editing.value;
};
function confirm() {
  // if (!paperType.value) {
  //   message.error("请选择卷型");
  //   return;
  // }
  emit("confirm", paperType.value);
  editing.value = false;
  oldPaperType = "";
  close();
}

watch(
  () => visible.value,
  (val) => {
    if (val) {
      paperType.value = props.areaResult || "";
    }
  },
  {
    immediate: true,
  }
);

onMounted(() => {
  getConfig();
});
</script>
