<template>
  <view class="detail-container">
    <view class="header-card">
      <view class="title">{{ form.projectName || '未知名称' }}</view>
      <view class="meta-row">
        <view class="leader" v-if="form.projectLeaderName">
          项目负责人：{{ form.projectLeaderName }}
        </view>
        <view class="tags">
          <text class="tag bg-blue">{{ formatterProjctType(form.projectType) }}</text>
        </view>
      </view>
    </view>
    <view class="tabs-container">
      <uv-tabs :list="tabList" :current="currentTab" @click="handleTabClick"
        :activeStyle="{ color: '#1c9bfd', fontWeight: 'bold' }" :inactiveStyle="{ color: '#666' }" lineColor="#1c9bfd"
        :scrollable="false"></uv-tabs>
    </view>

    <view class="scroll-wrapper">
      <scroll-view scroll-y class="content-area" :show-scrollbar="false">
      <view class="component-wrapper">
        <!-- 1. 单据信息 -->
        <view v-if="currentTab === 0">
          <CommonSection title="到款信息" :isFirst="true">
            <CommonInfoRow label="到账金额(元)" :value="amountUnitFormatter(paymentForm.amount)" isAmount />
            <CommonInfoRow label="管理费(元)" :value="amountUnitFormatter(paymentForm.manageAmount)" isAmount />
            <CommonInfoRow label="税费(元)" :value="amountUnitFormatter(paymentForm.taxAmount)" isAmount />
            <CommonInfoRow label="待认领金额(元)" :value="amountUnitFormatter(Number(paymentForm.allotAmount || 0))"
              isAmount />
            <CommonInfoRow label="到款日期"
              :value="paymentForm.date ? formatDate(new Date(paymentForm.date), 'YYYY-MM-DD') : '-'" />
            <CommonInfoRow label="经费类型" :value="getDictLabel(paymentReceivedTypeOptions, paymentForm.type)" />
            <CommonInfoRow label="打款单位" :value="paymentForm.unit || '-'" />
          </CommonSection>

          <CommonSection title="项目信息">
            <CommonInfoRow label="项目负责人" :value="form.projectLeaderName" />
            <CommonInfoRow label="科室" :value="form.deptName" />
          </CommonSection>

          <CommonSection title="认领经费" v-if="form.detail && form.detail.length > 0">
            <CommonInfoRow v-for="(item, index) in form.detail" :key="item.id || index" :label="item.subjName"
              :value="amountUnitFormatter(item.amount) + '元'" :isAmount="true" />
          </CommonSection>
        </view>

        <!-- 2. 审批记录 -->
        <view v-else-if="currentTab === 1">
          <CommonSection title="审批记录" :isFirst="true" v-if="form.id">
            <FlowTable :id="form.id" :businessCode="form.id ? form.id.toString() : ''" defCode="sci_fund_allot_apply" />
          </CommonSection>
        </view>

        <view class="bottom-spacer"></view>
      </view>
      </scroll-view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { useFundApi, useClaimApi } from '@/api/fund/index';
import { useSystemApi } from '@/api/system/index';
import { formatDate } from '@/utils/date';
import CommonSection from '@/components/ui/CommonSection.vue';
import CommonInfoRow from '@/components/ui/CommonInfoRow.vue';
import FlowTable from '@/pages/project/components/detail/FlowTable.vue';

const claimApi = useClaimApi();
const fundApi = useFundApi();
const systemApi = useSystemApi();

const tabList = ref([
  { name: '单据信息', index: 0 },
  { name: '审批记录', index: 1 }
]);
const currentTab = ref(0);

const handleTabClick = (item: any) => {
  currentTab.value = item.index;
};

const paymentReceivedTypeOptions = ref<any[]>([]);

const paymentForm = ref<any>({
  detail: [],
  id: 0,
  amount: 0,
  manageAmount: 0,
  taxAmount: 0,
  proportion: 0,
  date: '',
  type: '',
  serialNo: '',
  unit: '',
  remark: ''
});

const form = ref<any>({
  id: 0,
  amount: '',
  externalAmount: '',
  fundId: null,
  internalAmount: '',
  projectId: null,
  remark: '',
  schemeId: null,
  projectName: '',
  projectType: '',
  detail: []
});

const amountUnitFormatter = (val: any) => {
  if (val === null || val === undefined || val === '') return '0.00';
  const num = Number(val);
  return isNaN(num) ? '0.00' : num.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};

const getDictLabel = (options: any[], value: string) => {
  const find = options.find((item) => item.dictValue === value);
  return find ? find.dictLabel : value || '-';
};

const getDict = async () => {
  try {
    const res: any = await systemApi.getDictDataByType('PaymentReceivedType');
    if (res.code == 200 && res.data) {
      paymentReceivedTypeOptions.value = res.data.values || [];
    }
  } catch (err) {
    console.error(err);
  }
};

const formatterProjctType = (val: string) => {
  switch (val) {
    case '10': return '纵向项目';
    case '20': return '横向项目';
    case '30': return '内部项目';
    case '40': return '重点学科';
    default: return '-';
  }
};

const getFundDetail = async (id: number) => {
  try {
    const res: any = await claimApi.getEntityByFundId({ fundId: id });
    if (res.code == 200 && res.data) {
      form.value = { ...form.value, ...res.data };
    }

    const pRes: any = await fundApi.getDetails({ id });
    if (pRes.code == 200 && pRes.data) {
      paymentForm.value = pRes.data;
    }
  } catch (err) {
    console.error('获取详情失败', err);
  }
};

onLoad((options: any) => {
  const id = options.id ? Number(options.id) : 0;
  getDict();
  if (id) {
    getFundDetail(id);
  }
});
</script>

<style lang="scss" scoped>
.detail-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
  box-sizing: border-box;
  overflow: hidden;
}

.header-card {
  flex-shrink: 0;
  background: linear-gradient(135deg, #1c9bfd 0%, #15a982 100%);
  padding: 40rpx 30rpx 80rpx;
  color: #fff;
  border-bottom-left-radius: 40rpx;
  border-bottom-right-radius: 40rpx;
  box-shadow: 0 10rpx 20rpx rgba(28, 155, 253, 0.2);

  .title {
    font-size: 40rpx;
    font-weight: bold;
    margin-bottom: 20rpx;
    line-height: 1.4;
  }

  .meta-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 20rpx;
  }

  .leader {
    font-size: 28rpx;
    opacity: 0.9;
  }

  .tags {
    display: flex;
    flex-wrap: wrap;
    gap: 16rpx;

    .tag {
      font-size: 24rpx;
      padding: 6rpx 20rpx;
      border-radius: 30rpx;
      border: 2rpx solid rgba(255, 255, 255, 0.4);
      background: rgba(255, 255, 255, 0.1);
      backdrop-filter: blur(4px);
    }
  }
}

.tabs-container {
  flex-shrink: 0;
  margin: -40rpx 30rpx 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  padding: 10rpx 0;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
  position: relative;
  z-index: 10;
}

.scroll-wrapper {
  flex: 1;
  overflow: hidden;
}

.content-area {
  height: 100%;
}

.component-wrapper {
  padding: 30rpx;
  box-sizing: border-box;
}

.bottom-spacer {
  height: calc(10rpx + env(safe-area-inset-bottom));
  width: 100%;
}
</style>
