<template>
  <view class="document-form">
    <uv-loading-icon v-if="loading" mode="circle" text="正在加载详情..."></uv-loading-icon>
    <template v-else-if="form">
      <!-- 1. 项目信息 -->
      <CommonSection title="项目信息" :isFirst="true">
        <CommonInfoRow label="项目类型" :value="getProjectTypeName(form.projectType)" />
        <CommonInfoRow label="项目名称" :value="form.projectName" />
        <CommonInfoRow label="项目编号" :value="form.projectNo" />
        <CommonInfoRow label="项目来源" :value="form.projectSource" />
        <CommonInfoRow label="负责人" :value="form.projectIncharge" />
        <CommonInfoRow label="所属科室" :value="form.projectDeptName" />
        <CommonInfoRow label="经费卡" :value="cardLabel" />
        <CommonInfoRow label="费用科目" :value="form.subjName" />
        <CommonInfoRow label="入款/可用">
          <text class="value primary-color">￥{{ formatAmount(showAmount) }} / ￥{{ formatAmount(showBalanceAmount) }}</text>
        </CommonInfoRow>
        <CommonInfoRow label="费用类型" :value="form.subSubjName" />
        <CommonInfoRow label="事项" :value="form.purpose" isColumn />
      </CommonSection>

      <!-- 2. 报销经费 -->
      <CommonSection title="报销经费">
        <CommonInfoRow label="经办人" :value="form.handle" />
        <CommonInfoRow label="支出金额" :value="form.amount" isAmount />
      </CommonSection>

      <!-- 3. 发票信息 -->
      <CommonSection title="发票信息" v-if="form.invoice?.length">
        <view class="invoice-list">
          <view class="invoice-item" v-for="(inv, idx) in form.invoice" :key="idx">
            <view class="i-main">
              <text class="i-no">No.{{ inv.invoiceNo }}</text>
              <text class="i-amount red-color">￥{{ formatAmount(inv.amount) }}</text>
            </view>
            <view class="i-date">{{ formatDate(inv.invoiceBy) }}</view>
            <view class="i-files" v-if="inv.fileUrl">
              <text class="link-text" @click="previewFile(inv.fileUrl, inv.fileName)">查看发票文件</text>
            </view>
          </view>
        </view>
      </CommonSection>

      <!-- 4. 支付信息 -->
      <CommonSection title="支付信息" v-if="form.payment?.length">
        <view class="payment-list">
          <view class="pay-item" v-for="(pay, pIdx) in form.payment" :key="pIdx">
            <view class="p-header">
              <text class="p-type">{{ getPayTypeLabel(pay.payType) }}</text>
              <text class="p-amount red-color">￥{{ formatAmount(pay.amount) }}</text>
            </view>
            <view class="p-row">
              <text class="pl">收款人/单位</text>
              <text class="pv">{{ pay.receiver }}</text>
            </view>
            <view class="p-row">
              <text class="pl">类型</text>
              <text class="pv">{{ getDictLabel('sci_receiver_type', pay.receiverType) }}</text>
            </view>
          </view>
        </view>
      </CommonSection>

      <!-- 5. 附件 -->
      <AttachmentList :list="form.fileList" 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 { useDocumentApi } from '@/api/document';
import { useDict } from '@/hooks/useDict';
import { formatDate } from '@/utils/date';
import { previewFile } from '@/utils/file';
import { formatAmount } from '@/utils/format';
import to from 'await-to-js';
import CommonSection from '@/components/ui/CommonSection.vue';
import CommonInfoRow from '@/components/ui/CommonInfoRow.vue';
import AttachmentList from './AttachmentList.vue';

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

const { getDictLabel } = useDict('sci_receiver_type');
const documentApi = useDocumentApi();
const form = ref<any>(null);
const loading = ref(false);

const projectTypeOptions = [
  { dictValue: '10', dictLabel: '纵向项目' },
  { dictValue: '20', dictLabel: '横向项目' },
  { dictValue: '30', dictLabel: '内部项目' },
  { dictValue: '50', dictLabel: '人才类项目' },
  { dictValue: '60', dictLabel: '科研平台' },
];

const getProjectTypeName = (val: string) => {
  const item = projectTypeOptions.find(opt => opt.dictValue === val);
  return item ? item.dictLabel : val;
};

const showAmount = ref(0);
const showBalanceAmount = ref(0);

const cardLabel = computed(() => {
  if (!form.value) return '';
  const typeMap: Record<string, string> = { '10': '上级拨款', '20': '匹配经费', '30': '横向经费' };
  return `${form.value.cardNo || ''}_${typeMap[form.value.type] || ''}`;
});

const getPayTypeLabel = (val: string) => {
  const map: Record<string, string> = { '10': '银行转账', '20': '现金', '30': '国库集中支付' };
  return map[val] || val;
};

const fetchData = async () => {
  if (!props.code) return;
  loading.value = true;
  
  // 1. 获取报销单详情
  const [err, res] = await to(documentApi.getFundExpenseById(props.code));
  if (!err && res?.data) {
    form.value = res.data;
    
    // 2. 获取经费余额情况 (对齐PC预览逻辑)
    if (form.value.projectId && form.value.subjCode) {
      const balanceParams = {
        projectId: form.value.projectId,
        projectType: form.value.projectType,
        subjCode: form.value.subjCode,
        type: form.value.type,
      };
      const [bErr, bRes] = await to(documentApi.getSubjAmount(balanceParams));
      if (!bErr && bRes?.data) {
        showAmount.value = bRes.data.amount || 0;
        showBalanceAmount.value = bRes.data.balanceAmount || 0;
      }
    }
  }
  
  loading.value = false;
};

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

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

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

.invoice-list {
  .invoice-item {
    padding: 24rpx 0;
    border-bottom: 2rpx dashed #e2e8f0;
    &:last-child { border-bottom: none; }
    .i-main {
      display: flex;
      justify-content: space-between;
      .i-no { font-size: 28rpx; color: #1e293b; font-weight: 600; }
      .i-amount { font-size: 30rpx; color: #ef4444; font-weight: 800; font-family: 'Inter', sans-serif; }
    }
    .i-date { font-size: 24rpx; color: #64748b; margin-top: 8rpx; }
    .i-files { margin-top: 10rpx; }
  }
}

.payment-list {
  .pay-item {
    background: #f8fafc;
    padding: 24rpx;
    border-radius: 12rpx;
    margin-bottom: 20rpx;
    border: 1rpx solid #f1f5f9;
    
    .p-header {
      display: flex;
      justify-content: space-between;
      margin-bottom: 16rpx;
      .p-type { 
        font-size: 22rpx; 
        background: #eff6ff; 
        color: #3b82f6; 
        padding: 4rpx 16rpx; 
        border-radius: 100rpx; 
        font-weight: 700;
        border: 1rpx solid #dbeafe;
      }
      .p-amount { font-size: 30rpx; color: #1e293b; font-weight: 800; }
    }
    .p-row {
      display: flex;
      justify-content: space-between;
      margin-top: 8rpx;
      font-size: 26rpx;
      .pl { color: #64748b; }
      .pv { color: #334155; font-weight: 500; }
    }
  }
}

.link-text { color: #3b82f6; font-size: 26rpx; font-weight: 600; }
</style>
