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

      <!-- 2. 报销经费 -->
      <view class="common-section-card mt20">
        <view class="section-title">报销经费</view>
        <view class="info-row">
          <text class="label">经办人</text>
          <text class="value">{{ form.handle || '-' }}</text>
        </view>
        <view class="info-row">
          <text class="label">支出金额</text>
          <text class="value red-color font-bold">￥{{ formatAmount(form.amount) }} 元</text>
        </view>
      </view>

      <!-- 3. 发票信息 -->
      <view class="common-section-card mt20" v-if="form.invoice?.length">
        <view class="section-title">发票信息</view>
        <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>
      </view>

      <!-- 4. 支付信息 -->
      <view class="common-section-card mt20" v-if="form.payment?.length">
        <view class="section-title">支付信息</view>
        <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>
      </view>

      <!-- 5. 附件 -->
      <view class="common-section-card mt20" v-if="form.fileList?.length">
        <view class="section-title">附件信息</view>
        <view class="common-file-list">
          <view class="file-item" v-for="(file, fIdx) in form.fileList" :key="fIdx" 
               v-show="file.fileUrl"
               @click="previewFile(file.fileUrl, file.fileName)">
            <view class="file-info">
              <text class="f-name">{{ file.fileName }}</text>
              <text class="f-meta">{{ file.fileType }}</text>
            </view>
          </view>
        </view>
      </view>
    </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 to from 'await-to-js';

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 formatAmount = (num: number | string) => {
  if (!num && num !== 0) return '0.00';
  return Number(num).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
};

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: 20rpx 0;
    border-bottom: 1rpx solid #f5f5f5;
    &:last-child { border-bottom: none; }
    .i-main {
      display: flex;
      justify-content: space-between;
      .i-no { font-size: 28rpx; color: #333; font-weight: 500; }
      .i-amount { font-size: 28rpx; color: #ff4d4f; font-weight: bold; }
    }
    .i-date { font-size: 24rpx; color: #999; margin-top: 8rpx; }
    .i-files { margin-top: 10rpx; }
  }
}

.payment-list {
  .pay-item {
    background: #fcfcfc;
    padding: 20rpx;
    border-radius: 8rpx;
    margin-bottom: 15rpx;
    .p-header {
      display: flex;
      justify-content: space-between;
      margin-bottom: 12rpx;
      .p-type { font-size: 26rpx; background: #e6f7ff; color: #1890ff; padding: 2rpx 12rpx; border-radius: 4rpx; }
      .p-amount { font-size: 28rpx; color: #333; font-weight: bold; }
    }
    .p-row {
      display: flex;
      justify-content: space-between;
      margin-top: 6rpx;
      font-size: 24rpx;
      .pl { color: #999; }
      .pv { color: #555; }
    }
  }
}

.link-text { color: #007aff; font-size: 24rpx; }
.font-bold { font-weight: bold; }
</style>
