<template>
  <div class="about main-background main-background-type0">
    <div class="nav-placeholder" />
    <section class="main-section large">
      <div class="content">
        <div class="title left-right">
          <a-button :icon="h(ArrowLeftOutlined)" @click="router.back()">返回</a-button>
          <h2>自查评估表</h2>
          <div class="w-20"></div>
        </div>
        <a-spin :spinning="loader.loading.value">
          <a-result
            v-if="!currentForm"
            status="info"
            title="您还未填写评估表"
          >
            <template #extra>
              <a-button type="primary" @click="createForm">去填写评估表</a-button>
            </template>
          </a-result>
          <div v-else>
            <SelfAssessmentFormDisplay
              ref="blockRef"
              :current-form="(currentForm as SelfAssessmentDetail)"
              :check-item-list="(checkItemList as CheckItemInfo[])"
              :current-form-check-items="(currentFormCheckItems as SelfAssessmentCheckItemAnswer[])"
              :readonly="false"
            />
            <a-divider />
            <a-typography-title :level="4">各级审核意见（待终审填写）</a-typography-title>
            <div v-for="(sec, secIdx) in externalReviewSectionTitles" :key="secIdx" class="mb-6">
              <a-typography-text strong>{{ sec.title }}</a-typography-text>
              <a-input v-model:value="sec.suggestion" :disabled="sec.disabled" placeholder="(待终审填写)" class="mt-2" />
              <a-space class="mt-2" wrap>
                <a-checkbox v-for="(label, i) in externalReviewScoreRow1" :key="`r1-${i}`" disabled :checked="false">{{ label }}</a-checkbox>
              </a-space>
              <a-space class="mt-2" wrap>
                <a-checkbox v-for="(label, i) in externalReviewScoreRow2" :key="`r2-${i}`" disabled :checked="false">{{ label }}</a-checkbox>
              </a-space>
              <div class="text-end text-secondary mt-2 text-sm">填写单位（盖章）　年　月　日</div>
            </div>
            <a-divider />
            <a-space direction="vertical" class="w-full" size="middle">
              <a-button type="primary" block :loading="submitLoading" @click="saveForm">保存评估表</a-button>
              <a-button type="primary" block :loading="submitLoading" @click="submitForm">提交审核</a-button>
              <a-button block :loading="submitLoading" @click="downloadForm">下载评估表 PDF</a-button>
            </a-space>
          </div>
        </a-spin>
      </div>
    </section>
  </div>
</template>

<script setup lang="ts">
import { computed, h, onMounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { message, Modal } from 'ant-design-vue';
import { waitTimeOut } from '@imengyu/imengyu-utils';
import { RequestApiError } from '@imengyu/imengyu-utils';
import { ArrowLeftOutlined } from '@ant-design/icons-vue';
import { useAuthStore } from '@/stores/auth';
import AssessmentContentApi, {
  SelfAssessmentDetail,
  CheckItemInfo,
  SelfAssessmentCheckItemAnswer,
} from '@/api/collect/AssessmentContent';
import SelfAssessmentFormDisplay from './components/SelfAssessmentFormDisplay.vue';
import { useSimpleDataLoader } from '@/composeables/useSimpleDataLoader';
import { injectAppConfiguration } from '@/api/system/useAppConfiguration.ts';

function formatErr(e: unknown): string {
  if (e instanceof RequestApiError)
    return e.errorMessage;
  if (e instanceof Error)
    return e.message;
  return String(e);
}

const router = useRouter();
const route = useRoute();
const authStore = useAuthStore();
const appConfiguration = injectAppConfiguration();

const queryId = computed(() => Number(route.query.id) || 0);
const queryUserId = computed(() => Number(route.query.userId) || 0);

const currentForm = ref<SelfAssessmentDetail | null>(null);
const currentFormCheckItems = ref([] as SelfAssessmentCheckItemAnswer[]);
const checkItemList = ref([] as CheckItemInfo[]);

const blockRef = ref<InstanceType<typeof SelfAssessmentFormDisplay> | null>(null);
const submitLoading = ref(false);

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;

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 uid = authStore.userInfo?.id ?? authStore.userId;
  const basicInfo = await AssessmentContentApi.getInheritorBasic(uid);
  const f = currentForm.value;
  if (!f)
    return;
  f.inheritor = basicInfo.name;
  f.unit = basicInfo.unit;
  f.ichName = basicInfo.ichName;
  f.mobile = basicInfo.mobile;
  f.level = basicInfo.level;
  f.idCard = basicInfo.idCard;
  f.address = basicInfo.address;
  
}

async function loadCheckItems() {
  const f = currentForm.value;
  if (!f)
    return;
  const { top } = await AssessmentContentApi.getCheckItems(Number(f.level));
  checkItemList.value = top as CheckItemInfo[];
  currentFormCheckItems.value = [...f.checkItems] as SelfAssessmentCheckItemAnswer[];
}

async function createForm() {
  const uid = authStore.userInfo?.id ?? authStore.userId;
  const detail = new SelfAssessmentDetail();
  detail.userId = uid;
  detail.year = appConfiguration.value?.collectFormYear || new Date().getFullYear();
  detail.checkItems = [];
  currentForm.value = detail;
  loadEditorContent();
  await loadBasicInfo();
  await loadCheckItems();
}

async function saveForm() {
  try {
    await blockRef.value?.validate();
  } catch (e: unknown) {
    if (e && typeof e === 'object' && 'errorFields' in (e as object))
      message.warning('请填写完整信息');
    else if (e instanceof Error)
      message.warning(e.message);
    else
      message.warning('请填写完整信息');
    return;
  }
  submitLoading.value = true;
  const cf = currentForm.value;
  if (!cf) {
    submitLoading.value = false;
    return;
  }
  cf.checkItems = currentFormCheckItems.value;
  try {
    await AssessmentContentApi.saveSelfAssessment(cf as SelfAssessmentDetail);
    message.success('保存评估表成功');
    await waitTimeOut(500);
    await loader.load();
  } catch (error) {
    Modal.error({
      title: '保存评估表失败',
      content: formatErr(error),
    });
  }
  submitLoading.value = false;
}

async function submitForm() {
  try {
    await blockRef.value?.validate();
  } catch (e: unknown) {
    if (e && typeof e === 'object' && 'errorFields' in (e as object))
      message.warning('请填写完整信息');
    else if (e instanceof Error)
      message.warning(e.message);
    else
      message.warning('请填写完整信息');
    return;
  }
  submitLoading.value = true;
  const cf = currentForm.value;
  if (!cf) {
    submitLoading.value = false;
    return;
  }
  cf.checkItems = currentFormCheckItems.value;
  try {
    await AssessmentContentApi.saveSelfAssessment(cf as SelfAssessmentDetail, 1);
    message.success('提交审核成功');
    await waitTimeOut(500);
    await loader.load();
  } catch (error) {
    Modal.error({
      title: '提交审核失败',
      content: formatErr(error),
    });
  }
  submitLoading.value = false;
}

async function downloadForm() {
  if (!currentForm.value?.id) {
    message.warning('请先保存评估表后再下载 PDF');
    return;
  }
  try {
    await AssessmentContentApi.downloadSelfAssessmentPdf(currentForm.value.id);
    message.success('已开始下载');
  } catch (error) {
    Modal.error({
      title: '下载评估表失败',
      content: formatErr(error),
    });
  }
}

const loader = useSimpleDataLoader(async () => {
  if (queryId.value > 0) {
    const detail = await AssessmentContentApi.getSelfAssessmentDetail(queryId.value, queryUserId.value || undefined);
    currentForm.value = detail;
    loadEditorContent();
    await loadCheckItems();
    return currentForm.value;
  }
  const uid = authStore.userInfo?.id ?? authStore.userId;
  const basicInfo = await AssessmentContentApi.getInheritorBasic(uid);
  if (basicInfo.checkId > 0) {
    const detail = await AssessmentContentApi.getSelfAssessmentDetail(basicInfo.checkId, uid);
    currentForm.value = detail;
    console.log(currentForm.value);
    loadEditorContent();
    await loadCheckItems();
  } else {
    currentForm.value = null;
  }
  return currentForm.value;
}, {
  immediate: false,
});

onMounted(() => {
  loader.load();
});

watch(
  () => [queryId.value, queryUserId.value],
  () => {
    loader.load();
  },
);
</script>

<style scoped>
.total-points {
  font-size: 1.75rem;
  color: #315816;
  font-weight: 600;
}
</style>
