// 银行监管首页
const app = getApp();

Page({
  data: {
    userInfo: null,
    dashboardData: {
      totalLoans: 0,
      pendingApprovals: 0,
      riskAlerts: 0,
      complianceScore: 0
    },
    recentActivities: [],
    riskAlerts: [],
    quickActions: [
      {
        name: '贷款审批',
        icon: 'loan-approve',
        url: '/pages/loan/list?status=pending',
        permission: 'loan.approve'
      },
      {
        name: '风险监控',
        icon: 'risk-monitor',
        url: '/pages/risk/dashboard',
        permission: 'risk.view'
      },
      {
        name: '合规检查',
        icon: 'compliance',
        url: '/pages/compliance/check',
        permission: 'compliance.check'
      },
      {
        name: '审计报告',
        icon: 'audit-report',
        url: '/pages/audit/list',
        permission: 'audit.view'
      }
    ],
    loading: true,
    refreshing: false
  },

  onLoad() {
    this.checkLogin();
  },

  onShow() {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo
      });
      this.loadData();
    }
  },

  onPullDownRefresh() {
    this.setData({ refreshing: true });
    this.loadData().finally(() => {
      this.setData({ refreshing: false });
      wx.stopPullDownRefresh();
    });
  },

  // 检查登录状态
  checkLogin() {
    if (!app.globalData.userInfo) {
      wx.navigateTo({
        url: '/pages/auth/login'
      });
      return;
    }
    
    this.setData({
      userInfo: app.globalData.userInfo
    });
    this.loadData();
  },

  // 加载数据
  async loadData() {
    try {
      this.setData({ loading: true });
      
      await Promise.all([
        this.loadDashboardData(),
        this.loadRecentActivities(),
        this.loadRiskAlerts()
      ]);
    } catch (error) {
      console.error('加载数据失败：', error);
      app.showError('加载数据失败');
    } finally {
      this.setData({ loading: false });
    }
  },

  // 加载仪表板数据
  async loadDashboardData() {
    try {
      const res = await app.request({
        url: '/supervision/dashboard',
        method: 'GET'
      });
      
      this.setData({
        dashboardData: res.data || {}
      });
    } catch (error) {
      console.error('加载仪表板数据失败：', error);
    }
  },

  // 加载最近活动
  async loadRecentActivities() {
    try {
      const res = await app.request({
        url: '/supervision/activities',
        method: 'GET',
        data: { limit: 10 }
      });
      
      this.setData({
        recentActivities: res.data.list || []
      });
    } catch (error) {
      console.error('加载最近活动失败：', error);
    }
  },

  // 加载风险警报
  async loadRiskAlerts() {
    try {
      const res = await app.request({
        url: '/supervision/risk-alerts',
        method: 'GET',
        data: { 
          status: 'active',
          limit: 5 
        }
      });
      
      this.setData({
        riskAlerts: res.data.list || []
      });
    } catch (error) {
      console.error('加载风险警报失败：', error);
    }
  },

  // 快捷操作点击
  onQuickAction(e) {
    const { action } = e.currentTarget.dataset;
    
    // 检查权限
    if (action.permission && !app.hasPermission(action.permission)) {
      app.showError('权限不足，请联系管理员');
      return;
    }
    
    if (action.url.includes('tab')) {
      wx.switchTab({ url: action.url });
    } else {
      wx.navigateTo({ url: action.url });
    }
  },

  // 查看活动详情
  onActivityTap(e) {
    const { activity } = e.currentTarget.dataset;
    
    // 根据活动类型跳转到不同页面
    switch (activity.type) {
      case 'loan_approval':
        wx.navigateTo({
          url: `/pages/loan/detail?id=${activity.target_id}`
        });
        break;
      case 'risk_alert':
        wx.navigateTo({
          url: `/pages/risk/analysis?id=${activity.target_id}`
        });
        break;
      case 'compliance_check':
        wx.navigateTo({
          url: `/pages/compliance/report?id=${activity.target_id}`
        });
        break;
      case 'audit':
        wx.navigateTo({
          url: `/pages/audit/detail?id=${activity.target_id}`
        });
        break;
      default:
        app.showError('暂不支持查看此类活动详情');
    }
  },

  // 查看风险警报详情
  onRiskAlertTap(e) {
    const { alert } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/risk/analysis?id=${alert.id}`
    });
  },

  // 查看所有活动
  onViewAllActivities() {
    wx.navigateTo({
      url: '/pages/notification/index'
    });
  },

  // 查看所有风险警报
  onViewAllRiskAlerts() {
    wx.navigateTo({
      url: '/pages/risk/dashboard?tab=alerts'
    });
  },

  // 格式化数值
  formatNumber(num) {
    if (num >= 10000) {
      return (num / 10000).toFixed(1) + '万';
    }
    return num.toString();
  },

  // 格式化金额
  formatMoney(amount) {
    return app.formatMoney(amount);
  },

  // 格式化时间
  formatTime(timestamp) {
    return app.formatTime(timestamp);
  },

  // 格式化风险等级
  formatRiskLevel(level) {
    return app.formatRiskLevel(level);
  },

  // 获取合规分数颜色
  getComplianceScoreColor(score) {
    if (score >= 90) return '#28a745';
    if (score >= 80) return '#ffc107';
    if (score >= 70) return '#fd7e14';
    return '#dc3545';
  }
});