import CityApi from '../../apis/city'
import { getLocation } from './../../utils/tools'
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: ''
  },
  onLoad() {
    this.fetchCityList()
  },
  onReady() {
  },
  onShow () {
    this.setData({
      city: app.globalData.city
    })
    _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'
    })
  },
  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)
    }
    this.setData({
      resultTip 
    })
  },
  hideResultTip () {
    this.setData({
      resultTip: []
    })
  },
  handleCityClick (e) {
    console.log(e)
    const { city } = e.currentTarget.dataset
    app.globalData.city = city.replace('市', '')
    wx.navigateBack()
  },
  selectLocation () {
    app.globalData.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;
    }
  },
})
