// parents/pages/library/library.js
import { routers, viewImage, sharePage, isFn, getGlobalVal, getWxLocationSetting } from '../../../utils/util.js'
import { GetLibrary,GetMineInfo } from '../../../utils/api.js'
const { navigateTo, redirectTo, navigateBack } = routers()
const { globalData } = getApp()
const { baseImgUrl } = globalData

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isLoaded: 0,
    latitude: '',
    longitude: '',
    pageNo: 1,
    pageSize: 10,
    content: '',
    isResult: false,
    libraryList: [],
    isAll: 0,
    nodataArray: {
      text: "搜索无结果"
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (!options.isAdd){
      options.vipId = getGlobalVal('vipId', `vipId_${getGlobalVal('userId')}`) || ''
    }
    if (options.isAdd==1){
      this.getLocation(res => {
        this.setData({ isLoaded: 1 })
      })
    }else{
      this.getData()
    }
    this.setData({ options })
    console.log(options)
    // console.log(options.isAdd)
    // 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 () {
    let _this = this
    wx.getStorage({
      key: 'setStoragelibraryList',
      success: function (res) {
        const setStoragelibraryList = res.data
        _this.setData({
          setStoragelibraryList: setStoragelibraryList,
        })
        // console.log(setStoragelibraryList)
      }
    })

  },

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

  },

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

  },
  returnBack:function(){
    wx.navigateBack({
      
    })
  },
  /**
    * 输入搜索值
    */
  inputSearchCtl: function (e) {
    const { value } = e.detail
    const { content } = this.data
    if (content == value) {
      return
    }
    this.setData({ content: value, pageNo: 1 })
    this.setData({ isResult: true })
    this.getLibrary()
  },

  /**
   * 清除搜索值
   */
  clearSearchCtl: function () {
    this.setData({ content: '' })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    const { libraryList}=this.data
    if (libraryList.length<11) return
    this.setData({ pageNo: 1 })
    this.getLibrary(res => {
      wx.stopPullDownRefresh()
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    const { isAll } = this.data
    if (isAll) return
    this.getLibrary()
  },

  /**
   * 用户点击右上角分享
   */
  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()
        }
      })
    })
  },
  /**
  * 获取图书馆
  */
  getData: function (cb) {
    const continuousFn = { fn: this.getData, param: { ...arguments } }
    GetMineInfo({ data: {}, continuousFn }).then(res => {
      const { vipList } = res.data
      const data = (list => {
        const arr = []
        for (const v of list) {
          const { lname = '', lib_id = '',type=''} = v
          arr.push({
            league_name: lname,
            id: lib_id,
            type:type
          })
        }
        return arr
      })(vipList)
      console.log(data)
      if (data.length>0){
        this.setData({ libraryList: data, isLoaded:1})
      }else{
        this.getLocation(res => {
          this.setData({ isLoaded: 1 })
        })
      }
      cb && cb(res)
    }).catch(res => {
      cb && cb(res)
    })
  },

  /**
   * 获取图书馆
   */
  getLibrary: function (cb) {
    const continuousFn = { fn: this.getLibrary, param: { ...arguments } }
    const { options, latitude, longitude, pageNo, pageSize, libraryList, content } = this.data
    const { vipId } = options
    GetLibrary({ data: { vipId, pageNo, pageSize, leagueLat: latitude, leagueLng: longitude, leagueName: content }, continuousFn }).then(res => {
      const { list } = res.data
      let listTemp = []
      if (pageNo == 1) {
        listTemp = [].concat(list)
      } else {
        listTemp = [].concat(libraryList, list)
      }
      this.setData({
        libraryList: listTemp,
        pageNo: list.length == pageSize ? pageNo + 1 : pageNo,
        isAll: list.length < pageSize
      })
      cb && cb(res)
    }).catch(res => {
      cb && cb(res)
    })
  },

  /**
   * 获取图书馆
   */
  selectLibraryCtl: function (e) {
    const { index } = e.currentTarget.dataset
    const { libraryList,options } = this.data
    const { id, league_name } = libraryList[index]
    const { vipId = '', sex = '', school = '', grade = '', childName = '',isAdd,phone='',parentRole='',parentName='',imgUrl='',zindex}=options
    wx.setStorageSync('setStoragelibraryList', libraryList[index])
    console.log(isAdd)
    if (id) {
      if (isAdd==1){
        redirectTo({ url: 'parents/pages/information/information', paras: { zindex: 3, vipId, sex, school, grade, childName, libId: id, league_name, isAdd,phone,parentRole,parentName,imgUrl,isSchool:1} })
      }else{
        getApp().globalData.library = libraryList[index]
        wx.setStorageSync('library', libraryList[index])
        redirectTo({ url: 'parents/pages/me/me', zindex: 3 })
      }
    } else {
      wx.showToast({
        title: '该图书馆无效',
        icon: 'none'
      })
    }
  }
})