// pages/business/loan-contracts/detail.js
const { apiService } = require('../../../services/apiService');
const auth = require('../../../utils/auth.js');

Page({
  data: {
    contract: null,
    loading: false,
    error: null,
    contractId: null,
    typeMap: {
      'personal': '个人贷款',
      'mortgage': '住房贷款',
      'business': '企业贷款',
      'agricultural': '农业贷款',
      'livestock_collateral': '养殖抵押贷款'
    },
    statusMap: {
      'active': '生效中',
      'expired': '已到期',
      'terminated': '已终止',
      'completed': '已完成',
      'pending': '待处理'
    }
  },

  onLoad(options) {
    // 检查认证状态
    if (!auth.isAuthenticated()) {
      wx.reLaunch({
        url: '/pages/login/login'
      });
      return;
    }
    
    const { contractId } = options;
    if (contractId) {
      this.setData({ contractId });
      this.loadContractDetail();
    } else {
      this.setData({ 
        error: '缺少合同ID参数' 
      });
    }
  },

  onShow() {
    // 检查认证状态
    if (!auth.isAuthenticated()) {
      wx.reLaunch({
        url: '/pages/login/login'
      });
      return;
    }
  },

  // 加载合同详情
  async loadContractDetail() {
    if (!this.data.contractId) return;
    
    this.setData({ 
      loading: true, 
      error: null 
    });
    
    try {
      console.log('开始获取合同详情，合同ID:', this.data.contractId);
      const response = await apiService.loanContracts.getById(this.data.contractId);
      console.log('API响应:', response);
      
      if (response && response.success && response.data) {
        const contract = response.data;
        
        // 字段映射和格式化
        const formattedContract = {
          ...contract,
          customerName: contract.borrowerName || contract.farmerName || contract.customerName,
          customerId: contract.borrowerIdNumber || contract.customerId,
          typeText: this.data.typeMap[contract.type] || contract.type,
          statusText: this.data.statusMap[contract.status] || contract.status,
          signDate: this.formatDate(contract.contractTime || contract.signDate),
          expiryDate: this.formatDate(contract.maturityTime || contract.expiryDate),
          completedTime: this.formatDate(contract.completedTime),
          disbursementTime: this.formatDate(contract.disbursementTime),
          amount: contract.amount || 0,
          term: contract.term || 0,
          interestRate: contract.interestRate || 0,
          phone: contract.phone || '暂无',
          contractNumber: contract.contractNumber || '暂无',
          applicationNumber: contract.applicationNumber || '暂无',
          assetType: contract.assetType || '暂无',
          purpose: contract.purpose || '暂无',
          productName: contract.productName || '暂无',
          paidAmount: contract.paidAmount || 0,
          remainingAmount: contract.remainingAmount || 0,
          repaymentProgress: contract.repaymentProgress || 0,
          remark: contract.remark || ''
        };
        
        this.setData({
          contract: formattedContract,
          loading: false
        });
      } else {
        console.error('API返回失败:', response);
        throw new Error(response.message || '获取合同详情失败');
      }
    } catch (error) {
      console.error('加载合同详情失败:', error);
      console.error('错误详情:', {
        message: error.message,
        stack: error.stack,
        contractId: this.data.contractId
      });
      
      // 使用模拟数据作为降级处理
      console.log('使用模拟数据作为降级处理');
      const mockContract = {
        id: this.data.contractId,
        contractNumber: 'CONTRACT-202401180001',
        customerName: '张三',
        customerId: '110101199001010001',
        typeText: '个人贷款',
        statusText: '生效中',
        amount: 200000,
        term: 24,
        interestRate: 6.5,
        signDate: '2024-01-18',
        expiryDate: '2026-01-18',
        phone: '13800138000',
        applicationNumber: 'APP-202401180001',
        assetType: '养殖设备',
        purpose: '养殖经营',
        productName: '养殖贷款',
        paidAmount: 50000,
        remainingAmount: 150000,
        repaymentProgress: 25,
        remark: '测试合同数据'
      };
      
      this.setData({
        contract: mockContract,
        loading: false
      });
      
      wx.showToast({
        title: '使用模拟数据',
        icon: 'none',
        duration: 2000
      });
    }
  },

  // 格式化日期
  formatDate(dateString) {
    if (!dateString) return '';
    try {
      const date = new Date(dateString);
      return date.toLocaleDateString('zh-CN');
    } catch (error) {
      return dateString;
    }
  },

  // 重试加载
  retryLoadContractDetail() {
    this.loadContractDetail();
  },

  // 用户点击右上角分享
  onShareAppMessage() {
    return {
      title: '合同详情',
      path: `/pages/business/loan-contracts/detail?contractId=${this.data.contractId}`
    };
  }
});
