// pages/studyHouse/studyHouse.js
const app = getApp();
const { formatDate, formatTime2 } = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据school, vipId, isAddChild, type, childName, parentName, grade
   */
  data: {
    pageSize: 10,
    pageNo: 1,
    maxCreateTime: formatTime2(new Date()),
    hiddenModel: false,
    value:'',
    isWechat:0,
    imgUrl:'',
    childName:'',
    sex:0,
    parentName:'',
    phone:'',
    grade:'',
    school:'',
    derver:'',
    type:1,
    parentRole:'',
    schoolModel:false,
    schoolIdx:0,
    libIdx:0,
    schoolList:[],
    // list: [
      // {
      //   "id": "425ac67f-d0a5-49dc-bd8a-90768fbbd75f",
      //   "distance": 0.87,
      //   "leagueName": "私塾家深圳测试馆2",
      //   "leagueAddress": "深圳市南山智园b1座4楼"
      // }
      // ],
    libData: {
      list: []
    },
    location: {},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    wx.setStorageSync('schoolName', options.schoolName)
    this.setData(options);
    this.getLocation();
    // this.getLibrary();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

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

  },

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

  },

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

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

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  /**
   * 跳转
   */
  navigateCtl: app.navigateCtl,
  /**
   * 底部导航跳转
   */
  redirectCtl: app.redirectCtl,
  /**
   * 查询作业吧服务时间
   */
  chatHomeworkTime: function (id) {
    const { vipId } = this.data;
    const postData = { fn: this.chatHomeworkTime, param: { ...arguments } }
    app.post('/api/parents/parents/V2/service/findZybServiceList', { vipId, libId:id }, 0, postData).then(res => {
      const { list } = res.data;
      if (list.length==0){
        this.setData({ hiddenModel: true,isList:false })
      }else{
        this.setData({ serviceList: list, hiddenModel: true, isList: true });
      }
    })
  },
  
  /**
   * 输入馆名
   */
  inputCtl: function (e) {
    const { value } = e.detail
    this.setData({value})
    this.setData({ pageNo: 1 })
    this.getLibrary()
  },

  /**
   * 获取定位经纬度
   */
  getLocation: function () {
    app.getWxUserLocationSetting(res => {
      wx.showLoading({
        title: '定位中'
      })
      wx.getLocation({
        type: 'wgs84',
        success: res => {
          this.setData({
            location: {
              longitude: res.longitude,  // '113.36403' ||
              latitude: res.latitude // '23.14203' ||
            }
          })
          setTimeout(() => {
            this.getLibrary()
          }, 0)
        },
        fail: res => {
          setTimeout(() => {
            wx.showToast({
              title: '定位失败',
              icon: 'none'
            })
          }, 10)
          setTimeout(() => {
            wx.navigateBack({
              delta: 1
            })
          }, 1000)
        },
        complete: res => {
          wx.hideLoading()
        }
      })
    })

  },
  /**
  * 获取图书馆定位数据
  */
  getLibrary: function () {
    const postData = { fn: this.getLibrary, param: { ...arguments } }
    let { pageNo, pageSize, value, location, maxCreateTime,list=[],vipId} = this.data
    const schoolName=wx.getStorageSync('schoolName')||''
    app.post('/api/parents/parents/V2/getLibListV1', { 
      vipId,
      value,
      latitude: location.latitude,
      longitude: location.longitude,
      maxCreateTime,
      pageSize,
      pageNo,
      schoolName
    }, 0, postData).then(res => {
      const { id, leagueName, leagueAddress, schoolList, leagueAuditStatus, leagueNameAudit,schoolName}=res.data;
      if (pageNo == 1) {
        list = res.data.list
      } else {
        list = list.concat(res.data.list)
      }
      // if (pageNo == 1) {
      //   this.setData({
      //     libName: list[0].leagueName,
      //     libId: list[0].id
      //   })
      // }
      this.setData({
        id, leagueName, leagueAddress, leagueAuditStatus, leagueNameAudit,schoolName,
        list,
        schoolList,
        pageNo:list.length==pageSize * pageNo ? pageNo + 1 : pageNo,
        isAll: list.length < pageSize
      })
    })
  },
  /**
  * 解绑
  */
  unbind:function(e){
    const { unbindLeagueName, libId, isCut,index} = e.currentTarget.dataset.method
    const {list}=this.data
    if (isCut==1){
      this.setData({isCut})
      this.chatHomeworkTime(libId)
    }else{
      if (list[index].schoolList.length>0){
        this.setData({ schoolList: list[index].schoolList})
      }
      this.setData({ hiddenModel: true, unbindLeagueName, libId, isCut, libIdx: index})
    }
  },
  /**
   * 提示框隐藏
   */
  allShowModel: function () {
    this.setData({ hiddenModel: false, schoolModel:false })
  },
  /**
   *打开选择学校
   */
  selectShowModel: function () {
    this.setData({schoolModel: true })
  },
   /**
   * 选择学校
   */
  selectSchool:function(e){
    const { idx } = e.currentTarget.dataset
    const { list, libIdx, schoolList}=this.data
    this.setData({ schoolIdx: idx, school:schoolList[idx].schoolName})
  },
  
  /**
  * 解绑成功
  */
  unbindCtl:function(){
    const postData = { fn: this.unbindCtl, param: { ...arguments } };
    const { vipId, id, schoolList}=this.data;
    app.post('/api/parents/parents/V2/unbindVipLibV1', { vipId, libId:id}, 0, postData).then(res => {
      wx.showToast({
        title: '解绑成功',
        icon: 'none',
        duration: 1000
      });
      this.setData({ hiddenModel: false })
      this.getLibrary();
    })
  },
  /**
  * 重新选择
  */
  againChoose: function () {
    const postData = { fn: this.againChoose, param: { ...arguments } };
    const { vipId} = this.data;
    app.post('/api/parents/parents/V2/againChooseLib', { vipId}, 0, postData).then(res => {
      wx.showToast({
        title: '重新选择成功',
        icon: 'none',
        duration: 1000
      });
      this.setData({ hiddenModel: false })
      this.getLibrary();
    })
  },
  /**
  * 换学校
  */
 changeSchool: function () {
    const postData = { fn: this.unbindCtl, param: { ...arguments } };
   const { vipId, school, isCut, libId, isAddChild, type, childName, parentName, grade,unbindLeagueName, derver, sex, parentRole,schoolList } = this.data;
   if (isAddChild==1){
     this.redirectCtl({ url: 'kids_information', method: { isAddChild, school, vipId, type, childName, parentName, grade, libId, leagueName: unbindLeagueName, isMain: 1, derver, sex, parentRole, school, schoolList } }, true)
   }else{
     if (isCut == 2) {
       app.post('/api/parents/parents/V2/bindVipLibV2', { vipId, schoolName: school, libId }, 0, postData).then(res => {
         wx.showToast({
           title: '绑定成功',
           icon: 'none',
           duration: 1000
         });
         this.getLibrary();
         this.setData({ schoolModel: false })
       })
     } else {
       app.post('/api/parents/parents/V2/upMyChildInfo', { vipId, school }, 0, postData).then(res => {
         wx.showToast({
           title: '更换成功',
           icon: 'none',
           duration: 1000
         });
         this.setData({ schoolModel: false })
       })
     }
   }
   
   
  },
  /**
  * 绑定成功
  */
  bindVipLib:function(){
    const postData = { fn: this.bindVipLib, param: { ...arguments } };
    var that=this;
    const { vipId, libId, isAddChild, obj, isAddOrgam, unbindLeagueName, isWechat, isWechatschool, type, childName, parentName, grade, derver, school, sex, parentRole, schoolList} = this.data;
    if (schoolList.length==0){
        if (isAddOrgam==1){
          var that = this;
          if (isWechat==1){
            that.redirectCtl({ url: 'wechat_addchild', method: { isAddChild, school, vipId, type, childName, parentName, grade, libId, leagueName: unbindLeagueName, isMain: 1, derver, sex, parentRole, school, schoolList} }, true)
          }else{
            if (isAddChild==0){
              app.post('/api/parents/parents/V2/bindVipLibV2', { vipId, libId }, 0, postData).then(res => {
                wx.showToast({
                  title: '绑定成功',
                  icon: 'none',
                  duration: 1000
                });
                this.setData({ hiddenModel: false })
                this.getLibrary();
                // that.redirectCtl({ url: 'kids_information', method: { isAddChild, school, vipId, type, childName, parentName, grade, libId, leagueName: unbindLeagueName, isMain: 1, derver, sex, parentRole, school } }, true)
              })
            }else{
              that.redirectCtl({ url: 'kids_information', method: { isAddChild, school, vipId, type, childName, parentName, grade, libId, leagueName: unbindLeagueName, isMain: 1, derver, sex, parentRole, school, schoolList} }, true)
            }
            
          }
          
        }else{
          app.post('/api/parents/parents/V2/bindVipLibV2', { vipId, libId }, 0, postData).then(res => {
            wx.showToast({
              title: '绑定成功',
              icon: 'none',
              duration: 1000
            });
          })
          this.setData({ hiddenModel: false })
          this.getLibrary();
        }
    }else{
      this.setData({ schoolModel: true, hiddenModel: false })
    }
    
  }
})