<template>
  <CommonRoot>
    <FlexCol padding="space.lg">
      <SimplePageContentLoader :loader="loader">
        <template v-if="loader.isLoaded.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 />
            <Button type="primary" block :loading="submitLoading" @click="saveForm">保存评估表</Button>
            <Button v-if="currentForm?.progress === 0" type="primary" block :loading="submitLoading" @click="submitForm">提交审核</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, confirm } 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 XBarSpace from '@/components/layout/space/XBarSpace.vue';
import Divider from '@/components/display/Divider.vue';
import SelfAssessmentFormDisplay from './components/SelfAssessmentFormDisplay.vue';
import { buildSelfAssessmentFormOptions } from './evaluationFormOptions';
import { useImageSimpleUploadCo } from '@/common/components/upload/ImageUploadCo';
import { injectAppConfiguration } from '@/api/system/useAppConfiguration';

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 appConfig = injectAppConfiguration();

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 = `传承人填写${currentForm.value.year}年1月1日至${currentForm.value.year}年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 = appConfig.value?.collectFormYear || 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;
  }
  if ((detail?.progress ?? 0) > 0) {
    const confirmed = await confirm({
      title: '提示',
      content: '您之前已提交审核，修改将导致审核撤回并需要重新审核，是否继续修改？',
    });
    if (!confirmed)
      return;
  }
  submitLoading.value = true;
  currentForm.value!.checkItems = currentFormCheckItems.value;
  try {
    assertNotNull(detail, 'currentForm is null');
    await AssessmentContentApi.saveSelfAssessment(detail as SelfAssessmentDetail, 0);
    toast('保存评估表成功');

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

  submitLoading.value = false;
}
async function submitForm() {
  const detail = currentForm.value;
  try {
    await blockRef.value?.validate();
  } catch (error) {
    toast('请填写完整信息');
    return;
  }
  const confirmed = await confirm({
    title: '提示',
    content: '您确认要提交审核吗？请确认各项信息填写无误。',
  });
  if (!confirmed)
    return;
  submitLoading.value = true;
  currentForm.value!.checkItems = currentFormCheckItems.value;
  try {
    assertNotNull(detail, 'currentForm is null');
    await AssessmentContentApi.saveSelfAssessment(detail as SelfAssessmentDetail, 1);
    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>
