<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.projectIncharge">
          项目负责人：{{ form.projectIncharge }}
        </view>
        <view class="tags">
          <text class="tag bg-blue">{{ getProjectTypeLabel(form.projectType) }}</text>
        </view>
      </view>
    </view>
    <view class="tabs-container">
        <uv-tabs :list="tabList" :current="currentTab" @change="onTabChange"
        :activeStyle="{ color: '#1c9bfd', fontWeight: 'bold' }"
        :inactiveStyle="{ color: '#666' }" lineColor="#1c9bfd"
        :scrollable="true"></uv-tabs>
    </view>
    <scroll-view scroll-y class="content-area" :show-scrollbar="false">
        <view class="component-wrapper" v-if="currentTab === 0">
          <CommonSection title="项目信息">
            <CommonInfoRow label="项目编号" :value="form.projectNo" />
          <CommonInfoRow label="项目来源" :value="form.projectSource" />
          <CommonInfoRow label="项目负责人" :value="form.projectIncharge" />
          <CommonInfoRow label="所属科室" :value="form.projectDeptName" />
          <CommonInfoRow label="经费卡">
            <template v-if="form.type == '10'">{{ form.cardNo }}_上级拨款</template>
            <template v-else-if="form.type == '20'">{{ form.cardNo }}_匹配经费</template>
            <template v-else-if="form.type == '30'">{{ form.cardNo }}_横向经费</template>
            <template v-else>-</template>
          </CommonInfoRow>
          <CommonInfoRow label="费用科目" :value="form.subjName" />
          <CommonInfoRow label="入账金额" :value="showAmount ? amountUnitFormatter(showAmount) + '元' : '-'" :isAmount="true" />
          <CommonInfoRow label="可用金额" :value="showBalanceAmount ? amountUnitFormatter(showBalanceAmount) + '元' : '-'" :isAmount="true" />
          <CommonInfoRow label="费用类型" :value="form.subSubjName" />
          <CommonInfoRow label="事项" :value="form.purpose" />
        </CommonSection>

        <CommonSection title="报销经费">
          <CommonInfoRow label="经办人" :value="form.handle" />
          <CommonInfoRow label="支出金额" :value="amountUnitFormatter(form.amount) + '元'" :isAmount="true" />
          <CommonInfoRow label="结算金额" :value="form.settleAmount !== null && form.settleAmount !== undefined ? amountUnitFormatter(form.settleAmount) + '元' : '-'" :isAmount="true" />
        </CommonSection>
        </view>

        <!-- 发票信息 -->
        <view class="component-wrapper" v-else-if="currentTab === 1">
          <template v-if="form.invoice && form.invoice.length > 0">
            <CommonSection 
              v-for="(item, index) in form.invoice" 
              :key="'invoice-' + index"
              :title="'发票信息 ' + (Number(index) + 1)"
            >
              <CommonInfoRow label="发票号码" :value="item.invoiceNo" />
              <CommonInfoRow label="金额" :value="amountUnitFormatter(item.amount) + '元'" :isAmount="true" />
              <CommonInfoRow label="开票日期" :value="item.invoiceBy ? formatDate(new Date(item.invoiceBy), 'YYYY-MM-DD') : '-'" />
              
              <view class="mt10" v-if="item.fileList && item.fileList.length > 0">
                <view class="file-label">发票附件：</view>
                <view class="file-card">
                  <template v-for="(file, idx) in item.fileList" :key="idx">
                    <uv-image 
                      v-if="/\.(jpeg|jpg|gif|png|webp|bmp)$/i.test(file.name || '')" 
                      class="file-img mt10" 
                      :src="file.url" 
                      @click="onPreview(file.url)" 
                      width="120rpx" 
                      height="120rpx" 
                    ></uv-image>
                    <view class="file-doc mt10" v-else @click="onPreview(file.url)">
                      <uv-icon name="file-text" size="40"></uv-icon>
                      <text class="file-name">{{ file.name }}</text>
                    </view>
                  </template>
                </view>
              </view>
            </CommonSection>
          </template>
          <uv-empty v-else mode="data" text="暂无发票信息" margin-top="100"></uv-empty>
        </view>

        <!-- 支付信息 -->
        <view class="component-wrapper" v-else-if="currentTab === 2">
          <template v-if="form.payment && form.payment.length > 0">
            <CommonSection 
              v-for="(item, index) in form.payment" 
              :key="'payment-' + index"
              :title="'支付信息 ' + (Number(index) + 1)"
            >
              <CommonInfoRow label="支付方式">
                <template v-if="item.payType == '10'">银行转账</template>
                <template v-else-if="item.payType == '20'">现金</template>
                <template v-else-if="item.payType == '30'">国库集中支付</template>
                <template v-else>-</template>
              </CommonInfoRow>
              <CommonInfoRow label="收款人/单位" :value="item.receiver" />
              <CommonInfoRow label="个人/单位类型" :value="getDictLabel(receiverTypeOptions, item.receiverType)" />
              <CommonInfoRow label="金额" :value="amountUnitFormatter(item.amount) + '元'" :isAmount="true" />
            </CommonSection>
          </template>
          <uv-empty v-else mode="data" text="暂无支付信息" margin-top="100"></uv-empty>
        </view>

        <!-- 附件信息 -->
        <view class="component-wrapper" v-else-if="currentTab === 3">
          <template v-if="form.fileList && form.fileList.length > 0">
            <CommonSection title="附件信息">
              <view v-for="(file, idx) in form.fileList" :key="'file-' + idx" style="margin-bottom: 24rpx; padding-bottom: 24rpx; border-bottom: 1px dashed #eee;">
                <view style="font-size: 28rpx; color: #333; margin-bottom: 10rpx;">文件类型：{{ file.fileType || '-' }} <text v-if="file.required" style="color: #f5222d;">*</text></view>
                <view class="file-card">
                  <uv-image 
                    v-if="/\.(jpeg|jpg|gif|png|webp|bmp)$/i.test(file.name || '')" 
                    class="file-img mt10" 
                    :src="file.url" 
                    @click="onPreview(file.url)" 
                    width="120rpx" 
                    height="120rpx" 
                  ></uv-image>
                  <view class="file-doc mt10" v-else @click="onPreview(file.url)">
                    <uv-icon name="file-text" size="40"></uv-icon>
                    <text class="file-name">{{ file.name }}</text>
                  </view>
                </view>
              </view>
            </CommonSection>
          </template>
          <uv-empty v-else mode="data" text="暂无附件信息" margin-top="100"></uv-empty>
        </view>

      <view class="component-wrapper" v-else-if="currentTab === 4">
        <FlowTable :id="form.id || 0" :businessCode="'' + (form.id || '')" defCode="sci_fund_expense" />
      </view>
    </scroll-view>
  </view>
</template>

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

const systemApi = useSystemApi();
const expenseRemindApi = useExpenseRemindApi();
const fundApi = useFundApi();
const expenseApi = useExpenseApi();
const fundCardApi = useFundCardApi();
const rebateApi = useRebateApi();

const receiverTypeOptions = ref<any[]>([]);
const showAmount = ref(0);
const showBalanceAmount = ref(0);

const tabList = ref([{ name: '项目信息' }, { name: '发票信息' }, { name: '支付信息' }, { name: '附件信息' }, { name: '审批详情' }]);
const currentTab = ref(0);

const onTabChange = (e: any) => {
  currentTab.value = e.index;
};

const form = ref<any>({
  id: 0,
  orderNo: '',
  price: 0,
  buyerName: '',
  createdTime: '',
  status: '',
  fileList: [],
  amount: 0,
  noticeId: null,
  projectType: '',
  allotId: null,
  handle: '',
  projectId: 0,
  projectIncharge: '',
  projectCode: '',
  projectName: '',
  projectSource: '',
  deptName: '',
  startDate: '',
  endDate: '',
  purpose: '',
  invoice: [],
  payment: [],
  type: '',
  cardNo: '',
  settleAmount: 0,
  projectDeptName: '',
  deptId: null,
  subjCode: '',
  subjName: '',
  subSubjCode: '',
  subSubjName: '',
  expendTime: '',
  expend: ''
});

const getProjectTypeLabel = (type: string) => {
  const map: Record<string, string> = {
    '10': '纵向项目',
    '20': '横向项目',
    '30': '内部项目',
    '40': '重点学科',
    '50': '人才类项目',
    '60': '科研平台'
  };
  return map[type] || '-';
};

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 : '-';
};

const formatFileUrl = (url: string) => {
  if (!url) return '';
  if (url.startsWith('http')) return url;
  return import.meta.env.VITE_SCIENTIFIC + url;
};

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

const getAmountInfo = async () => {
  if (!form.value.projectId || !form.value.subjCode) return;
  const params = {
    projectId: form.value.projectId,
    projectType: form.value.projectType,
    type: form.value.type,
    subjCode: form.value.subjCode
  };
  showAmount.value = 0;
  showBalanceAmount.value = 0;
  try {
    const res: any = await fundCardApi.getSubjAmount(params);
    if (res.code == 200 && res.data) {
      showAmount.value = res.data.amount;
      showBalanceAmount.value = res.data.balanceAmount;
    }
  } catch (err) {
    console.error(err);
  }
};

const getFundDetail = async (id: number, remindId: number) => {
  try {
    const post = id ? rebateApi.getDetails : rebateApi.getExpenseByNoticeId;
    const res: any = await post({ id: id || remindId });
    if (res.code == 200 && res.data) {
      const data = res.data;
      const fileList = data.fileUrl ? JSON.parse(data.fileUrl) : [];
      data.fileList = fileList.map((item: any) => ({
        url: formatFileUrl(item.fileUrl),
        name: item.fileName,
        invoiceType: item.invoiceType || item.fileType,
        fileType: item.fileType,
        required: item.required
      }));
      const invoice = data.invoice ? data.invoice : [];
      data.invoice = invoice.map((item: any) => ({
        ...item,
        fileList: [
          {
            url: formatFileUrl(item.fileUrl),
            name: item.fileName,
            invoiceType: item.invoiceType || ''
          }
        ]
      }));
      form.value = data;
      getAmountInfo();
    }
  } catch (err) {
    console.error(err);
  }
};

const onPreview = (url: string) => {
  uni.previewImage({
    urls: [url]
  });
};

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

<style lang="scss" scoped>
.detail-container {
  height: calc(100vh - var(--window-top));
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
  box-sizing: border-box;
}

.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;
}

.content-area {
  flex: 1;
  height: 0;
}

.component-wrapper {
  margin: 0 30rpx;
  padding-top: 20rpx;
  padding-bottom: calc(40rpx + env(safe-area-inset-bottom));
}

.mt10 {
  margin-top: 20rpx;
}

.file-label {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.file-card {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  
  .file-img {
    border-radius: 8rpx;
    overflow: hidden;
    border: 1px solid #eee;
  }
  
  .file-doc {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 120rpx;
    height: 120rpx;
    background-color: #f7f8fa;
    border-radius: 8rpx;
    overflow: hidden;
    
    .file-name {
      font-size: 22rpx;
      color: #999;
      margin-top: 10rpx;
      width: 100%;
      text-align: center;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      padding: 0 4rpx;
    }
  }
}
</style>
