<template>
  <view class="document-form">
    <uv-loading-icon v-if="loading" mode="circle" text="正在加载专利授权详情..."></uv-loading-icon>
    <template v-else-if="form">
      <!-- 基本信息 -->
      <CommonSection title="基本信息" :isFirst="true">
        <CommonInfoRow label="专利名称" :value="form.patentName" />
        <CommonInfoRow label="所属科室" :value="form.deptName" />
        <CommonInfoRow label="专利类型" :value="getDictLabel('sci_patent_class', form.patentClass)" />
        <CommonInfoRow label="专利范围" :value="getDictLabel('sci_patent_scope', form.patentScope)" />
        <CommonInfoRow label="专利状态" :value="getDictLabel('sci_patent_condition', form.patentCondition)" />
        <CommonInfoRow label="专利（申请）号" :value="form.patentNumber" />
        <CommonInfoRow label="申请人" :value="form.applicantName" />
        <CommonInfoRow label="第几参与人" :value="form.patentApplicationCode" />
        <CommonInfoRow label="申请日期" :value="formatDate(form.patentApplicationDate)" />
        <CommonInfoRow label="发明人" :value="showMembers(form.memberList)" />
        <CommonInfoRow label="分类号" :value="form.classNum" />
        <CommonInfoRow label="公开号" :value="form.patentPublicCode" />
        <CommonInfoRow label="公开日期" :value="formatDate(form.patentPublicDate)" />
        <CommonInfoRow label="授权号" :value="form.patentAccreditCode" />
        <CommonInfoRow label="授权日期" :value="formatDate(form.effectiveTime)" />
        <CommonInfoRow label="署名" :value="getDictLabel('sci_circuit_signature', form.patentSchoolSignature)" />
        <CommonInfoRow label="专利权人" :value="form.patentObligee" />
        <CommonInfoRow label="专利代理机构" :value="form.entrustUnit" />
        <CommonInfoRow label="代理人" :value="form.agencyUserName" />
        <CommonInfoRow label="代理人联系电话" :value="form.agencyPhone" />
        <CommonInfoRow label="专利文献出版日" :value="formatDate(form.publicationDate)" />
        <CommonInfoRow label="所属年份" :value="form.patentYeat" />
        <CommonInfoRow label="是否失效" :value="form.patentEffectiveness === '10' ? '是' : '否'" />
        <CommonInfoRow label="成果权属" :value="getDictLabel('achievement_owner_unit', form.achievementOwnerUnit)" />
        <CommonInfoRow label="是否职务专利" :value="form.patentOffice === '10' ? '是' : '否'" />
        <CommonInfoRow label="是否为PCT专利" :value="form.patentCt === '10' ? '是' : '否'" />

        <CommonInfoRow label="所属平台">
          <view class="platform-tags">
            <template v-if="platformList.length > 0">
              <text v-for="(p, index) in platformList" :key="index" class="platform-tag">
                {{ p.platformName }}
              </text>
            </template>
            <text v-else>-</text>
          </view>
        </CommonInfoRow>
        <CommonInfoRow label="所属团队" :value="form.belongTeam || '-'" />

        <!-- 专利转化特有字段 -->
        <template v-if="code.includes('专利转化')">
          <CommonInfoRow label="转化时间" :value="formatDate(form.invertTime)" />
          <CommonInfoRow label="转化金额" :value="(form.invertAmount || '0') + ' 元'" isAmount />
          <CommonInfoRow label="转化单位" :value="form.invertUnit" />
          <CommonInfoRow label="知识产权交易类型" :value="form.tradeType === '10' ? '转让' : form.tradeType === '20' ? '许可' : '-'" />
        </template>

        <CommonInfoRow label="专利简介" :value="form.patentDesc" isColumn />
      </CommonSection>

      <!-- 标注经济来源 -->
      <CommonSection title="标注经济来源" v-if="form.projList?.length">
        <view class="achievement-card" v-for="(row, index) in form.projList" :key="index">
          <view class="a-row">
            <text class="al">关联类型：</text>
            <text class="av">{{ row.sourceType === '10' ? '项目' : '学科' }}</text>
          </view>
          <view class="a-row">
            <text class="al">项目/学科：</text>
            <text class="av">{{ row.projectSource || '-' }}</text>
          </view>
        </view>
      </CommonSection>

      <!-- 附件信息 -->
      <AttachmentList :list="mergedFileList" title="相关附件" />
    </template>
    <uv-empty v-else mode="data" text="暂无数据"></uv-empty>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue';
import { useDict } from '@/hooks/useDict';
import { useDocumentApi } from '@/api/document';
import { formatDate } from '@/utils/date';
import to from 'await-to-js';
import AttachmentList from './AttachmentList.vue';
import CommonSection from '@/components/ui/CommonSection.vue';
import CommonInfoRow from '@/components/ui/CommonInfoRow.vue';

const props = defineProps<{
  code: string;
}>();

const { getDictLabel } = useDict(
  'sci_patent_class',
  'sci_patent_scope',
  'sci_patent_condition',
  'sci_circuit_signature',
  'achievement_owner_unit'
);

const documentApi = useDocumentApi();

const form = ref<any>(null);
const loading = ref(false);

const platformList = computed(() => {
  if (form.value?.belongPlatform) {
    try {
      const data = JSON.parse(form.value.belongPlatform);
      return Array.isArray(data) ? data : [];
    } catch (e) {
      if (form.value.belongPlatform === '其他') return [{ platformName: '其他' }];
      return [{ platformName: form.value.belongPlatform }];
    }
  }
  return [];
});

const mergedFileList = computed(() => {
  if (!form.value) return [];
  const list: any[] = [];
  if (form.value.patentFile) {
    try {
      const file = JSON.parse(form.value.patentFile);
      list.push({ ...file, fileType: '专利附件' });
    } catch (e) {}
  }
  if (form.value.agencyContractFile) {
    try {
      const file = JSON.parse(form.value.agencyContractFile);
      list.push({ ...file, fileType: '委托合同' });
    } catch (e) {}
  }
  if (form.value.invertUrl) {
    try {
      const file = JSON.parse(form.value.invertUrl);
      list.push({ ...file, fileType: '转化附件' });
    } catch (e) {}
  }
  return list;
});

const fetchData = async () => {
  if (!props.code) return;
  loading.value = true;
  const patentCode = props.code.includes('-') ? props.code.split('-')[1] : props.code;
  const [err, res] = await to(documentApi.getPatentByCode(patentCode));
  if (!err && res?.data) {
    form.value = res.data;
  }
  loading.value = false;
};

onMounted(() => {
  fetchData();
});

watch(() => props.code, () => {
  fetchData();
});

const showMembers = (list: any[]) => {
  return list?.map(m => m.memberName).join(', ') || '-';
};
</script>

<style lang="scss" scoped>
@import "./common.scss";
</style>
