// pages/main/main.js
import { routers, viewImage, sharePage, isFn, getGlobalVal, formatDateTime, formateNumber,throttle } from '../../utils/util.js'
import { ClassList, TeacherList,StudentList,AuditTeacher,RenameClass, CreateClass, DeleteClass, MyInfo2,LibAuditList,BindLibAudit} 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: {
    baseImgUrl, 
    thumbnail,
    statusBar: app.globalData.statusBar,
    customBar: app.globalData.customBar,
    custom: app.globalData.custom,
    navList: ['班级','学生','教师','审核'],
    roleList: ['学生','教师'],
    roleIdx:0,
    navIdx:0,
    pageNo:1,
    pageSize:20,
    isAll: false,
    hiddenModel:false,
    renameModel:false,
    classModel:false,
    refuseModel:false,
    isSky:false,
    isType:1,
    isLogin:false,
    HOT_NAME: '#',
    CLOSE_SERVE:'服务关闭',
    toView: 'A',
    scrollTop: 10,
    list: [],
    nodata: [
      {
        text: '暂无班级'
      },
      {
        text: '暂无学生'
      },
      {
        text: '暂无教师'
      },
      {
        text: '暂无审核' 
      }
    ],
  }, 

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

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

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const {navIdx}=this.data
    const userInfo = wx.getStorageSync('userInfo')
    if (!userInfo) {
      this.setData({ isLogin: false })
    }else{
      this.getReviewteacher()
      this.setData({ isLogin: true, pageNo: 1})
      // if(navIdx!=3){
        this.getData()
      // }
      this.getInfo()
    }
    
  },

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

  },

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

  },

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

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

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

  },
  /**
 * 微信授权 
 */
  getUserInfoCtl: function (e) {
    const { detail } = e
    const { userInfo } = detail
    const { isCheckProtocol, code } = this.data
    if (userInfo) {
      if (isFn(saveUserInfo)) saveUserInfo(detail, code)
    } else {
      wx.showToast({
        title: '触发微信授权失效',
        icon: 'none'
      })
    }
  },
  /**
   * 获取资料
   */
 
  getInfo: function (cb) {
    const continuousFn = { fn: this.getInfo, param: { ...arguments } }
    MyInfo2({ data: {}, continuousFn }).then(res => {
      const { photo, orgName, libId} = res.data;
      if (orgName.length>10){
        var org = orgName.slice(0, 10) + '...'
      }else{
        var org = orgName
      }
      this.setData({ photo, orgName:org,libId})
      wx.setStorageSync('libId', libId)
      if (isFn(cb)) cb()
    }).catch(res => {
      this.setData({ isLoaded: true })
      if (isFn(cb)) cb()
    })
  },
  /**
  * input
  */
  inputCtl: function (e) {
    const { temp = {}, type } = e.currentTarget.dataset
    const { value } = e.detail
    temp[type] = value;
    const { className } = temp;
    if (type == 'className') {
      if (value != '') {
        // console.log(className)
        return this.setData({ className })
      }
    }
  },
  /**
   * 选择老师
   */
  selectTeacher:function(e){
    const { idx } = e.currentTarget.dataset
    const { roleIdx } = this.data
    this.setData({ roleIdx: idx })
    wx.showLoading({
      title: '加载中',
    })
    if(idx==0){
      this.getData()
    }else{
      this.getReviewteacher()
    }
  },
  /**
   * 删除输入
   */
  deleteInput:function(){
    this.setData({ className:'' })
  },
  /**
   * 选择班级
   */
  selectClass:throttle(function (e) {
    const { idx } = e.currentTarget.dataset
    const { navIdx } = this.data
    this.setData({ navIdx: idx,list:[],roleIdx:0,currentIndex:0,pageNo:1})
    this.getData()
  },300),
  /**
   * 提示框隐藏
   */
  allShowModel: function () {
    this.setData({ hiddenModel: false, renameModel: false, classModel:false,refuseModel:false })
  },
  /**
   * 编辑班级
   */
  redactClass:function(e){
    const { cname, id, snum, tnum,del } = e.currentTarget.dataset;
    const {isSky}=this.data
    this.setData({ isSky: false })
    if(snum==0&&tnum==0){
      this.setData({ isSky: true })
    }
    this.setData({ hiddenModel: true, className: cname, id, snum, tnum})
  },
  /**
   * 重命名弹框
   */
  renameShow: function (e) { 
    const { type } = e.currentTarget.dataset;
    if(type==0){
      this.setData({className:''})
    }
    this.setData({ isRename: Number(type),hiddenModel: false, renameModel: true})
  },
  /**
   * 删除班级弹框
   */
  classShow: function () {
    const { snum, tnum}=this.data
    // console.log(snum, tnum)
    // if (snum==0&&tnum==0){
    this.setData({ hiddenModel: false, classModel: true })
    // }else{
    //   this.setData({ isSky: true })
    // }
  },
  /**
  * 确认重命名
  */
  sureRename: function (cb) {
    const continuousFn = { fn: this.sureRename, param: { ...arguments } }
    const { id, className}=this.data;
    RenameClass({ data: { classId: id, className }, continuousFn }).then(res => {
      wx.showToast({
        title: '操作成功',
        icon: 'none'
      })
      this.allShowModel()
      this.getData()
      this.setData({ className:''})
      if (isFn(cb)) cb()
    }).catch(res => {
      if (isFn(cb)) cb()
    })
  },
  /**
  * 确认新建班级
  */
  sureCreateClass: function (cb) {
    const continuousFn = { fn: this.sureCreateClass, param: { ...arguments } }
    const { id, className } = this.data;
    if(!className){
      wx.showToast({
        title: '请输入班级名',
        icon: 'none'
      })
      return
    }
    CreateClass({ data: { className }, continuousFn }).then(res => {
      wx.showToast({
        title: '操作成功',
        icon: 'none'
      })
      this.allShowModel()
      this.getData()
      this.setData({ className: '' })
      if (isFn(cb)) cb()
    }).catch(res => {
      if (isFn(cb)) cb()
    })
  },
  /**
  * 确认删除班级
  */
  sureDeleteClass: function (cb) {
    const continuousFn = { fn: this.sureDeleteClass, param: { ...arguments } }
    const { id, cname } = this.data;
    DeleteClass({ data: { classId: id }, continuousFn }).then(res => {
      wx.showToast({
        title: '删除成功',
        icon: 'none'
      })
      this.allShowModel()
      this.getData()
      if (isFn(cb)) cb()
    }).catch(res => {
      if (isFn(cb)) cb()
    })
  },
  /**
   * 拒绝审核弹框
   */
  refuseShow: function (e) { 
    const { xid,type } = e.currentTarget.dataset;
    console.log(xid,type)
    this.setData({ refuseType: Number(type),xid})
    if(type==2){
      this.setData({ refuseModel: true})
    }else{
      this.selectRefuse()
    }
  },
  /**
  * 通过拒绝审核
  */
 selectRefuse: function (cb) {
  const continuousFn = { fn: this.selectRefuse, param: { ...arguments } }
  const { xid,refuseType,roleIdx} = this.data;
  var obj = [BindLibAudit,AuditTeacher]
  var dataList=[{vipId:xid,type:refuseType},{teacherId:xid,type:refuseType}]
  obj[roleIdx]({ data:dataList[roleIdx], continuousFn }).then(res => {
    if(refuseType==1){
      wx.showToast({
        title: '通过审核',
        icon: 'none'
      })
    }else{
      wx.showToast({
        title: '拒绝成功',
        icon: 'none'
      })
    }
    this.getReviewteacher()
    this.allShowModel()
    this.getData()
    if (isFn(cb)) cb()
  }).catch(res => {
    if (isFn(cb)) cb()
  })
},
 /**
  * 获取审核数量
  */
 getReviewNum: function (cb) {
  const continuousFn = { fn: this.getReviewNum, param: { ...arguments } }
  const {reviewNum}=this.data
  LibAuditList({ data: {}, continuousFn }).then(res => {
    const { list } = res.data;
    this.setData({reviewNum:reviewNum.length+list.length})
    if (isFn(cb)) cb()
  }).catch(res => {
    if (isFn(cb)) cb()
  })
},
/**
  * 获取审核老师列表
  */
 getReviewteacher: function (cb) {
  const continuousFn = { fn: this.getReviewteacher, param: { ...arguments } }
 
  TeacherList({ data: {type:1}, continuousFn }).then(res => {
    wx.hideLoading();
    const { list } = res.data;
    this.setData({teacherAuditList:list,reviewNum:list})
    this.getReviewNum()
    if (isFn(cb)) cb()
  }).catch(res => {
    if (isFn(cb)) cb()
  })
},
  /**
   * 获取数据
   */
  getData: function (cb) {
    const continuousFn = { fn: this.getData, param: { ...arguments } }
    const { navIdx,list=[],pageNo,pageSize,isAll} = this.data
    // console.log(navIdx)
    // if (isAll&&navIdx==1) {
    //   return
    // }
    wx.showLoading({
      title: '加载中',
    })
    var obj = [ClassList,StudentList,TeacherList,LibAuditList]
    var dataList=[{},{pageNo,pageSize,type:3},{},{}]
    var that=this;
    obj[navIdx]({ data: dataList[navIdx], continuousFn }).then(res => {
      wx.hideLoading();
      const temp= res.data.list;
      // if (navIdx == 0) {
      //   wx.setStorageSync('defaultClassId', list[0].classId)
      // }
      const listTemp = (res => {
        if(navIdx == 2){
          for (let i in res) {
            res[i]['subject'] = res[i].subject.split(',')
            res[i]['index'] = pinyin.go(res[i].name).slice(0, 1).toUpperCase()
          }
        }else if(navIdx == 1){
          for (let i in res) {
            res[i]['index'] = pinyin.go(res[i].childName).slice(0,1).toUpperCase()
          }
        }
        return res
      })(temp)
      if(navIdx == 1){
        
        let arr = []
        if (pageNo == 1) {
          arr = [...listTemp]
        } else {
          if (isAll) {
            arr = [...list]
          }else{
            arr = [...list, ...listTemp]
          }
        }
        this.setData({
          list:arr,
          getList:that.normalizeSinger(arr),
          pageNo: listTemp.length == pageSize ? Number(pageNo) + 1 : pageNo,
          isAll: listTemp.length < pageSize,
        })
      }else{
        this.setData({
          list:navIdx==2?that.normalizeSinger(listTemp):listTemp,
          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: []
      },
      closeServe:{
        title: this.data.CLOSE_SERVE,
        items: []
      },
    }
    if (navIdx==1){
      list.forEach((item, index) => {
        if(item.serviceType!=-1){
          var parent = /^[A-Za-z]+$/;
          if (!parent.test(item.index)) {
            map.hot.items.push({
              childName: item.childName,
              classId: item.classId,
              className: item.className,
              grade: item.grade,
              imgUrl: item.imgUrl,
              serviceType: item.serviceType,
              vipId: item.vipId,
              phone:item.phone
            })
          }
          const key = item.index
          if (!map[key]) {
            map[key] = {
              title: key,
              items: []
            }
          }
          map[key].items.push({
            childName: item.childName,
            classId: item.classId,
            className: item.className,
            grade: item.grade,
            imgUrl: item.imgUrl,
            serviceType: item.serviceType,
            vipId: item.vipId,
            phone: item.phone
          })
        }else if(item.serviceType==-1){
          map.closeServe.items.push({
            childName: item.childName,
            classId: item.classId,
            className: item.className,
            grade: item.grade,
            imgUrl: item.imgUrl,
            serviceType: item.serviceType,
            vipId: item.vipId,
            phone:item.phone
          })
        }
      })
    }else if(navIdx == 2){
      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,
          })
        }
        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,
        })
      })
    }
    // 为了得到有序列表,我们需要处理 map
    let ret = []
    let hot = []
    let close = []
    
    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)
      }else if (val.title === this.data.CLOSE_SERVE) {
        close.push(val)
      }
    }
    ret.sort((a, b) => {
      return a.title.charCodeAt(0) - b.title.charCodeAt(0)
    })
    if (hot[0].items.length == 0&&close[0].items.length == 0) {
      return ret
    } else if (hot[0].items.length == 0) {
      return ret.concat(close)
    }else if (close[0].items.length == 0) {
      return ret.concat(hot)
    }else{
      return ret.concat(hot,close)
    }

  },

  // 点击首字母
  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)
  }
})