<template>
  <CommonRoot>
    <FlexCol padding="space.lg">
      <SimplePageContentLoader :loader="loader">
        <template v-if="loader.isFinished.value">
          <Result
            v-if="!currentForm"
            status="info"
            title="您还未填写评估表"
          >
            <Height :height="30" />
            <Button type="primary" @click="createForm">去填写评估表</Button>
          </Result>
          <FlexCol v-else gap="gap.lg">
            <SelfAssessmentFormDisplay
              ref="blockRef"
              :current-form="(currentForm as SelfAssessmentDetail)"
              :form-options="formOptions"
              :form-options-end="formOptionsEnd"
              :check-item-list="(checkItemList as CheckItemInfo[])"
              :current-form-check-items="(currentFormCheckItems as SelfAssessmentCheckItemAnswer[])"
              :readonly="false"
            />
            <Divider />
            <FlexCol gap="gap.lg">
              <FlexCol v-for="(title, secIdx) in externalReviewSectionTitles" :key="secIdx" gap="gap.sm">
                <Text bold :text="title.title" />
                <Field v-model="title.suggestion" :disabled="title.disabled" placeholder="(待终审填写)" />
                <FlexRow wrap align="center" gap="gap.md">
                  <CheckBox
                    v-for="(label, i) in externalReviewScoreRow1"
                    :key="`${secIdx}-r1-${i}`"
                    disabled
                    :model-value="false"
                    :text="label"
                    :check-size="28"
                  />
                </FlexRow>
                <FlexRow wrap align="center" gap="gap.md">
                  <CheckBox
                    v-for="(label, i) in externalReviewScoreRow2"
                    :key="`${secIdx}-r2-${i}`"
                    disabled
                    :model-value="false"
                    :text="label"
                    :check-size="28"
                  />
                </FlexRow>
                <FlexCol align="flex-end">
                  <Text color="text.second" text="填写单位（盖章）" />
                  <Text color="text.second" text="年　月　日" />
                </FlexCol>
              </FlexCol>
            </FlexCol>
            <Divider />
            <Button type="primary" block :loading="submitLoading" @click="saveForm">保存评估表</Button>
            <Button :loading="submitLoading" @click="downloadForm">下载评估表PDF</Button>
          </FlexCol>
        </template>
      </SimplePageContentLoader>
      <XBarSpace />
    </FlexCol>
  </CommonRoot>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';
import { useSimpleDataLoader } from '@/components/composeabe/loader/SimpleDataLoader';
import { useAuthStore } from '@/store/auth';
import { useLoadQuerys } from '@/components/composeabe/LoadQuerys';
import { assertNotNull, formatError, waitTimeOut } from '@imengyu/imengyu-utils';
import { toast, alert } from '@/components/dialog/CommonRoot';
import AssessmentContentApi, {
  SelfAssessmentDetail,
  CheckItemInfo,
  SelfAssessmentCheckItemAnswer,
} from '@/api/collect/AssessmentContent';
import CommonRoot from '@/components/dialog/CommonRoot.vue';
import Button from '@/components/basic/Button.vue';
import Result from '@/components/feedback/Result.vue';
import FlexCol from '@/components/layout/FlexCol.vue';
import Height from '@/components/layout/space/Height.vue';
import SimplePageContentLoader from '@/components/loader/SimplePageContentLoader.vue';
import FlexRow from '@/components/layout/FlexRow.vue';
import Text from '@/components/basic/Text.vue';
import XBarSpace from '@/components/layout/space/XBarSpace.vue';
import Divider from '@/components/display/Divider.vue';
import CheckBox from '@/components/form/CheckBox.vue';
import Field from '@/components/form/Field.vue';
import SelfAssessmentFormDisplay from './components/SelfAssessmentFormDisplay.vue';
import { buildSelfAssessmentFormOptions } from './evaluationFormOptions';
import { useImageSimpleUploadCo } from '@/common/components/upload/ImageUploadCo';

/** 评估表下方展示用：各级审核意见（不接数据、禁用） */
const externalReviewSectionTitles = ref([
  { title: '1. 项目保护单位意见', suggestion: '', disabled: false },
  { title: '2. 县（区）文旅部门审核意见', suggestion: '', disabled: true },
  { title: '3. 设区市文旅部门、省非遗中心审核意见', suggestion: '', disabled: true },
]);
const externalReviewScoreRow1 = ['优秀', '合格', '不合格'] as const;
const externalReviewScoreRow2 = ['丧失传承能力', '取消资格'] as const;

let loaded = false;

const { querys } = useLoadQuerys({
  id: 0,
  userId: 0,
}, () => {
  if (loaded)
    return;
  loaded = true;
  loader.load();
});

const currentForm = ref<SelfAssessmentDetail | null>(null);
const currentFormCheckItems = ref<SelfAssessmentCheckItemAnswer[]>([]);
const authStore = useAuthStore();

const currentYear = new Date().getFullYear();

const blockRef = ref<InstanceType<typeof SelfAssessmentFormDisplay> | null>(null);
const signUploadCo = useImageSimpleUploadCo();
const formOptions = buildSelfAssessmentFormOptions(signUploadCo, 'start');
const formOptionsEnd = buildSelfAssessmentFormOptions(signUploadCo, 'end');

const checkItemList = ref<CheckItemInfo[]>([]);
const levelTitle = computed(() => {
  if (currentForm.value?.level === 23) return '国家级';
  if (currentForm.value?.level === 24) return '省级';
  if (currentForm.value?.level === 25) return '市级';
  return '国家级';
});

function loadEditorContent() {
  if (!currentForm.value)
    return;
  if (typeof currentForm.value.content !== 'object' || currentForm.value.content === null) {
    currentForm.value!.content = {};
  }
  currentForm.value!.content.title = `传承人填写${currentYear}年1月1日至${currentYear}年12月31日${levelTitle.value}非遗传承人义务履行和传承补助经费使用情况等，不超过1000字，如未履行职责请进行说明。参考提纲如下:`;
  for (let i = 0; i < 8; i++) {
    if (typeof currentForm.value.content[`item${i}`] !== 'string') {
      currentForm.value.content[`item${i}`] = '';
    }
  }
}
async function loadBasicInfo() {
  const basicInfo = await AssessmentContentApi.getInheritorBasic(authStore.userInfo?.id);
  assertNotNull(currentForm.value, 'currentForm is null');
  currentForm.value.inheritor = basicInfo.name;
  currentForm.value.unit = basicInfo.unit;
  currentForm.value.ichName = basicInfo.ichName;
  currentForm.value.mobile = basicInfo.mobile;
  currentForm.value.level = basicInfo.level;
  currentForm.value.idCard = basicInfo.idCard;
  currentForm.value.address = basicInfo.address;
}
async function loadCheckItems() {
  assertNotNull(currentForm.value, 'currentForm is null');
  const { top } = await AssessmentContentApi.getCheckItems(Number(currentForm.value.level));
  checkItemList.value = top;
  currentFormCheckItems.value = currentForm.value.checkItems.concat();
}

const submitLoading = ref(false);

async function createForm() {
  const detail = new SelfAssessmentDetail();
  detail.userId = authStore.userInfo!.id;
  detail.year = new Date().getFullYear();
  detail.checkItems = [];
  currentForm.value = detail;
  loadEditorContent();
  await loadBasicInfo();
  await loadCheckItems();
}
async function saveForm() {
  const detail = currentForm.value;
  try {
    await blockRef.value?.validate();
  } catch (error) {
    toast('请填写完整信息');
    return;
  }

  submitLoading.value = true;
  currentForm.value!.checkItems = currentFormCheckItems.value;
  try {
    assertNotNull(detail, 'currentForm is null');
    await AssessmentContentApi.saveSelfAssessment(detail as SelfAssessmentDetail);
    toast('保存评估表成功');

    await waitTimeOut(1000);
    await loader.reload();
  } catch (error) {
    alert({
      title: '保存评估表失败',
      content: formatError(error),
    });
  }

  submitLoading.value = false;
}
async function downloadForm() {
  if (!currentForm.value?.id) {
    toast('请先保存评估表后再下载PDF');
    return;
  }
  try {
    assertNotNull(currentForm.value, 'currentForm is null');
    const pdfPath = await AssessmentContentApi.downloadSelfAssessmentPdf(currentForm.value.id);
    uni.openDocument({
      filePath: pdfPath,
      fileType: 'pdf',
      showMenu: true,
    });
  } catch (error) {
    alert({
      title: '下载评估表失败',
      content: formatError(error),
    });
  }
}

const loader = useSimpleDataLoader(async () => {
  await waitTimeOut(1000);
  
  if (querys.value.id > 0) {
    const detail = await AssessmentContentApi.getSelfAssessmentDetail(querys.value.id, querys.value.userId);
    currentForm.value = detail;
    loadEditorContent();
    await loadCheckItems();
    return;
  }
  const basicInfo = await AssessmentContentApi.getInheritorBasic(authStore.userInfo?.id);
  if (basicInfo.checkId > 0) {
    const detail = await AssessmentContentApi.getSelfAssessmentDetail(
      basicInfo.checkId,
      authStore.userInfo?.id
    );
    currentForm.value = detail;
    loadEditorContent();
    await loadCheckItems();
  } else {
    currentForm.value = null;
  }
  return currentForm.value;
}, false);
</script>
