<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.projectName" />
        <CommonInfoRow label="学科分类" :value="form.disciplineFirstName" />
        <CommonInfoRow label="负责人类型" :value="getLeaderTypeLabel(form.projectLeaderType)" />
        <CommonInfoRow label="负责人" :value="form.projectLeaderName" />
        <CommonInfoRow label="合同类别" :value="getDictLabel('contract_type', form.contractType)" />
        <CommonInfoRow label="归属部门" :value="form.deptName" />
        <CommonInfoRow label="签订日期" :value="formatDate(form.signDate)" />
        <CommonInfoRow label="执行期" :value="formatDateRange(form.planStartDate, form.planEndDate)" />
        <CommonInfoRow label="统计年度" :value="form.statisticalYear" />
        <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 || '-'" />
        <CommonInfoRow label="备注" :value="form.remark" isColumn />
      </CommonSection>

      <!-- 经费信息 -->
      <CommonSection title="经费信息">
        <CommonInfoRow label="合同经费" :value="formatAmount(form.contractFunds)" isAmount />
        <CommonInfoRow label="配套经费" :value="formatAmount(form.supportFunds)" isAmount />
        <CommonInfoRow label="总金额" :value="formatAmount(form.totalAmount)" isAmount />
        <CommonInfoRow label="到账金额" :value="formatAmount(form.arrivalFunds)" isAmount />
        <CommonInfoRow label="到账日期" :value="formatDate(form.arrivalDate)" />
      </CommonSection>

      <!-- 分包信息 -->
      <CommonSection title="分包信息" v-if="form.isSubcontract === '10'">
        <view class="member-list">
          <view class="member-item" v-for="(item, index) in subcontractList" :key="index">
            <view class="member-header">
              <text class="m-name">{{ item.subProjectName }}</text>
            </view>
            <view class="m-body">
              <view class="m-line"><text class="l">负责人：</text><text class="v">{{ item.projectLeaderName }}</text></view>
              <view class="m-line"><text class="l">分包金额：</text><text class="v price">￥{{ formatAmount(item.subcontractAmount) }}</text></view>
            </view>
          </view>
        </view>
      </CommonSection>

      <!-- 合作单位 -->
      <CommonSection title="合作单位" v-if="form.companyList?.length">
        <view class="member-list">
          <view class="member-item" v-for="(item, index) in form.companyList" :key="index">
            <view class="member-header">
              <text class="m-name">{{ item.compName }}</text>
              <text class="m-type-tag" v-if="item.compType">{{ getDictLabel('sci_pjt_company_type', item.compType) }}</text>
            </view>
            <view class="m-body">
              <view class="m-line" v-if="item.compCode"><text class="l">单位编号：</text><text class="v">{{ item.compCode }}</text></view>
              <view class="m-line" v-if="item.contractParty"><text class="l">合同方：</text><text class="v">{{ getDictLabel('project_company_type', item.contractParty) }}</text></view>
              <view class="m-line" v-if="item.compContact"><text class="l">联系人：</text><text class="v">{{ item.compContact }} ({{ item.compPhoneNum || '-' }})</text></view>
              <view class="m-line" v-if="item.compLocalArea"><text class="l">单位地址：</text><text class="v">{{ item.compLocalArea }}</text></view>
            </view>
          </view>
        </view>
      </CommonSection>

      <!-- 成员信息 -->
      <CommonSection title="成员信息" v-if="form.member?.length">
        <view class="member-list">
          <view class="member-item" v-for="(row, index) in form.member" :key="index">
            <view class="member-header">
              <view class="name-box">
                <text class="m-name">{{ row.memberName }}</text>
                <text class="m-tag leader" v-if="row.projectRole === '10'">负责人</text>
                <text class="m-tag" v-else>参与人</text>
              </view>
              <text class="m-type-tag blue" v-if="row.memberType">{{ row.memberType === '10' ? '本院人员' : row.memberType === '20' ? '非本院人员' : '研究生' }}</text>
            </view>
            <view class="m-body">
              <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.degree"><text class="l">学位：</text><text class="v">{{ getDictLabel('sci_academic_degree', row.degree) }}</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 column" v-if="row.responsibleContent">
                <text class="l">负责内容：</text>
                <text class="v remark">{{ row.responsibleContent }}</text>
              </view>
            </view>
          </view>
        </view>
      </CommonSection>

      <!-- 预算信息 -->
      <CommonSection title="预算信息" v-if="form.budget?.length">
        <view class="funds-list">
          <view class="funds-item" v-for="(item, index) in form.budget" :key="index">
            <view class="f-row">
              <text class="f-name">{{ item.fundsSubjName }}</text>
            </view>
            <view class="f-grid">
              <view class="g-item"><text class="gl">财政拨款</text><text class="gv">￥{{ item.projectFundsAmount || 0 }}</text></view>
              <view class="g-item"><text class="gl">匹配经费</text><text class="gv">￥{{ item.otherFundsAmount || 0 }}</text></view>
              <view class="g-item"><text class="gl">自筹经费</text><text class="gv">￥{{ item.raiseFundsAmount || 0 }}</text></view>
              <view class="g-item highlight"><text class="gl">预算金额</text><text class="gv">￥{{ item.totalFundsAmount || 0 }}</text></view>
            </view>
          </view>
        </view>
      </CommonSection>

      <!-- 附件信息 -->
      <AttachmentList :list="form.files" 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 { formatAmount } from '@/utils/format';
import AttachmentList from './AttachmentList.vue';
import CommonSection from '@/components/ui/CommonSection.vue';
import CommonInfoRow from '@/components/ui/CommonInfoRow.vue';
import to from 'await-to-js';

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

const { getDictLabel } = useDict('contract_type', 'sci_academic_degree', 'sci_pjt_company_type', 'project_company_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 subcontractList = computed(() => {
  const list = form.value?.subcontractList || form.value?.subContractList || [];
  if (Array.isArray(list)) return list;
  if (typeof list === 'string' && list.trim()) {
    try {
      return JSON.parse(list);
    } catch (e) {
      return [];
    }
  }
  return [];
});

const getLeaderTypeLabel = (val: string) => {
  const map: Record<string, string> = { '10': '教师', '20': '学生', '30': '校外人员' };
  return map[val] || val || '-';
};

const formatDateRange = (start: string, end: string) => {
  if (!start && !end) return '-';
  return `${formatDate(start)} 至 ${formatDate(end)}`;
};

const fetchData = async () => {
  if (!props.code) return;
  loading.value = true;
  const [err, res] = await to(documentApi.getHorizontalByCode(String(props.code)));
  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";



.price {
  color: #ff4d4f;
  font-weight: bold;
}

.m-type-tag {
  font-size: 20rpx;
  padding: 2rpx 8rpx;
  background-color: #f0f7ff;
  color: #007aff;
  border-radius: 4rpx;
  border: 1px solid #d0e7ff;
}
</style>
