// pages/select_class/select_class.js
import { routers, viewImage, sharePage, isFn, getGlobalVal, formatDateTime, formateNumber } from '../../utils/util.js'
import { StudentChangeClass, StudentSelectClassList} from '../../utils/api.js'
import { pinyin } from '../../utils/hz2py_full.js'
const { navigateTo, redirectTo, navigateBack } = routers()
const { globalData, saveUserInfo, getWxloginCode, checkStatus } = getApp()
const { baseImgUrl, thumbnail } = globalData
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list:[],
    HOT_NAME: '#',
    toView: 'B',
    scrollTop: 10,
    classId:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var windowHeight = wx.getSystemInfoSync().windowHeight - 50;
    var scrollHeight_ = windowHeight +"px";
    this.setData({scrollHeight_})
    this.setData(options)
  },

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

  },

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

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

  },

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

  },

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

  },

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

  },

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

  },
  /**
   * 取消
   */
  cancel: function () {
    wx.navigateBack({})
  }, 
  /**
  * 选择班级
  */
  slectClass:function(e){
    const { idx, id,key} = e.currentTarget.dataset;
    const {list}=this.data;
    for(var i in list){
      for (var j in list[i].items){
        list[i].items[j]['isCheck'] ='';
      }
    }
    list[idx].items[key]['isCheck'] = list[idx].items[key].isCheck == '' ? 'active' : '';
    this.setData({ list })
  },
  /**
  * 学生选择加入班级列表
  */
  getClassList: function (cb) {
    const continuousFn = { fn: this.getClassList, param: { ...arguments } }
    const { vipId } = this.data;
    StudentSelectClassList({ data: { vipId }, continuousFn }).then(res => {
      const {list}=res.data;
      const tempList = (res => {
        for (let i in res) {
          res[i]['index'] = pinyin.go(res[i].className).slice(0, 1).toUpperCase()
        }
        return res
      })(list || [])
      this.setData({ list: this.normalizeSinger(list)})
      if (isFn(cb)) cb()
    }).catch(res => {
      if (isFn(cb)) cb()
    })
  },
  /**
  * 确认选择班级
  */
  sureConfirmTeacherClass: function (cb) {
    const continuousFn = { fn: this.sureConfirmTeacherClass, param: { ...arguments } }
    const { vipId,list} = this.data;
    const obj={}
    for(var i in list){
      for (var j in list[i].items){
        if (list[i].items[j].isCheck=='active'){
          obj.classId=list[i].items[j].classId
        }
      }
    }
    const {classId}=obj
    if (!classId) {
      wx.showToast({
        title: '请选择班级',
        icon: 'none'
      })
      return
    }
    StudentChangeClass({ data: { vipId, classId }, continuousFn }).then(res => {
      wx.showToast({
        title: '加入成功',
        duration:1000
      })
      setTimeout((function callback() {
        wx.navigateBack({
          delta: 2
        })
      }).bind(this), 1000);
      if (isFn(cb)) cb()
    }).catch(res => {
      if (isFn(cb)) cb()
    })
  },
  /**
   * 字母导航
   */
  normalizeSinger(list) {
    let map = {
      hot: {
        title: this.data.HOT_NAME,
        items: []
      }
    }
     list.forEach((item, index) => {
        var parent = /^[A-Za-z]+$/;
        if (!parent.test(item.index)) {
          map.hot.items.push({
            classId: item.classId,
            className: item.className,
            studentSum: item.studentSum,
            teacherSum: item.teacherSum,
            isCheck: ''
          })
        }
        const key = item.index
        if (!map[key]) {
          map[key] = {
            title: key,
            items: []
          }
        }
        map[key].items.push({
          classId: item.classId,
          className: item.className,
          studentSum: item.studentSum,
          teacherSum: item.teacherSum,
          isCheck: ''
        })
    })
    
    // console.log(map)
    // 为了得到有序列表,我们需要处理 map
    let ret = []
    let hot = []
    for (let key in map) {
      let val = map[key]
      if (val.title.match(/[a-zA-Z]/)) {
        ret.push(val)
      } else if (val.title === this.data.HOT_NAME) {
        hot.push(val)
      }
    }
    ret.sort((a, b) => {
      return a.title.charCodeAt(0) - b.title.charCodeAt(0)
    })
    console.log(hot, ret)
    if (hot[0].items.length == 0) {
      return ret
    } else {
      return ret.concat(hot)
    }

  },

  // 点击首字母
  scrollToview(e) {
    const { id, idx } = e.currentTarget.dataset
    console.log(id, idx)
    this.setData({ currentIndex: idx, toView: id })
    wx.showToast({
      title: `${id}`,
      icon: 'none',
      duration: 500
    })

  },
  // 滚动时触发事件
  viewScroll: function (e) {
    var newY = e.detail.scrollTop;
    // this.scrollY(newY);
  },
  scrollY(newY) {
    const listHeight = this.data.listHeight
    // console.log(listHeight)
    // 当滚动到顶部,newY>0
    if (newY == 0 || newY < 0) {
      this.setData({
        currentIndex: 0,
      })
      return
    }
    // 在中间部分滚动
    for (let i = 0; i < listHeight.length - 1; i++) {
      // debugger
      let height1 = listHeight[i]
      let height2 = listHeight[i + 1]
      console.log(listHeight, i)
      if (newY >= height1 && newY < height2) {
        // console.log(i)
        this.setData({
          currentIndex: i,
        })
        return
      }
    }
    // 当滚动到底部,且-newY大于最后一个元素的上限

    this.setData({
      currentIndex: listHeight.length - 2,
    })
  },
  calculateHeight() {
    var lHeight = [],
      that = this;
    let height = 0;
    lHeight.push(height);
    var query = wx.createSelectorQuery();
    query.selectAll('.list-group').boundingClientRect(function (rects) {
      var rect = rects,
        len = rect.length;
      for (let i = 0; i < len; i++) {
        height += rect[i].height;
        lHeight.push(height)
      }

    }).exec();
    var calHeight = setInterval(function () {
      if (lHeight != [0]) {
        that.setData({
          listHeight: lHeight
        });
        clearInterval(calHeight);
      }
    }, 1000)
  },
})