import CityApi from '../../apis/city'
import {
  getLocation
} from './../../utils/tools'
import states from './json/states'
import cities from './json/cities'
var wxaSortPicker = require('../../utils/wxaSortPicker/wxaSortPicker.js');
import {
  saveHistoryCity,
  loadHistoryCity,
  removeHistoryCity
} from "../../utils/storage";
const app = getApp();
const CHINA = {}
let _animation; // 动画实体
let _animationIndex = 0; // 动画执行次数index（当前执行了多少次）
let _animationIntervalId = -1; // 动画定时任务id，通过setInterval来达到无限旋转，记录id，用于结束定时任务
const _ANIMATION_TIME = 500; // 动画播放一次的时长ms
Page({
  data: {
    allCitys: [],
    resultTip: [],
    alphabet: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'],
    citys: [],
    city: '',
    states: states.states,
    cities: cities.cities,
    all_cities: cities.cities,
    new_cities: [],
    toView: '',
    // state_id: states.states[0].id, //省、州id
    state_id: 0, //省、州id
    apl_posArr: [],
    apl_index: 0,
    b_top: 0,
    sliderHeight: 0,
    historyCity: [],
    clientHeight: 0
  },

  onLoad() {
    this.fetchCityList()
    wx.getSystemInfo({
      success: (res) => {
        // 获取可使用窗口宽度
        let clientHeight = res.windowHeight;
        // 设置高度
        this.setData({
          clientHeight: clientHeight
        }, () => {
          this.set_new_alphabet(this.data.all_cities)

        });
      }
    });
    this.setData({
      city: app.globalData.city,
      historyCity: app.globalData.historyCity
    })
    // var that = this
    //初始化


    // wxaSortPicker.init(this.data.cities, that);
  },
  onReady() {

  },
  onShow() {


    _animation = wx.createAnimation({
      duration: 1000,
      timingFunction: 'linear', // "linear","ease","ease-in","ease-in-out","ease-out","step-start","step-end"
      delay: 0,
      transformOrigin: '50% 50% 0'
    })
  },

  getAplPos() {
    this.setData({
      apl_index: this.data.new_cities[0].alphabetIndex
    })
    wx.createSelectorQuery().select('.select-box').boundingClientRect((res_b) => {
      // let b_top = res_b.top

      this.setData({
        b_top: res_b.top,
        sliderHeight: this.data.clientHeight - res_b.top
      })

      let tab = this.data.new_cities
      let arr = []

      for (let i = 0; i < tab.length; i++) {
        wx.createSelectorQuery().select('#item' + i).boundingClientRect((res_i) => {
          // console.log(res_i)
          tab[i].top = res_i.top - this.data.b_top;
          this.setData({
            new_cities: tab,
            apl_posArr: arr
          })

        }).exec()
      }


    }).exec()


  },
  onPageScroll(e) {
    //创建节点选择器
    let query = wx.createSelectorQuery();
    //选择id
    // let that = this; 
    query.select('.city-side').boundingClientRect((rect) => {
      // console.log(e.detail.scrollTop)
      let scrollTop = e.detail.scrollTop
      let tabs = this.data.new_cities

      for (let i = 0; i < tabs.length; i++) {
        if (scrollTop > tabs[i].top && scrollTop < tabs[i + 1].top) {
          this.setData({
            apl_index: tabs[i].alphabetIndex
          })
          // console.log(tabs[i].alphabetIndex)
        } else if (scrollTop + this.data.b_top + 30 >= tabs[tabs.length - 1].top) {

          console.log('到底了')
          this.setData({
            apl_index: tabs[tabs.length - 1].alphabetIndex
          })
          return
        }
      }

      // console.log()
      // if (e.scrollTop > rect.height - 20) { // 页面上卷高度 大于页面固定按钮位置
      //   that.setData({
      //     fixedInputPhone: true // 显示指定区域
      //   })
      // } else {
      //   that.setData({
      //     fixedInputPhone: false  // 隐藏指定区域
      //   })
      // }
    }).exec();
  },
  getLocation() {

    this.startAnimationInterval()
    this.setData({
      animation: _animation.export()
    })
    getLocation().then(city => {
      this.setData({
        city: city
      })
      this.stopAnimationInterval()
    }).catch(err => {
      this.stopAnimationInterval()
    })
  },

  fetchCityList() {
    return CityApi.getCityList().then(res => {
      const {
        alphabet
      } = this.data
      let showCity = []
      res.data.forEach(item => {
        const index = alphabet.indexOf(item.first_alphabet)
        if (showCity[index]) {
          showCity[index].citys.push(item)
        } else {
          showCity[index] = {
            alphabetIndex: index,
            citys: [item]
          }
        }
      })
      console.log(showCity)
      this.setData({
        citys: showCity.filter(item => item),
        allCitys: res.data
      })
    })
  },
  searchResult(e) {
    const {
      value
    } = e.detail
    let resultTip = []
    if (value) {

      // resultTip = this.data.allCitys.filter(item => item.name.indexOf(value) !== -1)
      resultTip = this.data.all_cities.filter(item => item.name.indexOf(value) !== -1)
    }
    console.log(resultTip)

    this.setData({
      resultTip
    })
  },
  hideResultTip() {
    this.setData({
      resultTip: []
    })
  },
  handleCityClick(e) {
    console.log(e)
    const {
      city
    } = e.currentTarget.dataset
    // app.globalData.city = city.replace('市', '')
    app.globalData.city = city

    this.set_historyCity(city)
    wx.navigateBack()
  },
  selectLocation() {
    // app.globalData.city = '珠海'
    app.globalData.city = this.data.city
    this.set_historyCity(this.data.city)
    wx.navigateBack()
  },
  /**
   * 实现image旋转动画，每次旋转 120*n度
   */
  rotateAni: function (n) {
    _animation.rotate(120 * (n)).step()
    this.setData({
      animation: _animation.export()
    })
  },
  /**
   * 开始旋转
   */
  startAnimationInterval: function () {
    var that = this;
    that.rotateAni(++_animationIndex); // 进行一次旋转
    _animationIntervalId = setInterval(function () {
      that.rotateAni(++_animationIndex);
    }, _ANIMATION_TIME); // 每间隔_ANIMATION_TIME进行一次旋转
  },

  /**
   * 停止旋转
   */
  stopAnimationInterval: function () {
    if (_animationIntervalId > 0) {
      clearInterval(_animationIntervalId);
      _animationIntervalId = 0;
    }
  },
  //选中返回值
  // wxaSortPickerItemTap: function(e){
  //   console.log(e.target.dataset.text);
  //   console.log(e.target.dataset.value);//字符串数组无此字段
  // }
  jumpTo: function (e) {
    // 获取标签元素上自定义的 data-opt 属性的值
    let target = e.currentTarget.dataset.opt;
    let index = e.currentTarget.dataset.index;
    console.log(e)
    this.setData({
      toView: target,
      apl_index: index
    })
  },
  set_new_alphabet(cities) {
    let showCity = []
    const {
      alphabet
    } = this.data
    cities.forEach((item) => {
      const index = alphabet.indexOf(item.FirstLetter)
      if (showCity[index]) {
        showCity[index].citys.push(item)
      } else {
        showCity[index] = {
          alphabetIndex: index,
          citys: [item]
        }
      }
    })
    this.setData({
      new_cities: showCity.filter(item => item),
    }, () => {

      this.getAplPos()

    })
  },
  getCities(e) {
    let {
      id
    } = e.currentTarget.dataset;
    console.log(id)
    let cities = this.data.all_cities.filter(item => id == item.state_id)
    this.setData({
      state_id: id,
      cities: cities,
    }, () => {
      let data = id == 0 ? this.data.all_cities : this.data.cities
      this.set_new_alphabet(data)
      // this.getAplPos()

    })

  },
  set_historyCity(city) {
    console.log(city)
    if (!app.globalData.historyCity.includes(city)) {
      app.globalData.historyCity.push(city)
      saveHistoryCity(app.globalData.historyCity)
      this.setData({
        historyCity: app.globalData.historyCity
      })
    }
  },
  remove_historyCity() {
    removeHistoryCity()
    app.globalData.historyCity = loadHistoryCity() || []
    this.setData({
      historyCity: loadHistoryCity() || []
    })

  }

})