//app.js

const ald = require('./utils/ald-stat.js')
var xmad = require('./utils/dsp_sdk.js')

App({
  onLaunch: function() {
    this.getOpenId()
    let token = wx.getStorageSync("token");
    if (token != '') {
      this.getrecord()
    }
   

    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    //自动更新版本
    const updateManager = wx.getUpdateManager()
    updateManager.onCheckForUpdate(function(res) {
      // 请求完新版本信息的回调
    })

    updateManager.onUpdateReady(function() {
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好,是否重启应用?',
        success: function(res) {
          if (res.confirm) {
            // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })
    })
    updateManager.onUpdateFailed(function() {
      // 新的版本下载失败
      wx.showModal({
        title: '更新提示',
        content: '新版本下载失败',
        showCancel: false
      })
    })
  },

  getOpenId() {
    console.log('我是openid')
    let that = this
    wx.login({
      success: (res) => {
        console.log(res)
        let url = 'wxapp/public/getSessionKey'
        let param = {
          code: res.code,
        }
        let header = {
          'content-type': 'application/x-www-form-urlencoded'

        }
        wx.request({
          url: 'https://yxjingying.com/api/wxapp/public/getSessionKey',
          data: param,
          method: 'POST',
          header: header,

          success: function(res) { //返回取得的数据
            console.log(res)
            console.log(res.data.data.openid)
            wx.setStorageSync('openid', res.data.data.openid);
            let openid = wx.getStorageSync("openid");

            wx.dsp.setOpenid(openid)


            // else if (res.data.code == '42002') {

            // } 
            // setTimeout(function () {

            //   wx.hideNavigationBarLoading()
            // }, 600)
          },

          complete: function() {
            wx.hideNavigationBarLoading()
          },
          fail: function(e) {
            reject('网络出错');
            // wx.hideLoading()
            wx.hideNavigationBarLoading()
          }
        })

        // app.post(url, param).then((res) => {
        //   console.log(res)
        //   that.setData({
        //     openid: res.data.openid,
        //     session_key: res.data.session_key
        //   })

        //   wx.setStorageSync("openid", res.data.openid)

        //   // this.isregister()
        //   wx.getSetting({
        //     success: res => {
        //       if (res.authSetting['scope.userInfo'] === true) {
        //         wx.getUserInfo({
        //           success: reg => {
        //             that.setData({
        //               encrypted_data: reg.encryptedData,
        //               iv: reg.iv
        //             })
        //             // 获取完后自动执行login 然后跳转至设置的url
        //             // that.login()
        //           },
        //           fail(res) {
        //             console.log(res)
        //           }
        //         })
        //       }

        //     }
        //   })

        // }).catch((errMsg) => {
        // })


      }
    });
  },

  onshow() {
    
  

  },
  post: function(url, data, headerParams, showLoad) {
    wx.showNavigationBarLoading()
    var promise = new Promise((resolve, reject) => {
      //init
      let that = this;
      let postData = data;
      let baseUrl = 'https://yxjingying.com/api/';
      //网络请求
      let header = {
        'content-type': 'application/x-www-form-urlencoded'

      }
      header = Object.assign(header, headerParams)
      //网络请求  
      wx.request({
        url: baseUrl + url,
        data: postData,
        method: 'POST',
        header: header,

        success: function(res) { //返回取得的数据
          if (res.data.code == '20000') {
            resolve(res.data);
          } else if (res.data.code == '201') {
            resolve(res.data);
          } else {
            console.log(res)
            reject(res)
            if (res.data.msg == "请完善简历") {
              wx.showToast({
                title: res.data.msg,
                icon: 'none'
              })

              setTimeout(function() {
                wx.switchTab({
                  url: '/pages/index/index',
                })
              }, 1500)
              wx.setStorageSync('toisresume', 1)
            }
          }

          // else if (res.data.code == '42002') {

          // } 
          // setTimeout(function () {

          //   wx.hideNavigationBarLoading()
          // }, 600)
        },

        complete: function() {
          wx.hideNavigationBarLoading()
        },
        fail: function(e) {
          reject('网络出错');
          // wx.hideLoading()
          wx.hideNavigationBarLoading()
        }
      })
    });
    return promise;
  },

  // 获取用户记录
  getrecord() {
    let that = this;
    var url = 'index/user/visit';
    var params = {


    }
    var header = {
      'XX-Token': wx.getStorageSync('token'),
      "XX-Device-Type": 'wxapp'
    }
    that.post(url, params, header).then((res) => {
      console.log('88990', res);



    }).catch((err) => {

    })

  },

  upload(filetype, file) {

    var promise = new Promise((resolve, reject) => {
      wx.showNavigationBarLoading()
      wx.showLoading({
        title: '上传中',
      })
      let url = 'https://yxjingying.com/api/user/upload/one';
      let head = {
        'XX-Token': wx.getStorageSync('token'),
        'XX-Device-Type': ''
      }
      let typename = {
        filetype: filetype
      }
      wx.uploadFile({
        url: url, //仅为示例,非真实的接口地址
        filePath: file,
        name: 'file',
        header: head,
        formData: typename,
        success: function(res) {
          console.log('上传文件后', res)
          let temdata = JSON.parse(res.data);
          console.log(temdata)
          let urlobj = {
            url: temdata.data.url
            //url: temdata.data.filepath
          }
          resolve(urlobj);
          wx.hideNavigationBarLoading();
          wx.hideLoading();
        },
        fail: function(res) {
          reject('网络出错');
          wx.hideNavigationBarLoading()
          wx.hideLoading()
        },
        complete: () => {
          wx.hideNavigationBarLoading()
          wx.hideLoading()
        },
      })
    });
    return promise;
  },

  // pay(res, successData) {
  //   wx.requestPayment({
  //     "timeStamp": res.pay.timeStamp,
  //     "nonceStr": res.pay.nonceStr,
  //     "package": res.pay.package,
  //     "signType": "MD5",
  //     "paySign": res.pay.paySign,
  //     "success": function (res) {
  //       wx.showToast({
  //         title: '支付完成',
  //         icon: "success",
  //         duration: 1500,
  //         success: function (data) {
  //           successData(data)
  //         }
  //       })
  //     },
  //     "fail": function (res) {
  //       wx.showToast({
  //         title: '取消支付成功!',
  //         icon: "icon",
  //         duration: 1500,
  //       })
  //     }
  //   })
  // },
  // nowDate() {
  //   let date = new Date();
  //   let month = date.getMonth() + 1;
  //   let day = date.getDate();
  //   return date.getFullYear() + '-' + (month > 9 ? month : ('0' + month)) + '-' + (day > 9 ? day : ('0' + day));
  // },
  // minDate() {
  //   let date = new Date();
  //   date.setDate(date.getDate() - 287);
  //   let m = date.getMonth() + 1;
  //   return date.getFullYear() + '-' + m + '-' + date.getDate();
  // },
  // timeFormate(timestamp, timeType) {
  //   var timeStamp = timestamp.length == 13 ? timestamp : timestamp * 1000
  //   var date = new Date(timeStamp); //时间戳为10位需*1000,时间戳为13位的话不需乘1000
  //   var Y = date.getFullYear() + '-';
  //   var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
  //   var D = date.getDate() + ' ';
  //   var h = date.getHours() + ':';
  //   var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
  //   var s = date.getSeconds();
  //   if (timeType == 'YYMMDD') {
  //     return Y + M + D;
  //   } else {
  //     return h + m;
  //   }
  // },

  nowDate() {
    let date = new Date();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    return date.getFullYear() + '年' + (month > 9 ? month : ('0' + month)) + '月' + (day > 9 ? day : ('0' + day)) + '日';
  },

  newnowDate() {
    let date = new Date();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    return date.getFullYear() + '-' + (month > 9 ? month : ('0' + month)) + '-' + (day > 9 ? day : ('0' + day));
  },

  // 接口管理
  interface: {
    // historyDelete: '/home/index/historyDelete',//删除
    // shopClass: '/home/index/shopClass',//分类
    // shopPage: '/home/index/shopPage',//分页
    // history: '/home/index/history',//检索
    // index: '/home/index/index', //首页
    // login: '/wxapp/public/login', //小程序登录注册
    getSessionKey: '/wxapp/public/getSessionKey', //获取sessionKey和openid
  },
  //全局变量
  globalData: {
    userInfo: null,
    cid: null,
    class_id: null
  }
})