// 引入封装加密包
const aes = require('./utils/aes')
App({

  onLaunch: function(e) {
    var t = this;
    const query = e.query
    const inviter_nickname = query.uuid || ''
    console.log("邀请人id", inviter_nickname)
    wx.setStorageSync('inviter_nickname', inviter_nickname);
    this.globalData.launchOptions = e,
     this.getUserInfo().then(function() {
      console.log(e)
    }).catch(function(e) {
        console.error("获取用户信息失败：", e);
    });
},
  getCurrentTabbar(selected, that) {
    if (typeof that.getTabBar === 'function' &&
      that.getTabBar()) {
      that.getTabBar().setData({
        selected: selected
      })
    }
  },
  onShow() {
    console.log('执行app.jsonShow')
    console.log(1)
  },
  getPopupConfig() {
    return new Promise((resolve, reject) => {
      this.apiRequest({
        url: '/popup-config/', // 后端接口地址
        method: 'POST',
        success: res => {
          console.log(res)
          if (res.data) {
            const { is_enabled, popup_type, content } = res.data.data;

            // 存储到本地缓存
            wx.setStorageSync('popupEnabled', is_enabled);
            wx.setStorageSync('popupType', popup_type);
            wx.setStorageSync('popupContent', content);

            console.log('弹窗配置已成功获取');
            resolve(res.data.data); // 返回获取到的数据
          } else {
            console.warn('弹窗数据获取失败');
            reject(new Error('弹窗数据获取失败'));
          }
        },
        fail: error => {
          console.error('请求失败:', error);
          reject(error);
        }
      });
    });
  },
  广告(){
    wx.navigateTo({
      url: "/pages/details/details",
      success() {
        console.log('跳转成功');
      },
      fail(err) {
        console.error('跳转失败:', err);
      }
    });
  },
  checkUpdateVersion() {
    console.log('检查微信版本是否支持更新机制');
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager();
      updateManager.onCheckForUpdate(function (res) {
        console.log('检查新版本', res);
        if (res.hasUpdate) {
          updateManager.onUpdateReady(function () {
            console.log('新版本下载完成');
            wx.showModal({
              title: '更新提示',
              content: '新版本已准备好，是否重启应用？',
              success: (res) => {
                if (res.confirm) {
                  console.log('用户确认更新');
                  updateManager.applyUpdate();
                }
              }
            });
          });
          updateManager.onUpdateFailed(function () {
            console.log('新版本下载失败');
            wx.showModal({
              title: '已经有新版本了~',
              content: '新版本下载失败，请检查网络设置后重试。',
              showCancel: false,
            });
          });
        } else {
          console.log('当前是最新版本');
        }
      });
    } else {
      wx.showModal({
        title: '温馨提示',
        content: '当前微信版本过低，无法使用自动更新功能，请升级到最新微信版本后重试。',
        showCancel: false,
      });
    }
  },
  /**
   * 登陆并获取用户信息、token
   * @param {*} callback 
   */
  getUserInfo: async function () {
    wx.showLoading({
      title: '正在加载...'
    });
    try {
      let openid = wx.getStorageSync('openid');
      if (!openid) {
        const loginRes = await this.login();
        openid = loginRes.data.userInfo.openid;
        wx.setStorageSync('openid', openid);
        this.globalData.hasUserInfo = true;
      }
      await this.getinfo(); // 调用 getinfo 方法获取用户信息
      wx.hideLoading();
    } catch (error) {
      console.error('操作失败:', error);
      wx.hideLoading();
      throw error; // 将错误向上抛出，让调用者可以捕获
    }
  },

  login: function () {
    return new Promise((resolve, reject) => {
      wx.login({
        success: res => {
          const code = res.code;
          this.apiRequest({
            url: '/myapp/login/',
            method: 'POST',
            data: {
              code,
              data: res.encryptedData,
              iv: res.iv,
              Options: this.globalData.launchOptions
            },
            success: res => resolve(res),
            fail: error => reject(error)
          });
        },
        fail: error => reject(error)
      });
    });
  },

  getinfo: function () {
    return new Promise((resolve, reject) => {
      this.apiRequest({
        url: '/myapp/userinfo/',
        method: 'POST',
        data: {
          'openid': wx.getStorageSync('openid'),
        },
        success: res => {
          console.log('获取信息成功', res);
          this.processUserInfo(res.data.userInfo, res.data.membershipTypeList);
          resolve();
        },
        fail: error => {
          console.error('获取信息失败:', error);
          reject(error);
        }
      });
    });
  },

  processUserInfo: function (userInfo, membershipTypeList) {
    // 更新用户信息到本地存储
    wx.setStorageSync('userId', userInfo.nickname);


    wx.setStorageSync('uuid', userInfo.nickname);
    wx.setStorageSync('openid', userInfo.openid);
    wx.setStorageSync('token', userInfo.token);
    wx.setStorageSync('dailyVideoQuota', userInfo.daily_video_quota);
    wx.setStorageSync('totalParseNum', userInfo.usage_count);
    wx.setStorageSync('defaultDailyFreeParseNum', userInfo.coins);
    wx.setStorageSync('isMember', userInfo.is_member);
    wx.setStorageSync('startTime', userInfo.member_start_time);
    wx.setStorageSync('endTime', userInfo.member_end_time);
    wx.setStorageSync('cards', membershipTypeList);
    wx.setStorageSync('invitees_count', userInfo.invitees_count);
    wx.setStorageSync('balance', userInfo.balance);
    // 检查会员状态
    this.checkMembershipExpiration(userInfo.member_end_time, userInfo.is_member);
  },

  checkMembershipExpiration: function (endTimeStr, isMember) {
    if (endTimeStr && isMember) {
      const currentTimeStamp = Date.now(); // 当前时间戳（毫秒）
      
      // 判断 endTimeStr 是时间戳还是日期字符串
      const endTime = typeof endTimeStr === "number" 
        ? endTimeStr * 1000 // 如果是秒时间戳，转换为毫秒
        : new Date(endTimeStr).getTime(); // 如果是字符串，解析为毫秒
  
      // 验证时间是否有效
      if (isNaN(endTime)) {
        console.error("无效的时间格式:", endTimeStr);
        return;
      }
  
      console.log("当前时间戳（毫秒）:", currentTimeStamp);
      console.log("会员到期时间戳（毫秒）:", endTime);
  
      // 检查会员是否过期
      if (currentTimeStamp > endTime) {
        wx.setStorageSync('isMember', false);
        console.log('会员已过期，更新会员状态');
      }
    }
  },
  

check_status: function() {
  var e = this;
  return new Promise(function(t, n) {
      e.apiRequest({
          url: "/api/check_status/?param=0",
          method: "GET",
          success: function(e) {
              t(e);
          },
          fail: function(e) {
              n(e);
          }
      });
  });
},

  globalData: {
    selected: 0,
    userInfo: null,
    hasUserInfo: false,
    // chatApiDomain: "https://chat.guimiaokeji.com",
    chatApiDomain: "https://chat.guimiaokeji.com",
    apiDomain: 'https://kuaiying.bytefunction.com', //生产
    downloadPrefix: 'https://kuaiying.bytefunction.com/proxy?url=', // 通过代理服务器中转（微信限制资源域名，不同平台cdn域名千变万化）
    defaultDailyFreeParseNum: 0, //免费次数
    totalParseNum: 0, //总次数
    uuid: null,
    isMember: true, // 假设默认为会员
    startTime: null,
    endTime: null,
    launchOptions:null //页面参数
  },
  //chat服务统一调用接口的方法
  chatApiRequest: function (options) {
    const timestamp = Date.now();
    let t = timestamp
    let x = aes.Encrypt(String(timestamp))
    return wx.request({
      url: this.globalData.chatApiDomain + options.url,
      method: options.method ? options.method : 'GET',
      enableChunked: options.enableChunked?options.enableChunked:false,
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token'),
        'Accept': 'application/json',
        'x': x,
        't': t
      },
      dataType: 'json',
      data: options.data,
      success: res => {
        switch (res.statusCode) {
          case 200:
            options.success(res);
            break;
          case 401:
            this.toLogin();
            break;
          case 422:
            break;
          case 404:
            wx.showToast({
              title: '请求地址不存在',
              icon: 'none'
            })
            break;
          default:
            wx.showToast({
              title: res.data.error,
              icon: 'none'
            })
        }
      },
      fail: res => {
        if (options.fail) {
          options.fail(res);
        }
      },
      complete: res => {
        if (options.complete) {
          options.complete(res);
        }
      }
    });
  },
  //全局统一调用接口的方法
  apiRequest: function (options) {
    const timestamp = Date.now();
    let t = timestamp
    let x = aes.Encrypt(String(timestamp))
    wx.request({
      url: this.globalData.apiDomain + options.url,
      method: options.method ? options.method : 'GET',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token'),
        'Accept': 'application/json',
        'x': x,
        't': t
      },
      dataType: 'json',
      data: options.data,
      success: res => {
        switch (res.statusCode) {
          case 200:
            options.success(res);
            break;
          case 401:
            this.toLogin();
            break;
          case 422:
            break;
          case 404:
            wx.showToast({
              title: '请求地址不存在',
              icon: 'none'
            })
            break;
          default:
            wx.showToast({
              title: res.data.message,
              icon: 'none'
            })
        }
      },
      fail: res => {
        if (options.fail) {
          options.fail(res);
        }
      },
      complete: res => {
        if (options.complete) {
          options.complete(res);
        }
      }
    });
  },
  // 上传图片
  uploadFile: function (filePath) {
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: this.globalData.apiDomain + "/myapp/upload_image/", // 上传的服务器接口地址
        filePath: filePath,
        name: 'image_file',
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data)
          } else {
            reject(res)
          }

        },
        fail: (err) => {
          console.error('Upload failed:', err);
          wx.showToast({
            title: '上传错误',
            icon: 'error'
          });
        }
      })
    })
  },

  // 生成视频额度是否为0
  noQuota: function(){
   let dailyVideoQuota = wx.getStorageSync('dailyVideoQuota')
   return dailyVideoQuota < 1
  }
});