var city = require('../../data/city');
var $ = require('../../libs/gdconf.js');
import {
  imgServerUrl
} from '../../config/config.js'
var app = getApp()
Page({
  data: {
    imgServerUrl,
    searchLetter: [],
    showLetter: "",
    winHeight: 0,
    tHeight: 0,
    bHeight: 0,
    startPageY: 0,
    cityList: [],
    cityNameList: [],
    isShowLetter: false,
    scrollTop: 0,
    city: "",
    cityCode: "",
    currcity: "",
    currcityCode: "",
    hotList: [],
    hotCodeList: [],
    inputValue: "",
    searchList: [],
    letter: ''
  },
  onLoad: function (options) {
    var currcity = wx.getStorageSync('currcity') || '无锡'
    var currcityCode = wx.getStorageSync('currcityCode') || '320200';
    var pcity = wx.getStorageSync('city') || '无锡'
    var pcityCode = wx.getStorageSync('cityCode') || '320200';
    // var hotList = ['北京', '上海', '南京', '杭州', '厦门', '南昌', '武汉']
    // var hotCodeList = ['110000', '310000', '320100', '330100', '350200', '360100', '420100'];
    var searchLetter = city.searchLetter;
    var cityList = city.cityList();
    let cityNameList = city.cityNameList();
    this.setData({
      currcity: currcity,
      currcityCode: currcityCode,
      city: pcity,
      cityCode: pcityCode,
      hotList: city.hotCity(),
      // hotCodeList: hotCodeList
    })

    // console.log("cityinfo", cityList);

    var sysInfo = wx.getSystemInfoSync();
    // console.log(sysInfo);
    var winHeight = sysInfo.windowHeight;

    //添加要匹配的字母范围值
    //1、更加屏幕高度设置子元素的高度
    var itemH = (winHeight - 50) / searchLetter.length;
    var tempObj = [];
    for (var i = 0; i < searchLetter.length; i++) {
      var temp = {};
      temp.name = searchLetter[i];
      temp.tHeight = i * itemH;
      temp.bHeight = (i + 1) * itemH;

      tempObj.push(temp)
    }

    this.setData({
      winHeight: winHeight,
      itemH: itemH,
      searchLetter: [{
        name: '#'
      }, {
        name: '热'
      }].concat(tempObj),
      cityList: cityList,
      cityNameList: cityNameList
    })

  },
  onShow() {
    let cityName = wx.getStorageSync('city') || '无锡';
    let cityCode = wx.getStorageSync('cityCode') || '320200';
    this.setData({
      cityName: cityName,
      cityCode: cityCode
    })
  },
  // 返回上级页面
  back() {
    wx.navigateBack({
      delta: 1,
    })
  },
  toView(e) {
    var showLetter = e.currentTarget.dataset.letter;
    let letter = showLetter;
    if (showLetter === '#' || showLetter === '热') {
      this.setData({
        showLetter,
        letter: 'A',
        isShowLetter: true,
      })
    } else {
      this.setData({
        showLetter,
        letter,
        isShowLetter: true,
      })
    }

    setTimeout(() => {
      this.setData({
        showLetter,
        isShowLetter: false,
      })
    }, 1000)
  },
  searchStart: function (e) {
    var showLetter = e.currentTarget.dataset.letter;
    // var pageY = e.touches[0].pageY;
    // this.setScrollTop(this, showLetter);
    // this.nowLetter(pageY, this);
    // this.setData({
    //   showLetter: showLetter,
    //   startPageY: pageY,
    //   isShowLetter: true,
    // })
    if (showLetter === '#' || showLetter === '热') {
      wx.pageScrollTo({
        scrollTop: 0,
        duration: 300,
      })
    }
    this.setData({
      showLetter,
      isShowLetter: true,
    })
  },

  searchMove: function (e) {
    // var pageY = e.touches[0].pageY;
    // var startPageY = this.data.startPageY;
    // var tHeight = this.data.tHeight;
    // var bHeight = this.data.bHeight;
    // var showLetter = 0;
    // // console.log(pageY);
    // if (startPageY - pageY > 0) { //向上移动
    //   if (pageY < tHeight) {
    //     // showLetter=this.mateLetter(pageY,this);
    //     this.nowLetter(pageY, this);
    //   }
    // } else { //向下移动
    //   if (pageY > bHeight) {
    //     // showLetter=this.mateLetter(pageY,this);
    //     this.nowLetter(pageY, this);
    //   }
    // }
    var showLetter = e.currentTarget.dataset.letter;
    if (showLetter === '#' || showLetter === '热') {
      wx.pageScrollTo({
        scrollTop: 0,
        duration: 300,
      })
    }
    this.setData({
      showLetter,
      isShowLetter: true,
    })
  },

  searchEnd: function (e) {
    // console.log(e);
    // var showLetter=e.currentTarget.dataset.letter;
    var that = this;
    setTimeout(function () {
      that.setData({
        isShowLetter: false
      })
    }, 1000)

  },
  nowLetter: function (pageY, that) { //当前选中的信息
    var letterData = this.data.searchLetter;
    var bHeight = 0;
    var tHeight = 0;
    var showLetter = "";
    for (var i = 0; i < letterData.length; i++) {
      if (letterData[i].tHeight <= pageY && pageY <= letterData[i].bHeight) {
        bHeight = letterData[i].bHeight;
        tHeight = letterData[i].tHeight;
        showLetter = letterData[i].name;
        break;
      }
    }
    this.setScrollTop(that, showLetter);
    that.setData({
      bHeight: bHeight,
      tHeight: tHeight,
      showLetter: showLetter,
      startPageY: pageY
    })
  },
  bindScroll: function (e) {
    // console.log(e.detail)
  },
  setScrollTop: function (that, showLetter) {
    var scrollTop = 0;
    var cityList = that.data.cityList;
    var cityCount = 0;
    var initialCount = 0;
    for (var i = 0; i < cityList.length; i++) {
      if (showLetter == cityList[i].firstNameLetter) {
        scrollTop = initialCount * 30 + cityCount * 41;
        break;
      } else {
        initialCount++;
        cityCount += cityList[i].cityInfo.length;
      }
    }
    that.setData({
      scrollTop: scrollTop - 1558
    })
  },
  bindCity: function (e) {
    var city = e.currentTarget.dataset.city;
    this.setData({
      city: city
    })
  },
  chooseHotCity(e) {
    const areaList = this.data.hotList[e.currentTarget.dataset.index].areaList;
    this.wxSortPickerViewItemTap(e, areaList)
  },
  chooseCity(e) {
    const areaList = this.data.cityList[e.currentTarget.dataset.index].cityInfo[e.currentTarget.dataset.idx].areaList;
    this.wxSortPickerViewItemTap(e, areaList)
  },
  chooseSearchCity(e) {
    const areaList = this.data.searchList[e.currentTarget.dataset.index].areaList;
    this.wxSortPickerViewItemTap(e, areaList)
  },
  wxSortPickerViewItemTap(e, areaList) {
    var city = e.target.dataset.text;
    var cityCode = e.target.dataset.code;
    if (city.indexOf("市") != -1) {
      city = city.substring(0, city.lastIndexOf('市'));
    }
    if (city.indexOf("地区") != -1) {
      city = city.substring(0, city.lastIndexOf('地区'));
    }
    if (city.indexOf("自治州") != -1) {
      city = city.substring(0, city.lastIndexOf('自治州'));
    }
    if (city.indexOf("特别行政区") != -1) {
      city = city.substring(0, city.lastIndexOf('特别行政区'));
    }
    wx.setStorageSync('city', city)
    wx.setStorageSync('cityCode', cityCode)
    wx.setStorageSync('areaList', [{
      countryName: '不限',
      countryCode: ''
    }].concat(areaList))
    // wx.setStorageSync('countryCode', areaList[0].countryCode)
    this.setData({
      city: city,
      cityCode: cityCode
    })
    var pages = getCurrentPages();
    var currPage = pages[pages.length - 1]; //当前页面
    var prevPage = pages[pages.length - 2]; //上一个页面
    if (prevPage) {
      prevPage.setData({
        hasLocation1: true
      })
      wx.navigateBack()
    }
  },

  cxgps: function (e) {
    var that = this;
    wx.showLoading({
      title: 'loading',
      mask: true
    });
    wx.getSetting({
      success: function (res) {
        if (!res.authSetting['scope.userLocation']) {
          wx.hideLoading();
          wx.showModal({
            title: '授权提示',
            content: '当前服务需要获取您的位置信息，请确认授权',
            confirmText: '去授权',
            cancelText: '暂不授权',
            success: function (res) {
              if (res.confirm) {
                wx.openSetting();
              } else if (res.cancel) {

              }
            }
          })
        } else {
          $.map.getRegeo({
            success(data) {
              wx.hideLoading();
              var data = data[0],
                cityNmae = data.regeocodeData.addressComponent.city || "无锡",
                cityCode = data.regeocodeData.addressComponent.adcode.substring(0, 4) + "00";
              if (cityNmae.indexOf("市") != -1) {
                cityNmae = cityNmae.substring(0, cityNmae.lastIndexOf('市'));
              }
              let areaList = city.getcityList([cityNmae])[0].areaList;

              that.setData({
                currcity: cityNmae,
                currcityCode: cityCode,
                cityName: cityNmae
              })
              wx.setStorageSync('areaList', [{
                countryName: '不限',
                countryCode: ''
              }].concat(areaList))
              // wx.setStorageSync('countryCode', areaList[0].countryCode)
              wx.setStorageSync('city', cityNmae);
              wx.setStorageSync('cityCode', cityCode);
              wx.setStorageSync('currcity', cityNmae)
              wx.setStorageSync('currcityCode', cityCode)
            }
          })
        }
      }
    });

  },
  bindKeyInput(e) {
    var value = e.detail.value.trim()
    if (value == "") {
      this.setData({
        inputValue: value,
        searchList: []
      })
      return '';
    }
    this.setData({
      inputValue: value
    })
    this.serach(value)
  },
  serach(text) {

    var searchList = this.data.cityNameList.filter(function (name) {
      // console.log(name)
      return name.indexOf(text) !== -1
    })
    var cityList = this.data.cityList;
    var resultList = [];
    for (var k = 0; k < searchList.length; k++) {
      for (var i = 0; i < cityList.length; i++) {
        for (var j = 0; j < cityList[i].cityInfo.length; j++) {
          var resultArr = {};
          if (searchList[k] == cityList[i].cityInfo[j].cityName) {
            // resultArr.cityCode = cityList[i].cityInfo[j].cityCode
            // resultArr.cityName = cityList[i].cityInfo[j].cityName
            resultArr = cityList[i].cityInfo[j]
            resultList.push(resultArr)
          }
        }
      }
    }
    this.setData({
      searchList: resultList
    })
  },
  onError(err) {
    app.aldstat.sendEvent('报错', {
      'err': err
    });
  },
})

//经纬度定位获取站点
function ajaxGes(lat, lng) {
  //TODO:自己的定位接口
  var url = '';
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        resolve(res.data);
      },
      fail: function (err) {
        reject(err);
      }
    })
  })

}