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

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

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

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

  // 加载合同数据
  async loadContracts() {
    this.setData({ loading: true });
    
    try {
      const params = {
        page: 1,
        limit: 20,
        search: this.data.searchKeyword,
        status: this.data.filterStatus === 'all' ? '' : this.data.filterStatus
      };
      
      const response = await apiService.loanContracts.getList(params);
      
      if (response.success) {
        const contracts = response.data.contracts.map(contract => ({
          ...contract,
          // 字段映射 - 根据接口返回数据调整
          customerName: contract.borrowerName || contract.farmerName || contract.customerName,
          customerId: contract.borrowerIdNumber || contract.customerId,
          type: contract.type,
          typeText: this.data.typeMap[contract.type] || contract.type,
          status: contract.status,
          statusText: this.data.statusMap[contract.status] || contract.status,
          amount: contract.amount,
          term: contract.term,
          interestRate: contract.interestRate,
          signDate: this.formatDate(contract.contractTime || contract.signDate),
          expiryDate: this.formatDate(contract.maturityTime || contract.expiryDate),
          phone: contract.phone,
          contractNumber: contract.contractNumber,
          applicationNumber: contract.applicationNumber,
          applicationQuantity: contract.applicationQuantity,
          assetType: contract.assetType,
          purpose: contract.purpose,
          productName: contract.productName,
          paidAmount: contract.paidAmount,
          remainingAmount: contract.remainingAmount,
          repaymentProgress: contract.repaymentProgress,
          completedTime: contract.completedTime,
          disbursementTime: contract.disbursementTime,
          remark: contract.remark
        }));
        
        this.setData({
          contracts,
          loading: false
        });
      } else {
        throw new Error(response.message || '获取合同列表失败');
      }
    } catch (error) {
      console.error('加载合同失败:', error);
      
      // 使用模拟数据作为降级处理
      const mockContracts = [
        {
          id: 1,
          contractNumber: 'CONTRACT-202401180001',
          customerName: '张三',
          type: 'personal',
          typeText: '个人贷款',
          status: 'active',
          statusText: '生效中',
          amount: 200000,
          term: 24,
          interestRate: 6.5,
          signDate: '2024-01-18',
          expiryDate: '2026-01-18',
          phone: '13800138000'
        },
        {
          id: 2,
          contractNumber: 'CONTRACT-202401180002',
          customerName: '李四',
          type: 'mortgage',
          typeText: '住房贷款',
          status: 'active',
          statusText: '生效中',
          amount: 500000,
          term: 240,
          interestRate: 4.5,
          signDate: '2024-01-18',
          expiryDate: '2044-01-18',
          phone: '13800138001'
        }
      ];
      
      this.setData({
        contracts: mockContracts,
        loading: false
      });
      
      wx.showToast({
        title: '使用模拟数据',
        icon: 'none'
      });
    }
  },

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

  // 搜索输入
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
    this.loadContracts();
  },

  // 筛选状态
  onFilterChange(e) {
    const status = e.detail.value;
    this.setData({
      filterStatus: status
    });
    this.loadContracts();
  },

  // 查看合同详情
  viewContractDetail(e) {
    console.log('点击详情按钮', e);
    const contractId = e.currentTarget.dataset.contractId;
    console.log('查看合同详情:', contractId);
    
    if (!contractId) {
      wx.showToast({
        title: '合同ID不存在',
        icon: 'error'
      });
      return;
    }
    
    wx.navigateTo({
      url: `/pages/business/loan-contracts/detail?contractId=${contractId}`,
      success: (res) => {
        console.log('跳转到详情页面成功', res);
      },
      fail: (err) => {
        console.error('跳转到详情页面失败', err);
        wx.showModal({
          title: '跳转失败',
          content: `错误信息: ${err.errMsg || '未知错误'}`,
          showCancel: false
        });
      }
    });
  },

  // 编辑合同
  editContract(e) {
    console.log('点击编辑按钮', e);
    const contractId = e.currentTarget.dataset.contractId;
    console.log('编辑合同:', contractId);
    
    if (!contractId) {
      wx.showToast({
        title: '合同ID不存在',
        icon: 'error'
      });
      return;
    }
    
    // 跳转到编辑页面
    wx.navigateTo({
      url: `/pages/business/loan-contracts/edit?contractId=${contractId}`,
      success: (res) => {
        console.log('跳转到编辑页面成功', res);
      },
      fail: (err) => {
        console.error('跳转到编辑页面失败', err);
        wx.showToast({
          title: '跳转失败',
          icon: 'error'
        });
      }
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadContracts().finally(() => {
      wx.stopPullDownRefresh();
    });
  }
});
