// parents/pages/me/me.js
import { routers, viewImage, sharePage, isFn, getGlobalVal } from '../../../utils/util.js'
import { GetMineInfo, CheckRole} from '../../../utils/api.js'
const { navigateTo, redirectTo, navigateBack } = routers()
const { globalData, hasLibraryService, hasVipService, saveUserInfo, getWxloginCode} = getApp()
const { baseImgUrl, qrcodeInvalidToastText, isIphoneX, noVipListToastText} = globalData
Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseImgUrl,
    isLoaded: 0,
    isShowVipModal: 0,
    canIUseGetUserInfo: wx.canIUse('button.open-type.getUserInfo'),
    routerOne: [
      {
        icon: '../../../assets/vip.png',
        text: '会员服务',
        time: '',
        paras: {},
        url: '',
        zindex: 3
      },
    ],
    routerTwo: [
      {
        icon: '../../../assets/personal_info.png',
        text: '个人资料',
        time: '',
        paras: {
          type: 1
        },
        url: 'parents/pages/information/information',
        zindex: 3
      },
      {
        icon: '../../../assets/apply_pages.png',
        text: '申请书单记录',
        time: '',
        paras: {},
        url: 'parents/pages/apply_bookLists/apply_bookLists',
        zindex: 3
      },
      // {
      //   icon: '../../../assets/qiehuan_icon.png',
      //   text: '角色切换',
      //   time: '',
      //   paras: {},
      //   url: '',
      //   zindex: 3
      // },
      // {
      //   icon: '../../../assets/problem_icon.png',
      //   text: '常见问题',
      //   time: '',
      //   paras: {},
      //   url: 'pages/question/question',
      //   zindex: 3
      // },
      {
        icon: '../../../assets/aijia_icon.png',
        text: '关于私塾家',
        time: '',
        paras: {},
        url: 'pages/about_aijia/about_aijia',
        zindex: 3
      },
    ],
    routerThree: [
      {
        icon: '../../../assets/aijia_icon.png',
        text: '关于私塾家',
        time: '',
        paras: {
          type: 1
        },
        url: 'pages/about_aijia/about_aijia',
        zindex: 3
      },
    ],
    roleList: [],
    footerData: {
      isIphoneX,
      actIndex: 2,
      list: [
        {
          text: '找好书',
          icon: '../../../assets/book_gray.png',
          actIcon: '../../../assets/book_blue.png',
          url: 'parents/pages/main/main',
          zindex: 3,
        },
        {
          text: '好书推荐',
          icon: '../../../assets/wish_gray.png',
          actIcon: '../../../assets/wish_blue.png',
          url: 'parents/pages/growth_track/growth_track',
          zindex: 3,
        },
        {
          text: '我的',
          icon: '../../../assets/me_gray.png',
          actIcon: '../../../assets/me_blue.png',
          url: 'parents/pages/me/me',
          zindex: 3,
        }
      ]
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const userId = getGlobalVal('userId')
    options.library = getGlobalVal('library')
    options.vipList = getGlobalVal('vipList', `vipList_${userId}`)
    options.vipIndex = getGlobalVal('vipIndex', `vipIndex_${userId}`)
    options.vipId = getGlobalVal('vipId', `vipId_${userId}`)
    options.vip = getGlobalVal('vip', `vip_${userId}`)
    options.userId = userId
    options.userInfo = getGlobalVal('userInfo')
    console.log(options)
    this.setData({ options, isLoaded: 1 })
    getWxloginCode(code => {
      this.setData({ code })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    const obj = { navigateTo, redirectTo, navigateBack, viewImage }
    for (const i in obj) {
      this[i] = obj[i]
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // wx.hideHomeButton() 
    this.getVipList()
    this.getCheckRole()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  /**
    * 选择角色
   */
  pickerRoleCtl:function(e){
    const {value}=e.detail
    const {list=[]}=this.data;
    if (list[value].type==0){
      redirectTo({ url: 'parents/pages/me/me', paras: {} })
    }else{
      wx.setStorageSync('list', [list[value]])
      redirectTo({ url: 'president/pages/home/home', paras: { libId: list[value].libId } })
    }
  },
  /**
    * 获取角色列表
   */
  getCheckRole: function () {
    const continuousFn = { fn: this.getCheckRole, param: { ...arguments } }
    CheckRole({ continuousFn }).then(res => {
      const { list = null } = res.data
      const data = (res => {
        const arr = []
        for (const i in res) {
          arr.push(res[i].msg)
        }
        return arr
      })(list)
      this.setData({ roleList:data,list })
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    if (isFn(sharePage)) return sharePage()
  },
  /**
    * 获取会员卡列表
   */
  getVipList: function () {
    const continuousFn = { fn: this.getVipList, param: { ...arguments } }
    const userId = getGlobalVal('userId')
    const { options}=this.data
    const fn = (i, v) => {
      globalData['vip'] = v
      wx.setStorageSync(`vip_${userId}`, v)

      var obj={"league_name":v.lname,"id":v.lib_id,"type":v.type}
      wx.setStorageSync('library', obj)
      
      globalData['vipIndex'] = i
      wx.setStorageSync(`vipIndex_${userId}`, i)

      globalData['vipId'] = v['vip_id']
      wx.setStorageSync(`vipId_${userId}`, v['vip_id'])
    }
    GetMineInfo({ continuousFn }).then(res => {
      const { vipList = null } = res.data
      if (vipList.length > 0) {
        for (var i in vipList){
          if (options.vipId == vipList[i].vip_id){
            options.vipIndex = i
            getApp().globalData['vipIndex'] = i
            wx.setStorageSync(`vipIndex_${userId}`, i)
            fn(i, vipList[i]) 
            break
          }
        }
        this.setData({ vipList, options})
      } else {
        wx.showToast({
          title: noVipListToastText,
          icon: 'none'
        })
      }
    })
  },
  /**
   * 选择跳转进入页
   */
  selectRouteCtl: function (e) {
    const { index } = e.currentTarget.dataset
    const { routerTwo } = this.data
    const { url, zindex } = routerTwo[index]
    if (index==2){
      navigateTo({ url, zindex })
    }else{
      if (!hasVipService()) return
      navigateTo({ url, zindex,isAdd:0 })
    }
    
  },

  /**
   * 显示学员切换框
   */
  toggleSelectVipCtl: function () {
    const { vipList } = this.data.options
    // if (!vipList || vipList.length < 2) return
    this.setData({ isShowVipModal: !this.data.isShowVipModal })
  },
    /**
   * 添加孩子跳转
   */
  addchildPage: function () {
    const { routerTwo } = this.data
    const { url, zindex } = routerTwo[0]
    // if (!hasVipService()) return
    wx.scanCode({
      success: res => {
        const webUrl = res.result
        const vipId = webUrl.split('_')[1].split('.')[0]
        if (!vipId) {
          wx.showToast({
            title: qrcodeInvalidToastText,
            icon: 'none'
          })
          return
        }
        // console.log(vipId)
        navigateTo({ url, paras: { vipId, zindex: 3, isAdd: 1} }) 
      }
    })
    // 
  },
  /**
   * 学员切换
   */
  selectVipCtl: function (e) {
    const { index } = e.currentTarget.dataset
    const { options, vipList} = this.data
    const { vipIndex,  userId } = options
    // if (index == vipIndex) {
    //   return
    // }
    const { vip_id } = vipList[index]
    if (vip_id) {
      options.vip = vipList[index]
      getApp().globalData['vip'] = vipList[index]
      wx.setStorageSync(`vip_${userId}`, vipList[index])

      options.vipIndex = index
      getApp().globalData['vipIndex'] = index
      wx.setStorageSync(`vipIndex_${userId}`, index)

      var obj={"league_name":vipList[index].lname,"id":vipList[index].lib_id,"type":vipList[index].type}
      wx.setStorageSync('library', obj)

      options.vipId = vip_id
      getApp().globalData['vipId'] = vip_id
      wx.setStorageSync(`vipId_${userId}`, vip_id)

      // wx.removeStorageSync('library')
    }
    this.setData({ options, isShowVipModal: 0 })
  },
 
  /**
   * 获取微信用户信息 
   */
  getUserInfoCtl: function (e) {
    const { detail } = e
    const { userInfo, errMsg = '触发获取微信用户信息失败' } = detail
    if (userInfo) {
      if (isFn(saveUserInfo)) saveUserInfo(detail, this.data.code)
    } else {
      wx.showToast({
        title: '触发微信授权失败',
        icon: 'none'
      })
    }
  }
})