// 银行监管小程序
App({
  globalData: {
    userInfo: null,
    token: null,
    apiBase: 'https://api.xlxumu.com',
    version: '1.0.0',
    permissions: []
  },

  onLaunch() {
    console.log('银行监管小程序启动');
    
    // 检查更新
    this.checkForUpdate();
    
    // 初始化用户信息
    this.initUserInfo();
    
    // 设置网络状态监听
    this.setupNetworkListener();
  },

  onShow() {
    console.log('银行监管小程序显示');
  },

  onHide() {
    console.log('银行监管小程序隐藏');
  },

  onError(msg) {
    console.error('小程序错误：', msg);
  },

  // 检查小程序更新
  checkForUpdate() {
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager();
      
      updateManager.onCheckForUpdate((res) => {
        if (res.hasUpdate) {
          console.log('发现新版本');
        }
      });
      
      updateManager.onUpdateReady(() => {
        wx.showModal({
          title: '更新提示',
          content: '新版本已经准备好，是否重启应用？',
          success: (res) => {
            if (res.confirm) {
              updateManager.applyUpdate();
            }
          }
        });
      });
      
      updateManager.onUpdateFailed(() => {
        console.error('新版本下载失败');
      });
    }
  },

  // 初始化用户信息
  initUserInfo() {
    try {
      const token = wx.getStorageSync('token');
      const userInfo = wx.getStorageSync('userInfo');
      const permissions = wx.getStorageSync('permissions') || [];
      
      if (token && userInfo) {
        this.globalData.token = token;
        this.globalData.userInfo = userInfo;
        this.globalData.permissions = permissions;
      }
    } catch (error) {
      console.error('初始化用户信息失败：', error);
    }
  },

  // 设置网络状态监听
  setupNetworkListener() {
    wx.onNetworkStatusChange((res) => {
      if (!res.isConnected) {
        this.showError('网络连接已断开');
      }
    });
  },

  // 微信登录
  async wxLogin() {
    try {
      // 检查登录状态
      const loginRes = await this.checkSession();
      if (loginRes) {
        return this.globalData.userInfo;
      }
    } catch (error) {
      console.log('登录状态已过期，重新登录');
    }

    try {
      // 获取登录code
      const { code } = await this.promisify(wx.login)();
      
      // 获取用户信息
      const userProfile = await this.getUserProfile();
      
      // 发送登录请求
      const response = await this.request({
        url: '/auth/wechat/login',
        method: 'POST',
        data: {
          code,
          encrypted_data: userProfile.encryptedData,
          iv: userProfile.iv,
          app_type: 'bank_supervision'
        }
      });
      
      const { token, user, permissions } = response.data;
      
      // 保存用户信息
      this.globalData.token = token;
      this.globalData.userInfo = user;
      this.globalData.permissions = permissions || [];
      
      wx.setStorageSync('token', token);
      wx.setStorageSync('userInfo', user);
      wx.setStorageSync('permissions', permissions || []);
      
      return user;
      
    } catch (error) {
      console.error('微信登录失败：', error);
      throw error;
    }
  },

  // 检查登录状态
  checkSession() {
    return new Promise((resolve, reject) => {
      wx.checkSession({
        success: () => {
          if (this.globalData.userInfo) {
            resolve(this.globalData.userInfo);
          } else {
            reject(new Error('用户信息不存在'));
          }
        },
        fail: reject
      });
    });
  },

  // 获取用户信息
  getUserProfile() {
    return new Promise((resolve, reject) => {
      wx.getUserProfile({
        desc: '用于完善用户资料',
        success: resolve,
        fail: reject
      });
    });
  },

  // 网络请求封装
  async request(options) {
    const {
      url,
      method = 'GET',
      data = {},
      header = {}
    } = options;

    // 添加认证头
    if (this.globalData.token) {
      header.Authorization = `Bearer ${this.globalData.token}`;
    }

    try {
      const response = await this.promisify(wx.request)({
        url: this.globalData.apiBase + url,
        method,
        data,
        header: {
          'Content-Type': 'application/json',
          ...header
        }
      });

      const { statusCode, data: responseData } = response;

      if (statusCode === 200) {
        if (responseData.code === 0) {
          return responseData;
        } else {
          throw new Error(responseData.message || '请求失败');
        }
      } else if (statusCode === 401) {
        // 登录过期，清除用户信息
        this.clearUserInfo();
        wx.navigateTo({
          url: '/pages/auth/login'
        });
        throw new Error('登录已过期，请重新登录');
      } else if (statusCode === 403) {
        throw new Error('权限不足');
      } else {
        throw new Error(`请求失败：${statusCode}`);
      }
    } catch (error) {
      console.error('请求错误：', error);
      throw error;
    }
  },

  // 清除用户信息
  clearUserInfo() {
    this.globalData.token = null;
    this.globalData.userInfo = null;
    this.globalData.permissions = [];
    wx.removeStorageSync('token');
    wx.removeStorageSync('userInfo');
    wx.removeStorageSync('permissions');
  },

  // 检查权限
  hasPermission(permission) {
    return this.globalData.permissions.includes(permission);
  },

  // 权限检查装饰器
  requirePermission(permission, callback) {
    if (this.hasPermission(permission)) {
      callback();
    } else {
      this.showError('权限不足，请联系管理员');
    }
  },

  // Promise化微信API
  promisify(fn) {
    return (options = {}) => {
      return new Promise((resolve, reject) => {
        fn({
          ...options,
          success: resolve,
          fail: reject
        });
      });
    };
  },

  // 显示加载提示
  showLoading(title = '加载中...') {
    wx.showLoading({
      title,
      mask: true
    });
  },

  // 隐藏加载提示
  hideLoading() {
    wx.hideLoading();
  },

  // 显示成功提示
  showSuccess(title) {
    wx.showToast({
      title,
      icon: 'success',
      duration: 2000
    });
  },

  // 显示错误提示
  showError(title) {
    wx.showToast({
      title,
      icon: 'none',
      duration: 3000
    });
  },

  // 显示确认对话框
  showConfirm(options) {
    return new Promise((resolve) => {
      wx.showModal({
        title: options.title || '提示',
        content: options.content,
        confirmText: options.confirmText || '确定',
        cancelText: options.cancelText || '取消',
        success: (res) => {
          resolve(res.confirm);
        }
      });
    });
  },

  // 格式化金额
  formatMoney(amount) {
    if (!amount) return '¥0.00';
    return `¥${parseFloat(amount).toLocaleString()}`;
  },

  // 格式化时间
  formatTime(timestamp) {
    const date = new Date(timestamp);
    return date.toLocaleString();
  },

  // 格式化日期
  formatDate(timestamp) {
    const date = new Date(timestamp);
    return date.toLocaleDateString();
  },

  // 格式化风险等级
  formatRiskLevel(level) {
    const riskMap = {
      'low': { text: '低风险', color: '#28a745' },
      'medium': { text: '中风险', color: '#ffc107' },
      'high': { text: '高风险', color: '#dc3545' },
      'critical': { text: '极高风险', color: '#6f42c1' }
    };
    return riskMap[level] || { text: '未知', color: '#6c757d' };
  },

  // 格式化审批状态
  formatApprovalStatus(status) {
    const statusMap = {
      'pending': { text: '待审批', color: '#ffc107' },
      'approved': { text: '已批准', color: '#28a745' },
      'rejected': { text: '已拒绝', color: '#dc3545' },
      'cancelled': { text: '已取消', color: '#6c757d' }
    };
    return statusMap[status] || { text: '未知', color: '#6c757d' };
  }
});