<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.md">
            <EvaluationFormBlock
              :currentForm="(currentForm as SelfAssessmentDetail)"
              :formOptions="formOptions"
              :checkItemList="(checkItemList as CheckItemInfo[])"
              :currentFormCheckItems="(currentFormCheckItems as SelfAssessmentCheckItemAnswer[])"
            />
            <FlexRow align="center" justify="space-between">
              <H3>自评总分</H3>
              <Text fontSize="44rpx" fontFamily="HUNdin1451" :text="`${totalPoints}分`" />
            </FlexRow>
            <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 H3 from '@/components/typography/H3.vue';
import FlexRow from '@/components/layout/FlexRow.vue';
import Text from '@/components/basic/Text.vue';
import XBarSpace from '@/components/layout/space/XBarSpace.vue';
import type { IDynamicFormOptions, IDynamicFormRef } from '@/components/dynamic';
import type { RadioValueProps } from '@/components/dynamic/wrappers/RadioValue';
import type { FieldProps } from '@/components/form/Field.vue';
import type { SignatureFieldProps } from '@/components/form/SignatureField.vue';
import { useImageSimpleUploadCo } from '@/common/components/upload/ImageUploadCo';
import EvaluationFormBlock from './components/EvaluationFormBlock.vue';

let loaded = false;

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

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

const formRef = ref<IDynamicFormRef | null>(null);

const formOptions : IDynamicFormOptions = {
  formAdditionaProps: {
    labelFlex: 4,
    inputFlex: 8,
  },
  formItems: [
    {
      type: 'flat-group',
      label: '传承人自查评估',
      name: 'selfAssessmentGroup',
      childrenColProps: { span: 24 },
      children: [
        {
          label: '传承人名称',
          name: 'inheritor',
          type: 'text',
          additionalProps: { placeholder: '请输入传承人名称' },
        },
        {
          label: '项目保护单位',
          name: 'unit',
          type: 'text',
          additionalProps: { placeholder: '请输入项目保护单位' },
        },
        {
          label: '项目名称',
          name: 'ichName',
          type: 'text',
          additionalProps: { placeholder: '请输入项目名称' },
        },
        {
          label: '联系电话',
          name: 'mobile',
          type: 'text',
          additionalProps: { placeholder: '请输入联系电话' },
        },
        {
          label: '身份证号',
          name: 'idCard',
          type: 'text',
          additionalProps: { placeholder: '请输入身份证号' },
        },
        {
          label: '级别',
          name: 'level',
          type: 'select-id',
          additionalProps: {
            placeholder: '请选择级别',
            loadData: async () => [
              { text: '国家级', value: 23 },
              { text: '省级', value: 24 },
              { text: '市级', value: 25 },
            ],
          },
        },
        {
          label: '家庭住址',
          name: 'address',
          type: 'text',
          additionalProps: { placeholder: '请输入家庭住址' },
        },
        {
          label: '自评报告',
          name: 'content',
          type: 'richtext',
          additionalProps: { placeholder: '请填写自评报告' },
        },
      ],
    },
    {
      type: 'insertion',
      name: 'insertCheckList',
    },
    {
      type: 'flat-group',
      label: '传承人自查评估',
      name: 'selfAssessmentGroup',
      childrenColProps: { span: 24 },
      children: [
        {
          label: '其他相关情况(扣分内容)',
          name: 'deductContent',
          type: 'text',
          additionalProps: {
            showWordLimit: true,
            maxlength: 260,
            placeholder: '请输入其他相关情况(扣分内容)',
          } as FieldProps,
        },
        {
          label: '其他相关情况(扣分分值)',
          name: 'deductPoints',
          type: 'number',
          additionalProps: {
            placeholder: '请输入其他相关情况(扣分分值)',
            min: 0,
            max: 100,
          },
        },
        {
          label: '自我评估',
          name: 'self',
          type: 'radio-value',
          additionalProps: {
            options: [
              { text: '优秀', value: 1 },
              { text: '合格', value: 2 },
              { text: '不合格', value: 3 },
              { text: '丧失传承能力', value: 4 },
              { text: '取消资格', value: 5 },
            ],
            vertical: true,
          } as RadioValueProps,
        },
        {
          label: '传承人签名',
          name: 'sign',
          type: 'sign',
          formProps: {
            showRightArrow: true,
          },
          additionalProps: {
            upload: useImageSimpleUploadCo(),
          } as SignatureFieldProps,
        }
      ],
    },
  ],
  formRules: {
    inheritor: [{ required: true, message: '请输入传承人名称' }],
    unit: [{ required: true, message: '请输入项目保护单位' }],
    ichName: [{ required: true, message: '请输入项目名称' }],
    mobile: [{ required: true, message: '请输入联系电话' }],
    idCard: [{ required: true, message: '请输入身份证号' }],
    level: [{ required: true, message: '请选择级别' }],
    address: [{ required: true, message: '请输入家庭住址' }],
    content: [{ required: true, message: '请填写自评报告' }],
    self: [{ required: true, message: '请选择自我评估' }],
    sign: [{ required: true, message: '请传承人签名' }],
  },
};

const checkItemList = ref<CheckItemInfo[]>([]);

const totalPoints = computed(() => {
  if (!currentForm.value) 
    return 0;
  return currentFormCheckItems.value.reduce((acc, item) => acc + (item.count * item.points), 0);
});

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');
  checkItemList.value = await AssessmentContentApi.getCheckItems(Number(currentForm.value.level));
  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;
  await loadBasicInfo();
  await loadCheckItems();
}
async function saveForm() {
  const detail = currentForm.value;
  try {
    await formRef.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('保存评估表成功');
  } catch (error) {
    alert({
      title: '保存评估表失败',
      content: formatError(error),
    });
  }
  submitLoading.value = false;
}
async function downloadForm() {
  try {
    assertNotNull(currentForm.value, 'currentForm is null');
    throw new Error('没这个接口');
  } catch (error) {
    alert({
      title: '下载评估表失败',
      content: formatError(error),
    });
  }
}

const loader = useSimpleDataLoader(async () => {
  await waitTimeOut(1000);
  console.log('load');
  
  if (querys.value.id > 0) {
    const detail = await AssessmentContentApi.getSelfAssessmentDetail(querys.value.id);
    currentForm.value = detail;
    await loadCheckItems();
    return;
  }
  const list = await AssessmentContentApi.getSelfAssessmentList({
    userId: authStore.userInfo?.id,
    year: new Date().getFullYear(),
  });
  if (list.data.length > 0) {
    const detail = await AssessmentContentApi.getSelfAssessmentDetail(list.data[0].id);
    currentForm.value = detail;
    await loadCheckItems();
  } else {
    currentForm.value = null;
    createForm();
  }
  return currentForm.value;
}, false);
</script>
