<template>
  <CommonRoot>
    <FlexCol padding="space.lg">
      <SimplePageContentLoader :loader="loader">
        <template v-if="loader.isFinished.value">
          <Result
            v-if="!currentAgreement"
            status="info"
            title="您还未签署传承协议"
            description="请先签署传承协议"
          >
            <Height :height="30" />
            <Button type="primary" @click="createAgreement">去签署传承协议</Button>
          </Result>
          <FlexCol v-else gap="gap.md">
            <Alert type="info" message="请仔细阅读传承协议，确保您已理解内容，并签署传承协议。" />

            <FlexCol
              :gap="'md'"
              :innerStyle="articleWrapStyle"
            >
              <Form ref="formRef" :model="currentAgreement" :rules="formRules">
                <H3>{{ agreementTitle }}</H3>

                <FlexCol :gap="'sm'">
                  <P>甲方：福建省文化和旅游厅</P>
                  <FlexRow align="center" wrap :gap="'sm'">
                    <Text font-config="p" color="text.content">乙方：</Text>
                    <AgreementPrefillInline
                      v-model="currentAgreement.partyB"
                      name="partyB"
                      placeholder="请填写乙方（传承人）姓名"
                    />
                  </FlexRow>
                </FlexCol>

                <Height :height="8" />

                <Text font-config="p" color="text.content" :inner-style="paragraphStyle">
                  为传承弘扬中华优秀传统文化，有效保护和传承非物质文化遗产，鼓励和支持国家级非物质文化遗产代表性传承人开展传承活动，根据《中华人民共和国非物质文化遗产法》《国家级非物质文化遗产代表性传承人认定与管理办法》等有关法律法规，制定协议，并按照下列各项条款签署，甲、乙双方共同遵守。
                </Text>

                <Text font-config="p" color="text.content" :inner-style="paragraphStyle">
                  一、甲乙双方应当以习近平新时代中国特色社会主义思想为指导，坚持以人民为中心，弘扬社会主义核心价值观，共同保护传承非物质文化遗产，推动中华优秀传统文化创造性转化、创新性发展。
                </Text>

                <Text font-config="p" color="text.content" :inner-style="paragraphStyle">
                  二、甲方按照《国家级非物质文化遗产代表性传承人认定与管理办法》的要求，支持国家级非物质文化遗产代表性传承人开展传承、传播活动。
                </Text>

                <Text font-config="p" color="text.content" :inner-style="paragraphStyle">
                  三、甲方按照《国家级非物质文化遗产保护专项资金管理办法》的要求，落实国家给予的代表性传承人的传承补助。
                </Text>

                <FlexRow align="center" wrap :gap="'sm'" :inner-style="paragraphStyle">
                  <Text font-config="p" color="text.content">四、乙方应积极开展传承活动，培养后继人才，制定传承计划，{{ agreementYear }} 年度带徒</Text>
                  <AgreementPrefillInline
                    v-model="currentAgreement.apprentice"
                    name="apprentice"
                    number-mode
                    placeholder="人数"
                    suffix="人。"
                  />
                </FlexRow>

                <Text font-config="p" color="text.content" :inner-style="paragraphStyle">
                  五、乙方应妥善保存相关实物、资料情况。主动保存、提供与该项非遗项目有关的原始资料、实物，配合记录工作。
                </Text>

                <Text font-config="p" color="text.content" :inner-style="paragraphStyle">
                  六、乙方应主动、及时配合非遗调查，主动向文化和旅游主管部门、非遗保护中心反映非遗项目保护、传承情况和总结材料，并完成文化和旅游主管部门临时交办的非遗工作任务，提出保护的意见、建议。
                </Text>

                <FlexRow align="center" wrap :gap="'sm'" :inner-style="paragraphStyle">
                  <Text font-config="p" color="text.content">七、乙方应积极、主动参加各级政府组织的非物质文化遗产公益性宣传活动，{{ agreementYear }} 年度完成</Text>
                  <AgreementPrefillInline
                    v-model="currentAgreement.activity"
                    name="activity"
                    number-mode
                    placeholder="场次"
                    suffix="场。"
                  />
                </FlexRow>

                <Text font-config="p" color="text.content" :inner-style="paragraphStyle">
                  八、乙方应合理使用国家级非物质文化遗产代表性传承人补助经费，用于开展非遗项目的传习活动，做好传承补助经费使用记录、支出范围和绩效评价等，不得用于生活补助。
                </Text>

                <FlexRow align="center" wrap :gap="'sm'" :inner-style="paragraphStyle">
                  <Text font-config="p" color="text.content">九、乙方应积极、主动参加文化和旅游部组织的非物质文化遗产代表性传承人研修班，{{ agreementYear }} 年度完成</Text>
                  <AgreementPrefillInline
                    v-model="currentAgreement.course"
                    name="course"
                    number-mode
                    placeholder="场次"
                    suffix="场。"
                  />
                </FlexRow>

                <Text font-config="p" color="text.content" :inner-style="paragraphStyle">
                  十、乙方应积极参与非物质文化遗产相关理论和实践研究、发表（出版）论文、专著等研究。
                </Text>

                <Height :height="16" />

                <FlexCol :gap="'md'" :inner-style="signBlockStyle">
                  <FlexRow padding="space.sm">
                    <Text font-config="p" color="text.content" bold>甲方：福建省文化和旅游厅</Text>
                  </FlexRow>
                  <Field
                    label="负责人（代表人）"
                    label-position="top"
                    v-model="currentAgreement.partyASign"
                    placeholder="选填"
                    :show-bottom-border="true"
                  />
                  <Field
                    label="甲方电话"
                    label-position="top"
                    name="partyAMobile"
                    type="tel"
                    v-model="currentAgreement.partyAMobile"
                    placeholder="请填写甲方联系电话"
                  />
                  <AgreementDateWriteBlock
                    v-model="partyAStampDate"
                    hint="（以实际盖章日期为准）"
                  />

                  <Height :height="24" />

                  <FlexRow padding="space.sm">
                    <Text font-config="p" color="text.content" bold>乙方：{{ currentAgreement.partyB }}（签名）</Text>
                  </FlexRow>
                  <Field
                    label="乙方签名 / 说明"
                    label-position="top"
                    name="partyBSign"
                    showRightArrow
                  >
                    <Text>点击签名</Text>
                    <template #extra>
                      <SignatureField
                        v-model="currentAgreement.partyBSign"
                        placeholder=""
                        :upload="uploadAgreementSign"
                      />
                    </template>
                  </Field>
                  <Field
                    label="身份证号"
                    label-position="top"
                    name="idCard"
                    v-model="currentAgreement.idCard"
                    placeholder="请填写身份证号"
                  />
                  <Field
                    label="项目名称"
                    label-position="top"
                    name="ich"
                    v-model="currentAgreement.ich"
                    placeholder="非遗项目名称"
                  />
                  <Field
                    label="身体状况"
                    label-position="top"
                    name="health"
                    v-model="currentAgreement.health"
                    placeholder="请简要填写"
                  />
                  <Field
                    label="乙方电话"
                    label-position="top"
                    name="mobile"
                    type="tel"
                    v-model="currentAgreement.mobile"
                    placeholder="请填写联系电话"
                  />
                  <AgreementDateWriteBlock
                    v-model="partyBSignDate"
                    hint="（以实际签署日期为准）"
                  />
                </FlexCol>
              </Form>
            </FlexCol>

            <Button type="primary" block :loading="submitLoading" @click="saveAgreement">保存传承协议</Button>
            <Button :loading="submitLoading" @click="downloadAgreement">下载协议PDF</Button>
          </FlexCol>
        </template>
      </SimplePageContentLoader>
    </FlexCol>
  </CommonRoot>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';
import { useAuthStore } from '@/store/auth';
import { useSimpleDataLoader } from '@/components/composeabe/loader/SimpleDataLoader';
import { assertNotNull, formatError } from '@imengyu/imengyu-utils';
import { toast, alert } from '@/components/dialog/CommonRoot';
import AssessmentContentApi, { AgreementDetail } from '@/api/collect/AssessmentContent';
import FlexCol from '@/components/layout/FlexCol.vue';
import Result from '@/components/feedback/Result.vue';
import SimplePageContentLoader from '@/components/loader/SimplePageContentLoader.vue';
import Button from '@/components/basic/Button.vue';
import Height from '@/components/layout/space/Height.vue';
import H3 from '@/components/typography/H3.vue';
import Alert from '@/components/feedback/Alert.vue';
import FlexRow from '@/components/layout/FlexRow.vue';
import P from '@/components/typography/P.vue';
import Field from '@/components/form/Field.vue';
import Text from '@/components/basic/Text.vue';
import AgreementPrefillInline from './components/AgreementPrefillInline.vue';
import AgreementDateWriteBlock, { type AgreementYmdParts } from './components/AgreementDateWriteBlock.vue';
import SignatureField from '@/components/form/SignatureField.vue';
import Form, { type FormInstance } from '@/components/form/Form.vue';
import type { Rules } from 'async-validator';
import { useLoadQuerys } from '@/common/composeabe/LoadQuerys';
import CommonRoot from '@/components/dialog/CommonRoot.vue';
import { useImageSimpleUploadCo } from '@/common/components/upload/ImageUploadCo';

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

const authStore = useAuthStore();
const currentAgreement = ref<AgreementDetail | null>(null);
/** 甲方盖章日期（页面填写，保存时可拼为字符串提交） */
const partyAStampDate = ref<AgreementYmdParts>({ year: '', month: '', day: '' });
/** 乙方签署日期 */
const partyBSignDate = ref<AgreementYmdParts>({ year: '', month: '', day: '' });

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

const CN_MOBILE_RE = /^1\d{10}$/;
const CN_ID_RE = /^(?:\d{15}|\d{17}[\dXx])$/;

const formRules: Rules = {
  partyB: [{ required: true, message: '请填写乙方（传承人）姓名' }],
  apprentice: [
    { required: true, message: '请填写本年度带徒人数' },
    { type: 'integer', min: 0, message: '须为不小于 0 的整数' },
  ],
  activity: [
    { required: true, message: '请填写本年度宣传活动场次' },
    { type: 'integer', min: 0, message: '须为不小于 0 的整数' },
  ],
  course: [
    { required: true, message: '请填写本年度研修班场次' },
    { type: 'integer', min: 0, message: '须为不小于 0 的整数' },
  ],
  partyAMobile: [
    {
      validator(_rule, value, callback) {
        const s = value != null && value !== undefined ? String(value).trim() : '';
        if (!s) {
          callback();
          return;
        }
        if (!CN_MOBILE_RE.test(s))
          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: '请填写身份证号' },
    {
      validator(_rule, value, callback) {
        const s = value != null ? String(value).trim() : '';
        if (!CN_ID_RE.test(s))
          callback(new Error('请输入正确的身份证号'));
        else
          callback();
      },
    },
  ],
  ich: [{ required: true, message: '请填写非遗项目名称' }],
  health: [{ required: true, message: '请填写身体状况' }],
  mobile: [
    { required: true, message: '请填写乙方联系电话' },
    {
      validator(_rule, value, callback) {
        const s = value != null ? String(value).trim() : '';
        if (!CN_MOBILE_RE.test(s))
          callback(new Error('请输入正确的手机号'));
        else
          callback();
      },
    },
  ],
};

const articleWrapStyle = {
  padding: '24rpx 28rpx',
  borderRadius: '16rpx',
  backgroundColor: '#fafafa',
  borderWidth: '1rpx',
  borderStyle: 'solid',
  borderColor: '#eeeeee',
};
const paragraphStyle = {
  lineHeight: '1.75',
  marginBottom: '12rpx',
};
const signBlockStyle = {
  paddingTop: '8rpx',
};

async function loadBasicInfo() {
  const basicInfo = await AssessmentContentApi.getInheritorBasic(authStore.userInfo?.id);
  assertNotNull(currentAgreement.value, 'currentAgreement is null');
  currentAgreement.value.partyB = basicInfo.name;
  currentAgreement.value.mobile = basicInfo.mobile;
  currentAgreement.value.idCard = basicInfo.idCard;
  currentAgreement.value.ich = basicInfo.ichName;
}

const uploadAgreementSign = useImageSimpleUploadCo();

const agreementYear = computed(() => currentAgreement.value?.year ?? new Date().getFullYear());

const levelTitle = computed(() => {
  const v = currentAgreement.value?.level;
  if (v === 23) return '国家级';
  if (v === 24) return '省级';
  if (v === 25) return '市级';
  return '国家级';
});
const agreementTitle = computed(
  () => `${agreementYear.value} 年度${levelTitle.value}非物质文化遗产代表性传承人传承协议`,
);
const loader = useSimpleDataLoader(async () => {
  if (querys.value.id > 0) {
    const detail = await AssessmentContentApi.getAgreementDetail(querys.value.id);
    currentAgreement.value = detail;
    partyAStampDate.value = { year: '', month: '', day: '' };
    partyBSignDate.value = { year: '', month: '', day: '' };
    return currentAgreement.value;
  }
  const list = await AssessmentContentApi.getAgreementList({
    userId: authStore.userInfo?.id,
    year: new Date().getFullYear(),
  });
  if (list.data.length > 0) {
    const detail = await AssessmentContentApi.getAgreementDetail(list.data[0].id);
    currentAgreement.value = detail;
    partyAStampDate.value = { year: '', month: '', day: '' };
    partyBSignDate.value = { year: detail.updatetime.getFullYear().toString(), month: (detail.updatetime.getMonth() + 1).toString(), day: detail.updatetime.getDate().toString() };
  } else {
    currentAgreement.value = null;
  }
  return currentAgreement.value;
});

const submitLoading = ref(false);

function createAgreement() {
  const now = new Date();
  const u = authStore.userInfo;
  const nick = u?.nickname || u?.diyname;
  const detail = new AgreementDetail();
  detail.userId = authStore.userInfo!.id;
  detail.year = new Date().getFullYear();
  detail.partyA = '福建省文化和旅游厅';
  detail.partyB = nick ?? '';
  console.log(authStore.userInfo, u, nick);
  partyAStampDate.value = { year: now.getFullYear().toString(), month: (now.getMonth() + 1).toString(), day: now.getDate().toString() };
  partyBSignDate.value = { year: now.getFullYear().toString(), month: (now.getMonth() + 1).toString(), day: now.getDate().toString() };
  currentAgreement.value = detail;
  loadBasicInfo();
}
async function saveAgreement() {
  const detail = currentAgreement.value;
  try {
    await formRef.value?.validate();
  } catch (error) {
    toast('请填写完整信息');
    return;
  }
  submitLoading.value = true;
  try {
    assertNotNull(detail, 'currentAgreement is null');
    await AssessmentContentApi.saveAgreement(detail as AgreementDetail);
    toast('保存传承协议成功');
  } catch (error) {
    alert({
      title: '保存传承协议失败',
      content: formatError(error),
    });
  }
  submitLoading.value = false;
}
async function downloadAgreement() {
  const detail = currentAgreement.value;
  try {
    assertNotNull(detail, 'currentAgreement is null');
    throw new Error('没这个接口');
  } catch (error) {
    alert({
      title: '保存传承协议失败',
      content: formatError(error),
    });
  }
}
</script>
