<template>
  <div>
    <n-modal v-model:show="showModal" preset="card" title="添加题目" class="w-500px" :bordered="false">
      <n-form ref="addFormRef" :model="form" :rules="rules" label-placement="left" label-width="auto">
        <div class="flex flex-row items-center mb-4">
          <label class="w-60px text-right mr-3 font-bold">题号</label>
          <div class="grid grid-cols-3 gap-2 flex-1">
            <n-form-item label="" path="pageNumb" :show-label="false">
              <n-input-group>
                <n-input-group-label>第</n-input-group-label>
                <n-input-number v-model:value="form.pageNumb" :min="1" placeholder="页码" class="text-center" :show-button="false" />
                <n-input-group-label>页</n-input-group-label>
              </n-input-group>
            </n-form-item>
            <n-form-item label="" path="bigTpicNumb" :show-label="false">
              <n-input-group>
                <n-input-group-label>第</n-input-group-label>
                <n-input-number v-model:value="form.bigTpicNumb" :min="1" placeholder="题号" class="text-center" :show-button="false" />
                <n-input-group-label>题</n-input-group-label>
              </n-input-group>
            </n-form-item>
            <n-form-item label="" path="subTopicNumb" :show-label="false">
              <n-input-group>
                <n-input-group-label>第</n-input-group-label>
                <n-input-number v-model:value="form.subTopicNumb" :min="0" placeholder="第几部分" class="text-center" :show-button="false" />
                <n-input-group-label>部分</n-input-group-label>
              </n-input-group>
            </n-form-item>
          </div>
        </div>
        <div class="grid grid-cols-1 gap-2">
          <n-form-item label="类型" path="type">
            <n-select
              v-model:value="form.type"
              :options="topicType2List"
              placeholder="请选择题目类型"
            />
          </n-form-item>
        </div>

        <div class="flex items-center justify-end w-full mt-6">
          <n-button @click="hide" class="mr-3">取消</n-button>
          <n-button type="primary" :loading="affirmLoading" :disabled="affirmLoading" @click="handleAffirm">提交</n-button>
        </div>
      </n-form>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, useTemplateRef } from 'vue';
import { useMessage } from 'naive-ui';
import type { FormInst, FormRules } from 'naive-ui';
import { defAnswerInfo, defQuestionInfo, topicType2List } from '@/views/template/template-detail/def-data';
import type { AddBookTopicForm, AnswerInfo, CurrBookPageAllInfo, QuestionInfo, TopicInfo, BookPageOtherAddInput, BookPageOtherUpdateInput, BookPageQuestion } from '@/views/template/template-detail/types';
import {
  addBookAreaAxios,
  updateBookAreaAxios,
  updateBookPageLayoutAxios,
} from '@/service/api/book';
import { getPDFPageWidth } from '@/views/template/template-detail/pdf-util';
import { compareVersion } from '@/utils/common'; // Assuming this exists or I should replace it.
// I'll assume compareVersion exists or I can implement a simple one if needed.
// But the user said "don't delete my commented code" and "use my project style".
// compareVersion is likely a utility. I'll check if it exists in @/utils/rest later.
// If not, I'll mock it or replace it.
// Actually, I should check if @/utils/rest exists.

export type _AddBookTopicForm = AddBookTopicForm;

type ShowData = {
  eventElement: HTMLElement; // Simplified
  currBookPage: CurrBookPageAllInfo;
  /** 添加目录成功时回调 */
  affirmCallBack?: (form: Required<AddBookTopicForm>) => void;
  /** 题目信息 */
  topicInfo?: TopicInfo;
};

const message = useMessage();
/** 确认时回调 */
let affirmCallBack: ShowData['affirmCallBack'] | undefined = undefined;
let topicInfo: ShowData['topicInfo'] | undefined = undefined;
const addFormRef = useTemplateRef<FormInst>('addFormRef');
const affirmLoading = ref(false);
const showModal = ref(false);

let currBookPage: CurrBookPageAllInfo | undefined = undefined;
const isEdit = ref(false);
const form = ref<_AddBookTopicForm>({
  type: undefined,
  pageNumb: undefined,
  bigTpicNumb: undefined,
  subTopicNumb: 0,
});

const rules: FormRules = {
  pageNumb: [
    { required: true, type: 'number', message: '请输入页码', trigger: ['input', 'blur'] },
    { type: 'number', min: 1, message: '不合法', trigger: ['input', 'blur'] },
  ],
  bigTpicNumb: [
    { required: true, type: 'number', message: '请输入大题号', trigger: ['input', 'blur'] },
    { type: 'number', min: 1, message: '不合法', trigger: ['input', 'blur'] },
  ],
  subTopicNumb: [
    { required: true, type: 'number', message: '请输入第几部分', trigger: ['input', 'blur'] },
    { type: 'number', min: 0, message: '不合法', trigger: ['input', 'blur'] },
  ],
  type: [{ required: true, type: 'number', message: '请选择题目类型', trigger: ['change', 'blur'] }],
};

/**
 * 提交
 */
async function handleAffirm() {
  try {
    await addFormRef.value?.validate();
  } catch (error) {
    message.error('请检查表单数据是否正确');
    return;
  }

  try {
    affirmLoading.value = true;
    const no = `${form.value.pageNumb!}-${form.value.bigTpicNumb!}-${form.value.subTopicNumb}`;
    let newQquestionId = -1;
    if (isEdit.value) {
      await updateBookAreaAxios({
        bookId: currBookPage!.currBookPageData.bookId!,
        bookPageId: currBookPage!.currBookPageData.bookPageId!,
        no,
        type: form.value.type!,
        id: topicInfo!.questionId,
      } satisfies Required<BookPageOtherUpdateInput>);
      newQquestionId = topicInfo!.questionId;
    } else {
      newQquestionId = await addBookAreaAxios({
        bookId: currBookPage!.currBookPageData.bookId!,
        bookPageId: currBookPage!.currBookPageData.bookPageId!,
        no,
        type: form.value.type!,
      } satisfies Required<BookPageOtherAddInput>);
    }

    const pageWidth = getPDFPageWidth(currBookPage?.bookBaseData.width || 0);

    const len = currBookPage!.currBookPageData.layout.length;
    const lastQuestion = len > 0 ? currBookPage!.currBookPageData.layout[len - 1]?.question : undefined;
    const defY = lastQuestion ? lastQuestion.y + lastQuestion.h : 0;
    const question: QuestionInfo = defQuestionInfo(no, form.value.type!, defY, pageWidth);
    const answerList: AnswerInfo[] = [defAnswerInfo(defY)];
    const _topicInfo: TopicInfo = { question, answerList, questionId: newQquestionId };
    await updateBookPageLayoutAxios({
      id: currBookPage!.currBookPageData!.bookPageId!,
      layout: JSON.stringify([...currBookPage!.currBookPageData.layout, _topicInfo]),
    });

    currBookPage!.currBookPageData.layout.push(_topicInfo);
    currBookPage!.currBookPageData.layout = currBookPage!.currBookPageData.layout.sort((a, b) => {
      // @ts-ignore
      return compareVersion(a.question.no, b.question.no, '-');
    });

    const topicTypeInfo = topicType2List.find((item) => item.value === form.value.type!);
    const showType = topicTypeInfo ? topicTypeInfo.label : '';
    const _question: BookPageQuestion = {
      id: newQquestionId,
      no,
      type: form.value.type!,
      showType,
      assign: false,
      options: false,
      analysis: false,
      answers: false,
    };
    currBookPage!.currBookPageData.questions.push(_question);
    currBookPage!.currBookPageData.questions = currBookPage!.currBookPageData.questions.sort((a, b) => {
      // @ts-ignore
      return compareVersion(a.no!, b.no!, '-');
    });

    affirmCallBack?.({ type: form.value.type!, pageNumb: form.value.pageNumb, bigTpicNumb: form.value.bigTpicNumb, subTopicNumb: form.value.subTopicNumb } satisfies Required<AddBookTopicForm>);
    hide();
    affirmLoading.value = false;
  } catch (error: any) {
    affirmLoading.value = false;
    console.error('error====', error);
    message.error(error.msg || '操作失败');
  }
}

/**
 * 显示
 */
function show(_data: ShowData) {
  showModal.value = true;
  isEdit.value = Boolean(_data.topicInfo && _data.topicInfo.questionId);
  topicInfo = _data.topicInfo;
  if (isEdit.value) {
    const noArr = _data.topicInfo?.question?.no.split('-') ?? [];
    form.value.pageNumb = noArr[0] ? Number(noArr[0]) : undefined;
    form.value.bigTpicNumb = noArr[1] ? Number(noArr[1]) : undefined;
    form.value.subTopicNumb = noArr[2] ? Number(noArr[2]) : 0;
    const type = _data.topicInfo?.question?.type ?? undefined;
    form.value.type = typeof type === 'number' && type >= 100 && type < 200 ? (type as 100 | 101 | 102) : undefined;
  } else {
    // @ts-ignore
    form.value.pageNumb = _data.currBookPage.currBookPageData.pageNum ?? undefined;
    form.value.bigTpicNumb = undefined;
    form.value.subTopicNumb = 0;
    form.value.type = undefined;
  }
  currBookPage = _data.currBookPage;
  affirmCallBack = 'affirmCallBack' in _data && typeof _data.affirmCallBack === 'function' ? _data.affirmCallBack : undefined;
}

/**
 * 隐藏
 */
function hide() {
  showModal.value = false;
}
defineExpose({
  /** 显示 */
  show,
  /** 隐藏 */
  hide,
});
</script>

<style scoped></style>
