<template>
  <div>
    <a-form
      v-if="currentAgreement"
      ref="formRef"
      :model="currentAgreement"
      :rules="formRules"
      layout="vertical"
    >
      <a-typography-title class="mt-5!" :level="4">{{ agreementTitle }}</a-typography-title>

      <AgreementBodyNational
        v-if="currentAgreement?.level === 23"
        :detail="(currentAgreement as AgreementDetail)"
        :agreement-year="agreementYear"
        :isReviewer="isReviewer"
      />
      <AgreementBodyProvincial
        v-else-if="currentAgreement?.level === 24"
        :detail="(currentAgreement as AgreementDetail)"
        :agreement-year="agreementYear"
        :isReviewer="isReviewer"
      />
      <AgreementBodyMunicipal
        v-else-if="currentAgreement?.level === 25"
        :detail="(currentAgreement as AgreementDetail)"
        :agreement-year="agreementYear"
        :isReviewer="isReviewer"
      />

      <a-divider />

      <AgreementBody>
        <a-form-item label="甲方" name="partyA">
          <a-input v-model:value="currentAgreement.partyA" :readonly="!isReviewer" />
        </a-form-item>
        <a-form-item label="负责人（代表人）签名" name="partyASign">
          <Sign 
            v-if="isReviewer || currentAgreement.partyASign" :model-value="currentAgreement.partyASign ?? ''" 
            :disabled="!isReviewer"
            @update:model-value="(v) => { currentAgreement.partyASign = v }" 
          />
          <span v-else>待审核人员签名</span>
        </a-form-item>
        <a-form-item label="甲方电话" name="partyAMobile">
          <a-input v-model:value="currentAgreement.partyAMobile" :placeholder="isReviewer ? '请填写联系电话' : '待审核人员填写'" :disabled="!isReviewer" />
        </a-form-item>

        <a-divider />

        <a-typography-paragraph strong>乙方：{{ currentAgreement.partyB }}（签名）</a-typography-paragraph>
        <a-form-item label="乙方签名" name="partyBSign">
          <Sign :model-value="currentAgreement.partyBSign ?? ''" :readonly="isReviewer" @update:model-value="(v) => { currentAgreement.partyBSign = v }" />
        </a-form-item>
        <a-form-item label="身份证号" name="idCard">
          <a-input v-model:value="currentAgreement.idCard" :readonly="isReviewer" placeholder="请填写身份证号" />
        </a-form-item>
        <a-form-item label="项目名称" name="ich">
          <a-input v-model:value="currentAgreement.ich" :readonly="isReviewer" placeholder="非遗项目名称" />
        </a-form-item>
        <a-form-item label="身体状况" name="health">
          <a-input v-model:value="currentAgreement.health" :readonly="isReviewer" placeholder="请简要填写" />
        </a-form-item>
        <a-form-item label="乙方电话" name="mobile">
          <a-input v-model:value="currentAgreement.mobile" :readonly="isReviewer" placeholder="请填写联系电话" />
        </a-form-item>
        <a-form-item label="填报人联系方式" name="contactMobile">
          <a-input v-model:value="currentAgreement.contactMobile" :readonly="isReviewer" placeholder="请填写手机号" />
          <template v-if="!isReviewer" #extra>
            用于消息通知，若有审核回退或通过，会以短信方式通知您
          </template>
        </a-form-item>
      </AgreementBody>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import type { AgreementDetail } from '@/api/collect/AssessmentContent';
import AgreementBodyNational from './AgreementBodyNational.vue';
import AgreementBodyProvincial from './AgreementBodyProvincial.vue';
import AgreementBodyMunicipal from './AgreementBodyMunicipal.vue';
import AgreementBody from './AgreementBody.vue';
import { Sign } from '@imengyu/vue-dynamic-form-rich';
import { computed, ref } from 'vue';
import type { Rules } from 'async-validator';
import type { FormInstance } from 'ant-design-vue';

const props = withDefaults(defineProps<{
  currentAgreement: AgreementDetail;
  isReviewer?: boolean;
}>(), {
  isReviewer: false,
});

const agreementYear = computed(() => props.currentAgreement?.year ?? 2027);
const agreementTitle = computed(
  () => `${agreementYear.value} 年度${levelTitle.value}非物质文化遗产代表性传承人传承协议`,
);
const levelTitle = computed(() => {
  if (props.currentAgreement?.level === 23) return '国家级';
  if (props.currentAgreement?.level === 24) return '省级';
  return '市级';
});

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

const CN_PHONE = /^1[3-9]\d{9}$/;
const CN_PHONE_RE = /^(1\d{10}|0\d{2,3}-\d{7,8})$/;

const formRules = computed<Rules>(() => {
  const rules: Rules = {
    partyA: [
      { required: props.isReviewer, message: '请填写甲方负责人（代表人）姓名' }
    ],
    partyB: [
      { required: true, message: '请填写乙方（传承人）姓名' }
    ],
    partyAMobile: [
      {
        required: props.isReviewer,
        validator(_rule, value, callback) {
          const s = value != null ? String(value).trim() : '';
          if (props.isReviewer && !CN_PHONE_RE.test(s))
            callback(new Error('请输入正确的手机号或座机号'));
          else
            callback();
        },
      },
    ],
    apprentice: [
      { required: true, message: '请填写本年度带徒人数' },
      { type: 'integer', min: 0, message: '须为不小于 0 的整数' },
    ],
    activity: [
      { required: true, message: '请填写本年度宣传活动场次' },
      { type: 'integer', min: 0, message: '须为不小于 0 的整数' },
    ],
    partyASign: [
      {
        required: props.isReviewer,
        validator(_rule, value, callback) {
          const s = typeof value === 'string' ? value.trim() : '';
          if (!s && props.isReviewer)
            callback(new Error('请完成甲方签名'));
          else
            callback();
        },
      },
    ],
    partyBSign: [
      {
        validator(_rule, value, callback) {
          const s = typeof value === 'string' ? value.trim() : '';
          if (!s)
            callback(new Error('请完成乙方签名'));
          else
            callback();
        },
      },
    ],
    idCard: [
      { required: true, message: '请填写身份证号' },
    ],
    ich: [{ required: true, message: '请填写非遗项目名称' }],
    health: [{ required: true, message: '请填写身体状况' }],
    mobile: [
      { required: true, message: '请填写乙方联系电话' },
      {
        validator(_rule, value, callback) {
          const s = value != null ? String(value).trim() : '';
          if (!props.isReviewer && !CN_PHONE_RE.test(s))
            callback(new Error('请输入正确的手机号或座机号'));
          else
            callback();
        },
      },
    ],
    contactMobile: [
      {
        required: false,
        validator(_rule, value, callback) {
          const s = value != null ? String(value).trim() : '';
          if (!props.isReviewer && !CN_PHONE.test(s))
            callback(new Error('请输入正确的手机号'));
          else
            callback();
        },
      },
    ],
  };
  if (props.currentAgreement?.level !== 25)
    rules.course = [
      { required: true, message: '请填写本年度研修班场次' },
      { type: 'integer', min: 0, message: '须为不小于 0 的整数' },
    ];
  return rules;
});

defineExpose({
  validate: async () => await formRef.value?.validate(),
});
</script>

<style lang="scss" scoped>
</style>