// parents/pages/home/home.js
import { routers, viewImage, sharePage, isFn, getGlobalVal, getWxLocationSetting } from '../../../utils/util.js'
import { GetLibrary, GetParentHome, GetBorrowBookNum, ScanningBooks } from '../../../utils/api.js'
const { navigateTo, redirectTo, navigateBack } = routers()
const { globalData, hasLibraryService, hasVipService } = getApp()
const { baseImgUrl, qrcodeInvalidToastText } = globalData
Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseImgUrl,
    isFirst: 0,
    latitude: '',
    longitude: '',
    isLoaded: 0,
    pageNo: 1,
    pageSize: 10,
    routers: [
      {
        icon: '../../../assets/wo_yao_jie_shu.png',
        text: '我要借书',
        url: 'parents/pages/borrow/borrow',
        zindex: 3,
      },
      {
        icon: '../../../assets/yu_yue_jie_shu.png',
        text: '预约借书',
        url: 'parents/pages/reservations/reservations',
        zindex: 3,
      },
      {
        icon: '../../../assets/cheng_zhang_ji_lu.png',
        text: '成长记录',
        url: 'parents/pages/growth/growth',
        zindex: 3,
      }
    ],
    topList: [],
    list: [],
    footerData: {
      actIndex: 0,
      list: [
        {
          text: '找好书',
          icon: '../../../assets/book_gray.png',
          actIcon: '../../../assets/book_blue.png',
          url: 'parents/pages/home/home',
          zindex: 3,
        },
        {
          text: '好书推荐',
          icon: '../../../assets/wish_gray.png',
          actIcon: '../../../assets/wish_blue.png',
          url: 'parents/pages/good_books/good_books',
          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.vipId = getGlobalVal('vipId', `vipId_${userId}`) || ''
    options.library = getGlobalVal('library')
    this.setData({ options, isFirst: 1 })
    if (options.library) {
      this.getList(res => {
        this.setData({ isLoaded: 1 })
      })
    } else {
      this.getLocation(res => {
        this.setData({ isLoaded: 1 })
      })
    }
  },

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

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const { options, isFirst } = this.data
    options.library = getGlobalVal('library')
    this.setData({ options })
    if (!options.library && !isFirst) {
      this.getLocation()
    }
  },

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

  },

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

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getList(res => {
      wx.stopPullDownRefresh()
    })
  },

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

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    if (isFn(sharePage)) return sharePage()
  },

  /**
   * 获取定位
   */
  getLocation: function (cb) {
    getWxLocationSetting(res => {
      this.setData({
        isShowPosition: false
      })
      wx.showLoading({
        title: '定位中'
      })
      wx.getLocation({
        type: 'wgs84',
        success: res => {
          const { latitude, longitude } = res
          this.setData({
            latitude,
            longitude
          })
          this.getLibrary(cb)
        },
        fail: res => {
          wx.showToast({
            title: '定位失败',
            icon: 'none'
          })
        },
        complete: res => {
          wx.hideLoading()
        }
      })
    })
  },

  /**
   * 获取图书馆
   */
  getLibrary: function (cb) {
    const continuousFn = { fn: this.getLibrary, param: { ...arguments } }
    const { options, latitude, longitude, pageNo, pageSize } = this.data
    const { vipId } = options
    GetLibrary({ data: { vipId, pageNo, pageSize, leagueLat: latitude, leagueLng: longitude }, continuousFn }).then(res => {
      const { list } = res.data
      if (list[0]['id']) {
        getApp().globalData.library = list[0]
        wx.setStorageSync('library', list[0])
        this.setData({ 'options.library': list[0] })
        this.getList(cb)
      }
    })
  },

  /**
   * 获取首页数据
   */
  getList: function (cb) {
    const continuousFn = { fn: this.getList, param: { ...arguments } }
    const libId = this.data.options.library.id || ''
    hasLibraryService()
    if (!libId) {
      wx.showToast({
        title: '请先定位图书馆',
        icon: 'none'
      })
      return
    }
    GetParentHome({ data: { libId }, continuousFn }).then(res => {
      const { topList, list } = res.data
      this.setData({ topList, list })
      cb && cb(res)
    }).catch(res => {
      cb && cb(res)
    })
  },

  /**
   * 选择跳转进入页
   */
  selectRouteCtl: function (e) {
    const { index } = e.currentTarget.dataset
    const { routers } = this.data
    const { url, zindex } = routers[index]
    if (!hasVipService()) return
    navigateTo({ url, zindex })
  },

  /**
   * 调用微信扫一扫之前判断可借书多少本
   */
  scanCtl: function () {
    const continuousFn = { fn: this.scanCtl, param: { ...arguments } }
    const { vipId, library } = this.data.options
    const libId = library.id || ''
    if (!hasVipService() || !hasLibraryService()) return
    GetBorrowBookNum({ data: { vipId, libId }, continuousFn }).then(res => {
      const { totalBook, lentBook } = res.data
      wx.showToast({
        title: `您还可以借${totalBook}本书`,
        icon: 'none'
      })
      if (totalBook > 0) {
        this.scanFn()
      }
      this.setData({ ...res.data })
    })
  },

  /**
   * 调用微信扫一扫
   */
  scanFn: function () {
    wx.scanCode({
      success: res => {
        const url = res.result
        const detailsId = url.split('_')[1].split('.')[0]
        if (!detailsId) {
          wx.showToast({
            title: qrcodeInvalidToastText,
            icon: 'none'
          })
          return
        }
        this.scanningBooksFn(detailsId)
      }
    })
  },

  /**
   * 扫一扫借书
   */
  scanningBooksFn: function (detailsId) {
    const continuousFn = { fn: this.scanningBooksFn, param: { ...arguments } }
    const { vipId } = this.data.options
    ScanningBooks({ data:{ detailsId, vipId }, continuousFn}).then(res => {
      navigateTo({ url: 'borrow', paras: { ...res.data } })
    }).catch(res => {
      wx.showToast({
        title: res.msg,
        icon: 'none'
      })
    })
  }
})