// 保险监管首页
const app = getApp();

Page({
  data: {
    userInfo: null,
    dashboardData: {
      totalPolicies: 0,
      activeClaims: 0,
      pendingApprovals: 0,
      riskAlerts: 0
    },
    recentActivities: [],
    claimAlerts: [],
    quickActions: [
      {
        name: '保单审批',
        icon: 'policy-approve',
        url: '/pages/policy/list?status=pending',
        permission: 'policy.approve'
      },
      {
        name: '理赔处理',
        icon: 'claim-process',
        url: '/pages/claim/list?status=reviewing',
        permission: 'claim.process'
      },
      {
        name: '风险评估',
        icon: 'risk-assess',
        url: '/pages/risk/assessment',
        permission: 'risk.assess'
      },
      {
        name: '合规检查',
        icon: 'compliance',
        url: '/pages/compliance/check',
        permission: 'compliance.check'
      }
    ],
    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.loadClaimAlerts()
      ]);
    } catch (error) {
      console.error('加载数据失败：', error);
      app.showError('加载数据失败');
    } finally {
      this.setData({ loading: false });
    }
  },

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

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

  // 加载理赔警报
  async loadClaimAlerts() {
    try {
      const res = await app.request({
        url: '/insurance/claim-alerts',
        method: 'GET',
        data: { 
          status: 'urgent',
          limit: 5 
        }
      });
      
      this.setData({
        claimAlerts: 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 'policy_approval':
        wx.navigateTo({
          url: `/pages/policy/detail?id=${activity.target_id}`
        });
        break;
      case 'claim_processing':
        wx.navigateTo({
          url: `/pages/claim/detail?id=${activity.target_id}`
        });
        break;
      case 'risk_assessment':
        wx.navigateTo({
          url: `/pages/risk/report?id=${activity.target_id}`
        });
        break;
      case 'compliance_check':
        wx.navigateTo({
          url: `/pages/compliance/report?id=${activity.target_id}`
        });
        break;
      default:
        app.showError('暂不支持查看此类活动详情');
    }
  },

  // 查看理赔警报详情
  onClaimAlertTap(e) {
    const { alert } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/claim/detail?id=${alert.claim_id}`
    });
  },

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

  // 查看所有理赔警报
  onViewAllClaimAlerts() {
    wx.navigateTo({
      url: '/pages/claim/list?status=urgent'
    });
  },

  // 格式化数值
  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);
  },

  // 格式化理赔状态
  formatClaimStatus(status) {
    return app.formatClaimStatus(status);
  }
});