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

Page({
  data: {
    businessStats: {
      loanProducts: 0,
      applications: 0,
      contracts: 0,
      releases: 0
    }
  },

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

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

  // 加载业务统计
  async loadBusinessStats() {
    try {
      // 并行获取各项统计数据
      const [productsRes, applicationsRes, contractsRes, releasesRes] = await Promise.allSettled([
        apiService.loanProducts.getStats(),
        // apiService.loanApplications.getStats(),
        // apiService.loanContracts.getStats(),
        apiService.loanReleases.getStats()
      ]);

      const stats = {
        loanProducts: productsRes.status === 'fulfilled' ? productsRes.value.data?.total || 0 : 0,
        applications: applicationsRes.status === 'fulfilled' ? applicationsRes.value.data?.total || 0 : 0,
        contracts: contractsRes.status === 'fulfilled' ? contractsRes.value.data?.total || 0 : 0,
        releases: releasesRes.status === 'fulfilled' ? releasesRes.value.data?.total || 0 : 0
      };

      this.setData({
        businessStats: stats
      });
    } catch (error) {
      console.error('加载业务统计失败:', error);
      // 使用默认数据
      this.setData({
        businessStats: {
          loanProducts: 0,
          applications: 0,
          contracts: 0,
          releases: 0
        }
      });
    }
  },

  // 导航到对应页面
  navigateToPage(e) {
    const type = e.currentTarget.dataset.type;
    
    switch (type) {
      case 'loan-products':
        wx.navigateTo({
          url: '/pages/business/loan-products/loan-products'
        });
        break;
      case 'loan-applications':
        wx.navigateTo({
          url: '/pages/business/loan-applications/loan-applications'
        });
        break;
      case 'loan-contracts':
        wx.navigateTo({
          url: '/pages/business/loan-contracts/loan-contracts'
        });
        break;
      case 'loan-releases':
        wx.navigateTo({
          url: '/pages/business/loan-releases/loan-releases'
        });
        break;
      default:
        wx.showToast({
          title: '功能开发中',
          icon: 'none'
        });
    }
  },

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