// app.ts
import { userInfo, login } from './apis/login'
import { getOpenId } from './apis/open'
import { pay } from './apis/pay'
import { querystrToObj } from './utils/util'
import { bindPhoneList } from "./apis/consumer";
App<IAppOption>({
  globalData: {},
  onLaunch() {
    const res = wx.getMenuButtonBoundingClientRect()
    wx.setStorageSync('MenuButtonBoundingClientRect', res)
    // 展示本地存储能力
    const logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // const token = wx.getStorageSync('Authorization')
    // if (!token) {
    //   wx.reLaunch({
    //     url: '/pages/login/login'
    //   })
    // }
    // return
    // 登录
    this.login().then(() => {
      this.globalData.ready = true
      this.reload()
    }).catch(() => {
      this.globalData.ready = true
    })
    /*
    wx.login({
      success: res => {
        console.log(res.code)
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        getOpenId({
          field: res.code
        }).then((res:any) => {
          this.globalData.openId = res.d.openId
          login({
            openId: res.d.openId,
            staffType: 'WECHAT'
          }).then((res:any) => {
            wx.setStorageSync('Authorization', res.d)
            this.getUserInfo().then(() => {
              this.globalData.ready = true
              this.reload()
            })
          }).catch(() => {
            this.globalData.ready = true
            wx.reLaunch({
              url: '/pages/login/login'
            })
          })
        })
      },
    })
    */
  },
  onShow(options) {
    console.log('appShow', options)
    const { path, query } = options
    let { q, source } = query
    if (['pages/apply/apply', 'pages/reportPreview/reportPreview', 'pages/scanLogin/scanLogin'].includes(path)) {
      let pageQueryStr = ''
      if (q) {
        q = decodeURIComponent(q)
        const queryStr = q.split('?')[1]
        const queryObj = querystrToObj(decodeURIComponent(querystrToObj(queryStr).query))
        pageQueryStr = decodeURIComponent(querystrToObj(queryStr).query)
        source = queryObj.source
      }
      const backPage = `/${path}?${pageQueryStr}`
      console.log(backPage)
      wx.setStorageSync('QSource', source)
      wx.setStorageSync('backPage', backPage)
    } else {
      wx.removeStorageSync('QSource')
      wx.removeStorageSync('backPage')
    }
  },
  // 登录
  login() {
    console.log('login,app.ts');

    return new Promise((resolve, reject) => {
      wx.login({
        success: res => {
          console.log(res.code)
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          getOpenId({
            field: res.code
          }).then((res: any) => {
            this.globalData.openId = res.d.openId
            this.globalData.unionId = res.d.unionId
            login({
              openId: res.d.openId,
              // ...res.d,
              loginType: 1
            }).then((res: any) => {
              wx.setStorageSync('Authorization', res.d)
              // this.getBindPhoneList()
              
              resolve(true)
              console.log('resolve');
              bindPhoneList().then(res => {
                console.log('##2##',res);
                wx.setStorageSync('accountList', res.d)
                wx.setStorageSync('userInfo', res.d.find(item => item.phone === wx.getStorageSync('userInfo').phone) || res.d[0])
              })
              // this.getUserInfo().then(() => {
              //   resolve(true)
              //   this.getBindPhoneList()
              // }).catch((err: any) => {
              //   reject(err)
              // })
            }).catch((err) => {
              // this.globalData.ready = true
              // wx.reLaunch({
              //   url: '/pages/login/login'
              // })
              reject(err)
            })
          }).catch((err) => {
            reject(err)
          })
        },
      })
    })
  },
  // getBindPhoneList() {
  //   bindPhoneList().then(res => {
  //     // console.log(res);
  //     wx.setStorageSync('accountList', res.d)
  //   })
  // },
  // 获取用户信息, 在登录或开通会员等 用户信息改变时调用
  getUserInfo() {
    return userInfo({}).then((res: any) => {
      this.globalData.userInfo = res.d
      return res.d
    })
  },
  // 页面重载
  reload() {
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    currentPage.onLoad(currentPage.options)
    currentPage.onShow()
  },
  /**
   * 实名认证校验
   * @param skip 是否跳转到实名页面
   * @returns 
   */
  certificationVerify(skip = false): boolean {
    const status = this.globalData.userInfo?.status
    let val = false
    if (Number(status) >= 3) val = true
    if (skip && !val) {
      wx.navigateTo({
        url: '/pages/certification/certification'
      })
    }
    return val
  },
  
  /**
   * 会员校验
   * @param skip 是否跳转到购买会员页面
   * @returns 
   */
  memberVerify(skip = false): boolean {
    const status = this.globalData.userInfo?.status
    let val = false
    if (Number(status) === 4) val = true
    if (skip && !val) {
      wx.navigateTo({
        url: '/pages/member/member'
      })
    }
    return val
  },
  /**
   * 发起支付
   * @param payType 
   * @returns 
   */
  pay(payType: String) {
    return new Promise((resolve, reject) => {
      pay({
        payType,
        wxPayApiType: 'JSAPI'
      }).then((res: any) => {
        wx.requestPayment({
          ...res.d,
          success: (res: any) => {
            resolve(res)
          },
          fail: (err: any) => {
            wx.showToast({
              icon: 'none',
              title: '支付失败, 请稍后再试!'
            })
            reject(err)
          }
        })
      })
    })
  }
})