const app = getApp()
import request from '../../utils/request'
import { timestampToTime } from '../../utils/util'

Page({
  data: {
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canIUseGetUserProfile: false,
    canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName'),
    isPhone: false,
    isDevMode: false,
    devMode: '开发者模式',
    holdingSwitch: false,
    logoActive: false,
    timer: null,
    touchFlag: "",
    isNotRead: true,
    noticeText: ''
  },
  // 事件处理函数
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs',
    })
  },
  onLoad(option) {
    if (option.checkUserInfo) {
      this.checkUserInfo()
    }
    const that = this
    if (!this.data.checkUserInfo) {
      app.userInfoCallback = res => {
        console.log(res, 'userInfoCallback')
        that.setData({
          userInfo: res.data,
          isPhone: that.data.userInfo.phone ? true : false
        })
        if (app.globalData.noticeText) {
          that.setData({
            noticeText: app.globalData.noticeText
          })
        }
      }
    }
  },

  onShow() {
    if (!this.data.checkUserInfo) {
      this.getNoticeText()
    }
  },

  getUserProfile() {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res, 'getUserProfile')
      }
    })
  },

  agreedClick() {
    this.setData({
      isNotRead: !this.data.isNotRead
    })
  },

  // 跳转至用户协议页面
  checkUserProtocol() {
    wx.navigateTo({
      url: '/pages/userProtocol/userProtocol',
    })
  },

  // 跳转至联系我们页面
  goToProductDetail() {
    wx.navigateTo({
      url: '/pages/ContactUs/ContactUs',
    })
  },

  // 跳转至购买历史页面
  checkPayHistory() {
    wx.navigateTo({
      url: '/pages/payHistory/payHistory',
    })
  },

  getUserPhone(e) {
    const sessionKey = wx.getStorageSync('sessionKey')
    this.doGetUserPhone(e.detail.encryptedData, e.detail.iv, sessionKey, request.appId)
  },

  /** 获取手机号授权 */
  doGetUserPhone(encryptedData, iv, sessionKey, appId) {
    request.post({
      url: '/api/user/getUserPhone',
      data: {
        encryptedData,
        iv,
        sessionKey,
        appId
      }
    }).then(res => {
      console.log(res, 'getUserPhone');
      wx.showToast({
        title: '申请成功！',
        icon: 'success'
      })
      this.checkUserInfo()
    }).catch(err => {
      console.log(err, 'err');
    })
  },

  // 购买会员
  goToBuy() {
    const userInfo = JSON.stringify(this.data.userInfo)
    wx.navigateTo({
      url: `/pages/payOrder/payOrder?userInfo=${userInfo}`,
    })
  },

  goToChat() {
    wx.navigateTo({
      url: '/pages/chat/chat',
    })
  },

  checkCheatCode(e) {
    const flag = e.currentTarget.dataset.flag
    const touchFlag = this.data.touchFlag
    /** 更改data中touchFlag的数据 */
    const setTouchFlag = touchFlag => {
      this.setData({
        touchFlag: touchFlag,
        isDevMode: false,
        holdingSwitch: false,
        logoActive: false,
        timer: null,
      })
    }
    // topLeft => bottomRight => topRight => bottomLeft
    if (flag == "topLeft") {
      setTouchFlag('topLeft')
    } else if (flag == "bottomRight") {
      if (touchFlag == 'topLeft') {
        setTouchFlag('bottomRight')
      } else {
        setTouchFlag('')
      }
    } else if (flag == "topRight") {
      if (touchFlag == 'bottomRight') {
        setTouchFlag('topRight')
      } else {
        setTouchFlag('')
      }
    } else if (flag == "bottomLeft") {
      if (touchFlag == 'topRight') {
        this.setData({
          holdingSwitch: true
        })
      } else {
        setTouchFlag('')
      }
    }
  },

  iconTouchStart() {
    if (!this.data.holdingSwitch) return
    const that = this
    that.setData({
      timer: setTimeout(() => {
        that.setData({
          logoActive: true,
          noticeText: '𝙒𝙚𝙡𝙘𝙤𝙢𝙚 𝘿𝙚𝙫𝙚𝙡𝙤𝙥𝙚𝙧 𝙔𝙒𝙌 !'
        })
        wx.showToast({
          title: 'Developer Mode',
          icon: 'success'
        })
      }, 7000)
    })
  },

  iconTouchEnd() {
    clearTimeout(this.data.timer)
  },

  checkCheatCodeStatus() {
    if (this.data.logoActive) {
      this.setData({
        isDevMode: true
      })
    }
  },

  apply() {
    request.get({
      url: '/api/user/apply'
    }).then(res => {
      console.log(res, 'apply');
      wx.showToast({
        title: '申请成功！',
        icon: 'success'
      })
      this.checkUserInfo()
    }).catch(err => {
      console.log(err, 'err');
    })
  },

  /**
  * @description 检查用户信息
  * @returns userInfo
  */
  checkUserInfo() {
    request.get({
      url: '/api/user/userinfo'
    }).then(res => {
      console.log(res, 'userinfo');
      res.data.createDate = res.data.createDate ? timestampToTime(res.data.createDate, 'YYYY-MM-DD hh:mm:ss') : ''
      res.data.updateDate = res.data.updateDate ? timestampToTime(res.data.updateDate, 'YYYY-MM-DD hh:mm:ss') : ''
      res.data.validStartTime = res.data.validStartTime ? timestampToTime(res.data.validStartTime, 'YYYY-MM-DD hh:mm:ss') : ''
      res.data.validEndTime = res.data.validEndTime ? timestampToTime(res.data.validEndTime, 'YYYY-MM-DD hh:mm:ss') : ''
      res.data.coverPhone = res.data.phone ? (res.data.phone.slice(0, 3) + `****` + res.data.phone.slice(7)) : ''
      this.setData({
        userInfo: res.data,
        isPhone: res.data.phone ? true : false
      })
    }).catch(err => {
      console.log(err, 'err');
    })
  },

  /**
 * @description 获取通知栏信息文本
 * @returns list
 */
  getNoticeText() {
    const that = this
    request.get({
      url: '/api/notice/list'
    }).then(res => {
      console.log(res, 'getNoticeText');
      let noticeText = ''
      res.data.forEach((item, index) => {
        noticeText += index + 1 + '、' + item.content + '          '
      })
      app.globalData.noticeText = noticeText
      that.setData({
        noticeText: noticeText
      })
      // 检查用户信息
      that.checkUserInfo()
    }).catch(err => {
      console.log(err, 'err');
    })
  },

  onShareAppMessage() {
    const promise = new Promise(resolve => {
      setTimeout(() => {
        resolve({
          title: '小闲聊'
        })
      }, 500)
    })
    return {
      title: '小闲聊',
      promise
    }
  },
  onShareTimeline() {
    const promise = new Promise(resolve => {
      setTimeout(() => {
        resolve({
          title: '小闲聊'
        })
      }, 500)
    })
    return {
      title: '小闲聊',
      promise
    }
  }
})
