import {pinyin} from '../../utils/hz2py_full.js'
import { routers, viewImage, sharePage, isFn, getGlobalVal, formatDateTime } from '../../utils/util.js'
import { AllStudentList } from '../../utils/api.js'
const { navigateTo, redirectTo, navigateBack } = routers()
const app = getApp();
const { globalData } = getApp()
const { baseImgUrl, thumbnail } = globalData
const TITLE_HEIGHT = 30
Page({
  data: {
    baseImgUrl,
    thumbnail,
    isLoaded: false,
    toView: 'B',
    studentList: [],
    scrollTop: 10,
    HOT_NAME: '#',
    HOT_SINGER_LEN: 10,
    listHeight: [],
    currentIndex: 0,
    fixedTitle: '',
    fixedTop: 0,
    // studentName:'',
    nodata: {
      nodataObj: {
        image: '../../assets/no_search.png',
        text: '没有搜索结果'
      }
    },
    list: [
      // {
      //   "vipId": "90782e09-c1a8-4f9d-9de8-337ef1adb2ef",
      //   "studentName": "张某某",
      //   index:'Z',
      //   "school": "希望小学",
      //   "grade": "一年级",
      //   "imgUrl": "/2019/03/15/9bb54074bbe34f11bca5b8fca675bf43.jpg",
      //   "checkedIn": 0,
      //   "exited": 0
      // },
      // {
      //   "vipId": "90782e09-c1a8-4f9d-9de8-337ef1adb2ef",
      //   "studentName": "萧某某",
      //   "school": "希望小学",
      //   "grade": "四年级",
      //   index: 'X',
      //   "imgUrl": "/2019/03/15/9bb54074bbe34f11bca5b8fca675bf43.jpg",
      //   "checkedIn": 1,
      //   "exited": 1
      // },
      // {
      //   "vipId": "90782e09-c1a8-4f9d-9de8-337ef1adb2ef",
      //   "studentName": "李某某",
      //   "school": "南山小学",
      //   "grade": "一年级",
      //   index: 'L',
      //   "imgUrl": "/2019/03/15/9bb54074bbe34f11bca5b8fca675bf43.jpg",
      //   "checkedIn": 1,
      //   "exited": 0
      // },
      // {
      //   "vipId": "90782e09-c1a8-4f9d-9de8-337ef1adb2ef",
      //   "studentName": "王某某",
      //   "school": "龙华小学",
      //   "grade": "三年级",
      //   index: 'W',
      //   "imgUrl": "/2019/03/15/9bb54074bbe34f11bca5b8fca675bf43.jpg",
      //   "checkedIn": 0,
      //   "exited": 1
      // },
    ],
    footerData: {
      actIndex: 1,
      list: [
        {
          text: '任务',
          url: '../../assets/task_gray.png',
          actUrl: '../../assets/task_green.png',
          src: 'pages/task/task',
          id: 'task'
        },
        {
          text: '学生',
          url: '../../assets/student_gray.png',
          actUrl: '../../assets/student_green.png',
          src: 'pages/student_address_book/student_address_book',
          id: 'student_address_book'
        },
        {
          text: '我的',
          url: '../../assets/me_gray.png',
          actUrl: '../../assets/me_green.png',
          src: 'pages/me/me',
          id: 'me'
        }
      ]
    },
  },
  onLoad: function (options) {
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    const obj = { navigateTo, redirectTo, navigateBack, viewImage }
    for (const i in obj) {
      this[i] = obj[i]
    }
  },

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

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

  },

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

  },

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

  },

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

  },

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

  },
  
  /**
   * 重新搜索学生列表
   */
  blurCtl: function () {
    // const { navIndex, navList } = this.data
    // navList[navIndex]['pageNo'] = 1
    // this.setData({ navList })
    this.getData()
  },

  /**
   * 保存学生姓名
   */
  inputCtl: function (e) {
    const { value } = e.detail
    const { studentName } = this.data
    if (studentName == value) {
      return
    }
    this.setData({ studentName: value })
  },
  /**
    * 获取数据
    */
  getData: function (cb) {
    const continuousFn = { fn: this.getData, param: { ...arguments } }
    const { studentName } = this.data
    AllStudentList({ data: { studentName }, continuousFn }).then(res => {
      const { list = [] } = res.data
      const tempList = (res => {
        for (let i in res) {
          res[i]['index'] = pinyin.go(res[i].studentName).slice(0, 1).toUpperCase()
        }
        return res
      })(res.data.list || [])
      // console.log(this.normalizeSinger(list)) 
      this.setData({ studentList: this.normalizeSinger(list), isLoaded: true})
      this.calculateHeight()
      if (isFn(cb)) cb()
    }).catch(res => {
      this.setData({ isLoaded: true })
      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({
          studentName: item.studentName,
          imgUrl: item.imgUrl,
          school: item.school,
          checkedIn: item.checkedIn,
          grade: item.grade,
          exited: item.exited,
          vipId: item.vipId
        })
      }
      const key = item.index
      if (!map[key]) {
        map[key] = {
          title: key,
          items: []
        }
      }
      map[key].items.push({
        studentName: item.studentName,
        imgUrl: item.imgUrl,
        school: item.school,
        checkedIn: item.checkedIn,
        grade: item.grade,
        exited: item.exited,
        vipId: item.vipId
      })
    })
    // 为了得到有序列表,我们需要处理 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)
    })
    
    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)
  },
})