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

Page({
  data: {
    applications: [],
    loading: false,
    searchKeyword: '',
    filterStatus: 'all',
    typeMap: {
      'personal': '个人贷款',
      'mortgage': '住房贷款',
      'business': '企业贷款',
      'agricultural': '农业贷款'
    },
    statusMap: {
      'pending': '待审核',
      'processing': '审核中',
      'approved': '已通过',
      'rejected': '已拒绝'
    }
  },

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

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

  // 加载申请数据
  async loadApplications() {
    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.loanApplications.getList(params);
      
      if (response.success) {
        const applications = response.data.applications.map(application => ({
          ...application,
          // 字段映射 - 根据接口返回数据调整
          applicantName: application.borrowerName || application.farmerName || application.applicantName,
          applicantId: application.borrowerIdNumber || application.id,
          type: application.type,
          typeText: this.data.typeMap[application.type] || application.type,
          status: application.status,
          statusText: this.data.statusMap[application.status] || application.status,
          amount: application.amount || application.loanAmount,
          term: application.term || application.loanTerm,
          interestRate: application.interestRate,
          applicationTime: this.formatDate(application.applicationTime || application.created_at),
          phone: application.phone,
          purpose: application.purpose,
          applicationNumber: application.applicationNumber,
          applicationQuantity: application.applicationQuantity,
          assetType: application.assetType,
          borrowerIdNumber: application.borrowerIdNumber,
          borrowerName: application.borrowerName,
          farmerName: application.farmerName,
          approvedTime: application.approvedTime,
          rejectedTime: application.rejectedTime,
          remark: application.remark
        }));
        
        this.setData({
          applications,
          loading: false
        });
      } else {
        throw new Error(response.message || '获取申请列表失败');
      }
    } catch (error) {
      console.error('加载申请失败:', error);
      
      // 使用模拟数据作为降级处理
      const mockApplications = [
        {
          id: 1,
          applicationNumber: 'APP-202401180001',
          applicantName: '张三',
          type: 'personal',
          typeText: '个人贷款',
          status: 'pending',
          statusText: '待审核',
          amount: 200000,
          term: 24,
          interestRate: 6.5,
          applicationTime: '2024-01-18 09:30',
          phone: '13800138000',
          purpose: '个人消费'
        },
        {
          id: 2,
          applicationNumber: 'APP-202401180002',
          applicantName: '李四',
          type: 'mortgage',
          typeText: '住房贷款',
          status: 'approved',
          statusText: '已通过',
          amount: 500000,
          term: 240,
          interestRate: 4.5,
          applicationTime: '2024-01-18 10:15',
          phone: '13800138001',
          purpose: '购买住房'
        }
      ];
      
      this.setData({
        applications: mockApplications,
        loading: false
      });
      
      wx.showToast({
        title: '使用模拟数据',
        icon: 'none'
      });
    }
  },

  // 格式化日期
  formatDate(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  },

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

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

  // 查看申请详情
  viewApplicationDetail(e) {
    const applicationId = e.currentTarget.dataset.applicationId;
    wx.navigateTo({
      url: `/pages/business/loan-applications/detail?applicationId=${applicationId}`
    });
  },

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