<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">
            <DynamicForm
              ref="form1Ref"
              :model="currentForm"
              :options="formOptions"
            />
            <H3>自查项目选择</H3>
            <FlexCol gap="gap.md">
              <FlexCol v-for="(item, index) in checkItemList" :key="item.id" gap="gap.md">
                <Text fontConfig="subTitleText" :text="`${index + 1}. ${item.name}`" />
                <template v-if="item.checkType == 2">
                  <FlexCol gap="gap.sm">
                    <FlexRow v-for="child in item.children" :key="child.id" justify="space-between">
                      <CheckBox
                        :text="`${child.name} (${child.points}分)`"
                        :modelValue="hasCheckedItem(child.id)" 
                        @update:modelValue="setCheckedItem(item as CheckItemInfo, child as CheckItemInfo, $event)" 
                      />
                      <Stepper 
                        v-if="hasCheckedItem(child.id)"
                        :min="0"
                        :max="20"
                        :step="1"
                        :modelValue="getCheckedItemCount(child.id) ?? 0" 
                        @update:modelValue="setCheckedItem(item as CheckItemInfo, child as CheckItemInfo, $event)" 
                      />
                      <view v-else></view>
                    </FlexRow>
                  </FlexCol>
                </template>
                <template v-else>
                  <FlexCol gap="gap.sm">
                    <CheckBox 
                      v-for="child in item.children" :key="child.id"
                      :text="`${child.name} (${child.points}分)`"
                      :modelValue="hasCheckedItem(child.id)" 
                      @update:modelValue="setCheckedItem(item as CheckItemInfo, child as CheckItemInfo, $event)" 
                    />
                  </FlexCol>
                </template>
              </FlexCol>
            </FlexCol>
            <DynamicForm
              ref="form3Ref"
              :model="currentForm"
              :options="formOptionsEnd"
            />
            <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 { ArrayUtils, assertNotNull, formatError } 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 DynamicForm from '@/components/dynamic/DynamicForm.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 CheckBox from '@/components/form/CheckBox.vue';
import Stepper from '@/components/form/Stepper.vue';
import type { IDynamicFormOptions, IDynamicFormRef } from '@/components/dynamic';
import type { RadioValueProps } from '@/components/dynamic/wrappers/RadioValue';
import type { FieldProps } from '@/components/form/Field.vue';

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

const currentForm = ref<SelfAssessmentDetail | null>(null);
const authStore = useAuthStore();

const form1Ref = ref<IDynamicFormRef | null>(null);
const form3Ref = ref<IDynamicFormRef | null>(null);

const formOptions = ref<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: '请填写自评报告' },
        },
      ],
    },
  ],
  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: '请选择自我评估' }],
  },
});
const formOptionsEnd = ref<IDynamicFormOptions>({
  formAdditionaProps: {
    labelPosition: 'top',
  },
  formItems: [
    {
      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',
          additionalProps: {
            placeholder: '请签名',
          } as FieldProps,
        }
      ],
    },
  ],
  formRules: {
    self: [{ required: true, message: '请选择自我评估' }],
    sign: [{ required: true, message: '请传承人签名' }],
  },
});
const checkItemList = ref<CheckItemInfo[]>([]);

const totalPoints = computed(() => {
  if (!currentForm.value) 
    return 0;
    console.log(currentForm.value?.checkItems);
  return Object.values(currentForm.value.checkItems).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));
}
function hasCheckedItem(id: number) {
  return currentForm.value?.checkItems.some(item => item.id === id);
}
function getCheckedItemCount(id: number) {
  return currentForm.value?.checkItems.find(item => item.id === id)?.count;
}
function setCheckedItem(checkItem: CheckItemInfo, childItem: CheckItemInfo, count: number|boolean) {
  if (!currentForm.value)
    return;
  if (typeof count === 'boolean') {
    count = count ? 1 : 0;
  }
  let item = currentForm.value.checkItems.find(item => item.id === childItem.id);
  if (!item) {
    item = new SelfAssessmentCheckItemAnswer();
    currentForm.value.checkItems.push(item);
  }
  item.id = childItem.id;
  item.points = childItem.points;
  item.count = count;
  switch (checkItem.checkType) {
    case 1: {
      /** 单选,清除其他选项 */
      const allChildren = checkItem.children.map(child => child.id);
      currentForm.value?.checkItems.forEach(item => {
        if (allChildren.includes(item.id) && item.id !== childItem.id)
          item.count = 0;
      });
      break;
    }
  }
  if (item.count === 0)
    ArrayUtils.remove(currentForm.value.checkItems, item);
}

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 form1Ref.value?.validate();
    await form3Ref.value?.validate();
  } catch (error) {
    toast('请填写完整信息');
    return;
  }

  submitLoading.value = true;

  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 () => {
  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>
