<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.paperName" />
        <CommonInfoRow label="学科类型" :value="getDictLabel('project_class', form.disciplineFirstName)" />
        <CommonInfoRow label="论文类型" :value="form.paperType" />
        <CommonInfoRow label="论文类别" :value="getDictLabel('paper_category', form.paperCategory)" />
        <CommonInfoRow label="发表/出版时间" :value="formatDate(form.publicationDate)" />
        <CommonInfoRow label="刊名" :value="form.publicationName" />
        <CommonInfoRow label="期刊类型" :value="form.periodicalType || '-'" />
        <CommonInfoRow v-if="isConferenceType" label="会议名称" :value="form.conferenceName || '-'" />
        <CommonInfoRow v-if="isConferenceType" label="会议地址" :value="form.conferenceAddress || '-'" />
        <template v-if="form.periodicalType?.toLowerCase() === 'sci'">
          <CommonInfoRow label="中科院分区" :value="getDictLabel('sci_paper_subTreasury', form.subTreasury)" />
          <CommonInfoRow label="IF" :value="form.impactFactors" />
        </template>
        <CommonInfoRow label="论文DOI号/PMID（(PubMed标识码）" :isColumn="true" :value="form.doi" />
        <CommonInfoRow label="所属年份" :value="form.statisticalYear ? formatDate(form.statisticalYear, 'YYYY') : '-'" />
        <CommonInfoRow label="年、卷（期）" :value="`${form.yearNum || ''}、${form.volNum || ''}(${form.issueNum || ''})`" />
        <CommonInfoRow v-if="form.pageRange" label="页码" :value="form.pageRange" />
        <CommonInfoRow label="本院署名" :value="getDictLabel('sci_paper_signType', form.signType)" />
        <CommonInfoRow label="ISSN号" :value="form.issnNum" />
        <CommonInfoRow label="合作单位" :value="form.partnerOrg || '-'" />
        <CommonInfoRow label="单位类型" :value="getDictLabel('partner_org_type', form.partnerOrgType)" />
        <CommonInfoRow label="所属平台" isColumn>
          <view class="platform-tags">
            <template v-if="platformList.length > 0">
              <uv-tags v-for="(p, index) in platformList" :key="index" :text="p.platformName === '其他' ? '其他' : (p.platformType ? p.platformName + ' (' + p.platformType + ')' : p.platformName)" type="primary" plain size="mini" class="mr5"></uv-tags>
            </template>
            <text v-else>-</text>
          </view>
        </CommonInfoRow>
        <CommonInfoRow label="所属团队" :value="form.belongTeam || '-'" />
      </CommonSection>

      <!-- 作者信息 -->
      <CommonSection title="作者信息" v-if="form.authorList?.length">
        <view class="member-list">
          <view class="member-item" v-for="(row, index) in form.authorList" :key="index">
            <view class="m-index">{{ Number(index) + 1 }}</view>
            <view class="m-body">
              <view class="member-header">
                <view class="name-box">
                  <text class="m-name">{{ row.memberName }}</text>
                  <text class="m-tag">{{ getDictLabel('sci_paper_author_type', row.authorType) }}</text>
                </view>
                <text class="m-type-tag">{{ getDictLabel('sci_paper_member_type', row.memberType) }}</text>
              </view>
              <view class="m-detail-row">
                <view class="m-line" v-if="row.deptName"><text class="l">科室/单位：</text><text class="v">{{ row.deptName }}</text></view>
                <view class="m-line" v-if="row.technicalTitle"><text class="l">职称：</text><text class="v">{{ row.technicalTitle }}</text></view>
                <view class="m-line" v-if="row.contributionRate"><text class="l">贡献率(%)：</text><text class="v">{{ row.contributionRate }}</text></view>
                <view class="m-line" v-if="row.signOrder"><text class="l">排名：</text><text class="v">{{ row.signOrder }}</text></view>
              </view>
            </view>
          </view>
        </view>
      </CommonSection>

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

      <!-- 电子附件 -->
      <CommonSection title="电子附件">
        <CommonInfoRow label="论文全文" isColumn>
          <view class="file-hint">附件说明：SCI上传文章；中文期刊上传封面、目录及文章</view>
          <view class="file-links">
            <template v-if="paperResultList.length">
              <view class="file-item" v-for="(item, index) in paperResultList" :key="'paper-full-' + index" @click="handlePreview(item)">
                <text class="file-link">{{ item.fileName || item.name || '-' }}</text>
              </view>
            </template>
            <text v-else>-</text>
          </view>
        </CommonInfoRow>
        <CommonInfoRow label="收录证明" isColumn>
          <view class="file-links">
            <template v-if="includedProofList.length">
              <view class="file-item" v-for="(item, index) in includedProofList" :key="'paper-included-' + index" @click="handlePreview(item)">
                <text class="file-link">{{ item.fileName || item.name || '-' }}</text>
              </view>
            </template>
            <text v-else>-</text>
          </view>
        </CommonInfoRow>
        <CommonInfoRow label="伦理批件" isColumn>
          <view class="file-links">
            <template v-if="ethicsApprovalList.length">
              <view class="file-item" v-for="(item, index) in ethicsApprovalList" :key="'paper-ethics-' + index" @click="handlePreview(item)">
                <text class="file-link">{{ item.fileName || item.name || '-' }}</text>
              </view>
            </template>
            <text v-else>-</text>
          </view>
        </CommonInfoRow>
        <CommonInfoRow label="原始数据" isColumn>
          <view class="file-links">
            <template v-if="rawDataList.length">
              <view class="file-item" v-for="(item, index) in rawDataList" :key="'paper-raw-' + index" @click="handlePreview(item)">
                <text class="file-link">{{ item.fileName || item.name || '-' }}</text>
              </view>
            </template>
            <text v-else>-</text>
          </view>
        </CommonInfoRow>
      </CommonSection>

      <!-- 审批信息 -->
      <CommonSection title="审批信息" v-if="form.id">
        <FlowTable :id="form.id" :businessCode="'学术论文-' + form.paperCode" defCode="sci_academic_achievement" />
      </CommonSection>
    </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 { previewFile } from '@/utils/file';
import to from 'await-to-js';
import FlowTable from '@/pages/project/components/detail/FlowTable.vue';
import CommonSection from '@/components/ui/CommonSection.vue';
import CommonInfoRow from '@/components/ui/CommonInfoRow.vue';

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

const { getDictLabel } = useDict(
  'project_class',
  'sci_paper_type',
  'paper_category',
  'sci_publication_range',
  'sci_paper_subTreasury',
  'sci_paper_signType',
  'sci_paper_author_type',
  'sci_paper_member_type',
  'partner_org_type'
);
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 paperResultList = computed(() => form.value?.paperResultList || []);
const includedProofList = computed(() => form.value?.includedProofList || []);
const ethicsApprovalList = computed(() => form.value?.ethicsApprovalList || []);
const rawDataList = computed(() => form.value?.rawDataList || []);

const isConferenceType = computed(() => {
  const paperType = String(form.value?.paperType || '');
  return paperType.includes('会议');
});

const handlePreview = (file: any) => {
  const url = file.fileUrl || file.url;
  const name = file.fileName || file.name;
  if (url) {
    previewFile(url, name);
  }
};

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

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

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

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

.info-row {
  display: flex;
  justify-content: space-between;
  padding: 24rpx 0;
  border-bottom: 2rpx dashed #f5f5f5;
  font-size: 28rpx;

  .label {
    color: #343a3f;
    width: 200rpx;
    flex-shrink: 0;
    margin-right: 20rpx;
  }
}

.member-list {
  .member-item {
    display: flex;
    align-items: flex-start;
    padding: 20rpx 0;
    border-bottom: 2rpx solid #f5f5f5;
    &:last-child { border-bottom: none; }
  }
  .m-index {
    width: 40rpx;
    height: 40rpx;
    background: #3b82f6;
    color: #fff;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 22rpx;
    flex-shrink: 0;
    margin-right: 16rpx;
    margin-top: 4rpx;
  }
  .m-body {
    flex: 1;
  }
}

.member-header {
  .name-box {
    display: flex;
    align-items: center;
    gap: 12rpx;
    flex-wrap: wrap;
  }
}

.m-detail-row {
  margin-top: 12rpx;
  display: flex;
  flex-direction: column;
  gap: 6rpx;
  .m-line {
    font-size: 24rpx;
    color: #64748b;
    .l { color: #94a3b8; margin-right: 8rpx; }
    .v { color: #343a3f; }
  }
}

.file-hint {
  font-size: 22rpx;
  color: #ef4444;
  margin-bottom: 8rpx;
}

.file-links {
  .file-item {
    padding: 6rpx 0;
  }

  .file-link {
    color: #2979ff;
    text-decoration: underline;
    word-break: break-all;
  }
}
</style>
