App({
  onLaunch: function (options) {
    if (options.query) {
      console.log('扫码加载')
      var code1 = decodeURIComponent(options.query.qrCode)
      var index = code1.lastIndexOf("\=");
      let code = code1.substring(index + 1, code1.length);
      this.globalData.scanCode = code
      console.log(code, 'ceode-------------------------------------')
    }


    if (my.canIUse('getUpdateManager')) {
      const updateManager = my.getUpdateManager()
      updateManager.onCheckForUpdate(function (res) {
        if (res.hasUpdate) {
          updateManager.onUpdateReady(function () {
            my.alert({
              title: '更新提示',
              content: '新版本已经准备好，是否重启应用？',
              success: function (res) {

                updateManager.applyUpdate()

              }
            })
          })
          updateManager.onUpdateFailed(function () {
            my.alert({
              title: '已经有新版本了哟~',
              content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~'
            })
          })
        }
      })
    } else {
      my.alert({
        title: '提示',
        content: '当前支付宝版本过低，无法使用该功能，请升级到最新支付宝版本后重试。'
      })
    }
    console.log(my.getStorageSync({ 'key': 'token' }).data, 'XXXXXXXXXXXXXXXXXXXXX')

  },
  globalData: {
    statusBarHeight: my.getSystemInfoSync()['statusBarHeight'],
    windowHeight: my.getSystemInfoSync()['windowHeight'],
    imgUrl: 'http://resource.bike.hanyiyun.com/',
    screenHeight: '',
    login: false,
    scanCode: '',//扫描普通二维码跳转小程序解析出的车牌号码
    platform: '',
    version: '',
    req: true,
    id: 0,
    times: 60,
    invalid: false,

    // title: '禹见你', //全局修改此小程序名称
    // company:'禹州市途娱科技有限公司',
    // company_1:'途娱科技',
    // scanLength: 9,//车辆编码数
    // compatible: '',
    // title: '禹见你', //全局修改此小程序名称
    // logoUrl: '../../img/logo.png', //logo图片路径 网络图片/本地图片 dejin.png  shanxianLg.png  yuzhouLg.png dingding.png
    // appid: '2021002147603404', //小程序的appid wxc5f328a92356183f--遇见你appid
    // merchant_id: '1',
    // url: 'https://api.mtu.ximengnaikang.com/api', //线上域名
    // mapKey: 'GTLBZ-F6BKO-5EDWH-SDHIX-K2ART-O2FRQ' //地图key值

    
    // appName:'mtu',
    // isOnlineKefu:false,//是否使用在线客服
    // title: '禹见你', //全局修改此小程序名称
    // company:'禹州市途娱科技有限公司',
    // company_1:'途娱科技',
    // scanLength: 9, //车辆编码位数  跶跶出行为11位 沃骑、禹见你9位
    // logoUrl: '../../img/logo.png', //禹见你
    // appid: '2021002147603404', //禹见你
    // url: 'https://api.mtu.ximengnaikang.com/api', //禹见你
    // mapKey: 'GTLBZ-F6BKO-5EDWH-SDHIX-K2ART-O2FRQ', //禹见你
    // merchant_id: 1, //商户id
    // imgUrl: 'http://resource.mtu.ximengnaikang.com/',
    // videoUrl:'https://resource.mtu.ximengnaikang.com'

    appName:'tkcx',
    isUseTK:true,// 是否使用头盔
    isOnlineKefu:false,//是否使用在线客服
    title: '太康共享出行', //全局修改此小程序名称
    company:'太康县速柯行科技有限公司',
    company_1:'太康科技',
    scanLength: 9, //车辆编码位数  跶跶出行为11位 沃骑、禹见你9位
    logoUrl: '../../img/tkcx.png', //太康共享出行
    appid: '2021004144649616', //太康共享出行
    url: 'https://api.yjtk.ximengnaikang.com/api', //太康共享出行
    mapKey: 'GWTBZ-3B7HN-XYVFI-SNRHK-HF2F5-2WBB2', //太康共享出行
    merchant_id: 1, //商户id
    imgUrl: 'http://resource.mtu.ximengnaikang.com/',
    videoUrl:'https://resource.mtu.ximengnaikang.com'
  },
  request(api, params, method, req1) {
    var that = this;
    // if (req1 == false) return;
    // if (req1) {
    //   that.globalData.req = false;
    // }
    // if (my.getStorageSync({ 'key': 'token' }).data != '' || my.getStorageSync({ 'key': 'token' }).data != undefined) {
    //   if (req1 == true || req1 == undefined) {
    return new Promise((resolve, reject) => {
      my.request({
        url: this.globalData.url + api,
        data: params,
        headers: {
          'content-type': 'application/json',
          'Accept': 'application/json',
          'Cache-Control': 'no-cache',
          'Authorization': my.getStorageSync({ 'key': 'token' }).data,
          'merchant-id': this.globalData.merchant_id,
          'source-type': 'alipay'
        },
        method: method,
        success: (res) => {
          // console.log(res)
          if (res.status == 450) {
            return;
          }
          if (res.status != 200) {
            let data = {
              response: res,
              'url': api,
              'data': params,
              'merchant-id': this.globalData.merchant_id,
              'authorization':my.getStorageSync({ 'key': 'token' }).data,
              type: 'success',
              user: my.getStorageSync({ 'key': 'userInfo' }).data ? my.getStorageSync({ 'key': 'userInfo' }).data.user : '',
              version: '1.2.2'
            }
            my.request({
              url: this.globalData.url + '/logs', //仅为示例，并非真实的接口地址
              data: { data: data },
              method: 'POST',
              header: {
                'content-type': 'application/json', // 默认值
                'merchant-id': this.globalData.merchant_id
              },
              success(res) {
                console.log(res.data)
              }
            })
          }
          if (res.status != 200) {
            if (res.data.message == '订单不存在或订单已结算') {
              if (this.globalData.compatible) {
                my.reLaunch({
                  url: '/pages/compatible/index/index',
                })
              } else {
                my.reLaunch({
                  url: '/pages/index/index',
                })
              }
              return false;
            } else if (res.data.message == '运动中不能关锁') {
              return false;
            }
            if (res.message != undefined) {
              my.showToast({
                content: res.message,
                icon: 'none',
                duration: 3000,
                mask: true
              })
            } else if (res.data.message != undefined) {
              my.showToast({
                content: res.data.message,
                icon: 'none',
                duration: 3000,
                mask: true
              })
            }
          }

          console.log(res, 'token-------------------------------------------')
          resolve(res)
        },
        fail: (err) => {

          if (err.status == 401) {
            var timeout;
            console.log('token过期')

            my.removeStorageSync({ key: 'token' })
            my.removeStorageSync({ key: 'token_time' })
            // this.token()
            my.reLaunch({
              url: '/pages/index/index',
            })
          } else if (err.status == 404) {
            my.navigateTo({
              url: '/pages/undefind/undefind',
            })
          } else {
            my.showToast({
              content: err.data.message || err.data,
              icon: 'none',
              mask: true,
              duration: 3000,
            });
          }
          console.log(err, 'qingqiushibai')
          let data = {
            response: res,
            'url': api,
            'data': params,
            'merchant-id': this.globalData.merchant_id,
            'authorization': my.getStorageSync({'key':'token'}).data,
            type: 'success',
            user: my.getStorageSync({ 'key': 'userInfo' }).data ? my.getStorageSync({ 'key': 'userInfo' }).data.user : '',
            version: '1.2.2'
          }
          my.request({
            url: this.globalData.url + '/logs', //仅为示例，并非真实的接口地址
            data: { data: data },
            method: 'POST',
            header: {
              'content-type': 'application/json', // 默认值
              'merchant-id': this.globalData.merchant_id
            },
            success(res) {
              console.log(res.data)
            }
          })
          reject(err, "请求失败")
        },
        complete: () => {
          that.globalData.req = true
        }
      })
    })
  },

  login() {
    let that = this
    let token = my.getStorageSync({ 'key': 'token' }).data
    let data = Math.round(new Date().getTime() / 1000).toString();
    let tokenTime = my.getStorageSync({ 'key': 'token_time' }).data || 0;
    let cha = data - tokenTime
    let data1 = 60 * 60 * 4
    return new Promise((resolve, reject) => {
      if (token && cha < data1) {
        console.log(Math.round(new Date() / 1000), 'test--------')
        return resolve();

      } else {
        my.getAuthCode({
          success: (res) => {
            // 发送 res.code 到后台换取 openId, sessionKey, unionId
            if (res.authCode) {
              console.log(res.authCode)
              var data = {
                'code': res.authCode,
                'appid': that.globalData.appid,
                'type': 1
              };
              my.request({
                url: that.globalData.url + '/auth/weapp-login',
                data: data,
                headers: {
                  'content-type': 'application/json',
                  'Accept': 'application/json',
                  'Cache-Control': 'no-cache',
                  // 'Authorization': my.getStorageSync({ 'key': 'token' }).data,
                  'merchant-id': that.globalData.merchant_id,
                  'source-type': 'alipay'
                },
                method: 'POST',
                success: (res) => {
                  console.log(res, 'token')
                  if (res.status == 401) {
                    my.showToast({
                      content: '登陆失败,请重新登录',
                      icon: 'none'
                    })
                    setTimeout(function () {
                      my.reLaunch({
                        url: '/pages/authorization/authorization',
                      })
                    }, 1000)
                  } else if (res.status != 200) {
                    console.log(res, 'cesgu---------------')
                    my.showToast({
                      content: res.data.message,
                      icon: 'none'
                    })
                  } else {
                    my.setStorageSync({ 'key': 'token', data: res.data.token });
                    my.setStorageSync({ 'key': 'session_key', data: res.data.session_key });
                    my.setStorageSync({ 'key': 'token_time', data: res.data.exp });
                    my.setStorageSync({ 'key': 'user_ID', data: res.data.user.id });
                  }

                  resolve()
                }, fail: (err) => {
                  my.alert({
                    title: '提示',
                    content: '可能网络不太好，请重试！',
                    success: () => {
                      my.reLaunch({
                        url: '/pages/error/error?error=0'
                      });
                    }
                  })
                 
                }
              })
            } else {
              my.showToast({
                content: res.errMsg,
                icon: none,
              })
            }
          }
        })
      }
    })
  },
})
