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

Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseImgUrl, 
    thumbnail,
    statusBar: app.globalData.statusBar,
    isLoaded: false,
    isChild:false,
    searchKey: '', 
    checkNum:0,
    isCheck:false,
    pageNo: 1,
    pageSize: 10,
    isAll: false,
    isAllType:1,
    isType:1,
    hiddenModel:false,
    HOT_NAME: '#',
    toView: 'A',
    scrollTop: 10,
    nodata: [
      {
        text: '暂无教师'
      },
    ],
    list: [
      // {
      //   "teacherId": "asdasd",
      //   "teacherTypeList": ["2", "3"],
      //    "subject": "语文,数学",
      //   "name": "王的大",
      //   "imgUrl": "",
      //   "phone": "",
      //   "classSum": 10
      // }
    ]
  },

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

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

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

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

  },

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

  },

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

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

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    if (app.sharePageDefaultCtl) {
      return app.sharePageDefaultCtl()
    }

  },
  /**
     * 跳转
     */
  navigateCtl:function(e){
    // const { parentVipList } = this.data
    var parentVipList = wx.getStorageSync('parentVipList')
    if (parentVipList.length>0) {
      app.navigateCtl(e);
    } else {
      wx.showToast({
        title: '请勾选孩子后再试',
        icon: 'none'
      })
    }
  },

  /**
   * 底部导航跳转
   */
  redirectCtl: app.redirectCtl,
  /**
   * 添加老师
   */
  addTeacher:function(){
    wx.setNavigationBarTitle({
      title: `添加老师`,
    })
    this.setData({ pageNo: 1, isAddTeacher: true,isAdd:true,list:[]})
    this.getAddTeacher()
  },
  
  /**
  * 提示框隐藏
  */
  allShowModel: function () {
    this.setData({ hiddenModel: false})
  },
  /**
   * 选择老师
   */
  selectTeacher:function(e){
    const { idx } = e.currentTarget.dataset
    const { navIdx } = this.data
    this.setData({ pageNo: 1, pageSize: 10, navIdx: idx })
    wx.showLoading({
      title: '加载中',
    })
    if(idx==0){
      this.getData()
    }else{
      this.teacherGetData()
    }
  },
 
  
  /**
   * 班级添加老师
   */
  addTeacherList:function(){
    const continuousFn = { fn: this.addTeacherList, param: { ...arguments } }
    const { classId, teacherIdList=[], className } = this.data
    if (teacherIdList.length==0){
      wx.showToast({
        title: '请添加教师',
        icon: 'none'
      })
      return
    }
    ConfirmClassTeacher({ data: { teacherIdList, classId }, continuousFn }).then(res => {
      wx.showToast({
        title: '添加教师成功',
        icon: 'none',
        duration:1000
      })
      setTimeout((function callback() {
        wx.navigateBack({
          delta: 1
        })
      }).bind(this), 500);
      if (isFn(cb)) cb()
    }).catch(res => {
      if (isFn(cb)) cb()
    })
  },
  
 
 
  
  /**
   * 选择学生
   */
  selectLiCtl: function (e) {
    const { index,key} = e.currentTarget.dataset
    const { isCheck,navIdx,teacherList } = this.data
      teacherList[index].items[key]['isCheck'] = teacherList[index].items[key].isCheck == '' ? 'active' : '';
      this.setData({ teacherList})
      this.caculate(teacherList)
  },
  /**
   * 计算学生总数和vip列表
   */
  studentCaculate: function (list) {
    let checkNum = 0
    const vipIds = [];
    for (let i in list) {
        if (list[i]['isCheck'] =='active') {
                checkNum++
                vipIds.push(list[i]['vipId'])
              }
    }
    this.setData({ checkNum, vipIds})
  },
  /**
   * 计算教师总数和vip列表
   */
  caculate: function (list) {
      let checkNum = 0
    const vipIds = [];
    const teacherIdList = [];
    for (let i in list) {
      for (let j in list[i].items){
        if (list[i].items[j]['isCheck'] =='active') {
                checkNum++
                vipIds.push(list[i].items[j]['vipId'])
                teacherIdList.push(list[i].items[j]['teacherId'])
              }
        }
    }
    this.setData({ checkNum, vipIds, teacherIdList})
  },
 
  /**
   * 获取添加老师列表
   */
  getAddTeacher: function (cb) {
    const continuousFn = { fn: this.getData, param: { ...arguments } }
    const { pageNo, pageSize, list = [],classId } = this.data;
    var that=this;
    ClassTeacherList({ data: {classId,type:1}, continuousFn }).then(res => {
      const { isCheck } = this.data;
      const temp = res.data.list;
      const tempList = (res => {
        for (let i in res) {
          // res[i]['isCheck'] = ''
          res[i]['subject'] = res[i].subject.split(',')
          res[i]['index'] = pinyin.go(res[i].name).slice(0, 1).toUpperCase()
        }
        return res
      })(temp || [])
      let arr = []
      if (pageNo == 1) {
        arr = [...tempList]
      } else {
        arr = [...list, ...tempList]
      }
      this.setData({
        teacherList: that.normalizeSinger(arr),
        pageNo: tempList.length == pageSize ? Number(pageNo) + 1 : pageNo,
        isAll: tempList.length < pageSize,
        isLoaded: true
      })
      if (isFn(cb)) cb()
    }).catch(res => {
      this.setData({ isLoaded: true })
      if (isFn(cb)) cb()
    })
  },
  /**
   * 字母导航
   */
  normalizeSinger(list) {
    const { navIdx}=this.data;
    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({
            name: item.name,
            phone: item.phone,
            subject: item.subject,
            imgUrl: item.imgUrl,
            teacherTypeList: item.teacherTypeList,
            teacherId: item.teacherId,
            isCheck: ''
          })
        }
        const key = item.index
        if (!map[key]) {
          map[key] = {
            title: key,
            items: []
          }
        }
        map[key].items.push({
          name: item.name,
          phone: item.phone,
          subject: item.subject,
          imgUrl: item.imgUrl,
          teacherTypeList: item.teacherTypeList,
          teacherId: item.teacherId,
          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,
    })
  },
   /**
   * 返回孩子信息
   */
  blockInfo:function(){
    const { classId} = this.data
    this.redirectCtl({ url: 'main', method: { classId} }, true)
  },
  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)
  }
})