<template lang="html">
<div class="citylist1 content-block ">
  <Scroll class="citylist change-height" :data="city" ref="cityList" :listenScroll="listenScroll" @scroll="scroll" :probetype="probetype">
  <div style="font-size:13px">
    <div v-for="(item,index) in city" class="allCity" ref="listGroup" :key="index">
      <div class="letter-title">
        <span class="letter">{{item.initial}}</span>
        <div class="title-line"></div>
      </div>
      <ul>
        <li v-for="(city, index) in item.list" @click="selectItem(city, index)" :key="city.id" :class="{'city-active':index === currentCity}">
            {{city.name}}
        </li>
      </ul>
    </div>
  </div>
  </Scroll>
    <div class="list-shortcut" @touchstart="onShortcutTouchStart">
    <ul>
      <li class="starCity"></li>
      <li v-for="(item,index) in city" :class="{'item-active': index === currentIndex,'item': index !== currentIndex}" :data-index="index" :key="index">
        {{item.initial}}
      </li>
    </ul>
  </div>
  </div>
</template>
<script type="text/javascript" src="https://cdn.bakeroad.com/cityPicker/data/originalTmapData.js"/>
<script>
import Scroll from './m-scroll'
const TITLE_HEIGHT = 20
export default {
  components: {
    Scroll
  },
  data () {
    return {
      city: [],
      scrollY: -1,
      currentIndex: 0,
      diff: -1,
      currentCity: -1
    }
  },
  props: ['inited'],
  created () {
    this.touch = {}
    this.listenScroll = true
    this.listenHeight = []
    this.probetype = 3
  },
  computed: {
    fixedTitle () {
      if (this.scrollY > 0) {
        return ''
      }
      return this.city[this.currentIndex] ? this.city[this.currentIndex].initial : ''
    }
  },
  mounted () {
    let that = this
    setTimeout(() => {
      this.city = that.formatData(that.data_letter_sort(that.cityData(mapData), 'pinyin'))
      this.$emit('cityData', this.city)
    }, 30)
  },
  methods: {
    scroll (pos) {
      this.scrollY = pos.y
    },
    onShortcutTouchStart (e) {
      let anchorIndex = this.getData(e.target, 'index')
      let firstTouch = e.touches[0]
      this.touch.y1 = firstTouch.pageY
      this.touch.anchorIndex = anchorIndex
      // this.$refs.singerlist.scrollToElement(this.$refs.listGroup[anchorIndex],0);
      this._scrollTo(anchorIndex)
    },
    _scrollTo (index) {
      if (!index && index !== 0) {
        return
      }
      // 点击右边字母跳到指定位置并高亮
      this.scrollY = -this.listenHeight[index] - 1
      this.$refs.cityList.scrollToElement(this.$refs.listGroup[index], 0)
    },
    _calculateHeight () {
      this.listenHeight = []
      const list = this.$refs.listGroup
      let height = 0
      this.listenHeight.push(height)
      for (let i = 0; i < list.length; i++) {
        let item = list[i]
        height += item.clientHeight
        this.listenHeight.push(height)
      }
    },
    selectItem (item, index) {
      this.currentCity = index
      this.$emit('selectItem', item)
    },
    data_letter_sort (data, field) {
      // var letter_reg = /^[A-Z]$/
      var list = new Array()
      for (var i = 0; i < data.length; i++) {
        // 添加 # 分组，用来 存放 首字母不能 转为 大写英文的 数据
        //      list['#'] = new Array();
        // 首字母 转 大写英文
        var letter = (data[i][field][0]).substr(0, 1).toUpperCase()
        // 是否 大写 英文 字母
        //      if (!letter_reg.test(letter)) {
        //          letter = '#';
        //      }
        // 创建 字母 分组
        if (!(letter in list)) {
          list[letter] = new Array()
        }
        // 字母 分组 添加 数据
        list[letter].push(data[i])
      }
      // 转换 格式 进行 排序；
      var resault = new Array()
      for (var key in list) {
        resault.push({
          letter: key,
          list: list[key]
        })
      }
      resault.sort(function (x, y) {
        return x.letter.charCodeAt(0) - y.letter.charCodeAt(0)
      })
      // 转换 数据 格式
      var json_sort = {}
      for (var j = 0; j < resault.length; j++) {
        json_sort[resault[j].letter] = resault[j].list
      }
      return json_sort
    },
    formatData (data) {
      var result = []
      for(var key in data){
        var formatItem = {}
        formatItem['initial'] = key
        formatItem['list'] = data[key]
        result.push(formatItem)
      }
      return result
    },
    cityData (mapData) {
      let city = []
      let provinceCity = [
        {
          'id': '110100',
          'name': '北京',
          'fullname': '北京市',
          'pinyin': [
            'bei',
            'jing'
          ],
          'location': {
            'lat': 39.90469,
            'lng': 116.40717
          },
          'cidx': [
            0,
            15
          ]
        },
        {
          'id': '120100',
          'name': '天津',
          'fullname': '天津市',
          'pinyin': [
            'tian',
            'jin'
          ],
          'location': {
            'lat': 39.0851,
            'lng': 117.19937
          },
          'cidx': [
            16,
            31
          ]
        },
        {
          'id': '310100',
          'name': '上海',
          'fullname': '上海市',
          'pinyin': [
            'shang',
            'hai'
          ],
          'location': {
            'lat': 31.23037,
            'lng': 121.4737
          },
          'cidx': [
            102,
            117
          ]
        },
        {
          'id': '500100',
          'name': '重庆市辖区',
          'fullname': '重庆市辖区',
          'pinyin': [
            'chong',
            'qing'
          ],
          'location': {
            'lat': 29.56471,
            'lng': 106.55073
          },
          'cidx': [
            297,
            334
          ]
        },
        {
          'id': '500200',
          'name': '重庆市辖县',
          'fullname': '重庆市辖县',
          'pinyin': [
            'chong',
            'qing'
          ],
          'location': {
            'lat': 29.56471,
            'lng': 106.55073
          },
          'cidx': [
            297,
            334
          ]
        }
      ]
      provinceCity.forEach(function (item,index) {
        city.push(item)
      })
      mapData.result[1].forEach(function (item,index) {
        let provinceCode = item.id.substr(0, 2)
        if (provinceCode !== '11' && provinceCode !== '12' && provinceCode !== '31' && provinceCode !== '50') {
          city.push(item)
        }
      })
      return city
    },
    getData:function (el, name, val) {
      const prefix = 'data-'
      if (val) {
        return el.setAttribute(prefix + name, val)
      }
      return el.getAttribute(prefix + name)
    }
  },
  watch: {
    city () {
      setTimeout(() => {
        this._calculateHeight()
      }, 70)
    },
    scrollY (newY) {
      // 滚动到中间部分
      const listenHeight = this.listenHeight
      // 滚动到头部以上
      if (newY >= -25) {
        this.currentIndex = 0
        return
      }
      for (let i = 0; i < listenHeight.length - 1; i++) {
        let height1 = listenHeight[i]
        let height2 = listenHeight[i + 1]
        // 如果没在下限，且在height1和height2之间
        if (-newY >= height1 && -newY <= height2) {
          this.currentIndex = i
          this.diff = height2 + newY
          return
        }
      }
    },
    diff (newVal) {
      let fixedTop = (newVal > 0 && newVal < TITLE_HEIGHT) ? newVal - TITLE_HEIGHT : 0
      if (this.fixedTop === fixedTop) {
        return
      }
      this.fixedTop = fixedTop
      // this.$refs.fixed.style.transform = `translate3d(0,${fixedTop}px,0)`
    }
  }
}
</script>
<style lang="less" scoped>
  .list-shortcut{
    position: fixed;
    z-index: 3000;
    right: 20px;
    top: 7.7rem;
    transform: translateY(-43%);
    width: 20px;
    border-radius: 2px;
    text-align: center;
    ul{
      list-style: none
    }
    .item{
      padding: .1rem 0;
      line-height: 12px;
      color: #9A9A9A;
    }
    .item-active{
      border: 1px solid #F9AF76;
      background-color: #FFBD95;
      color: #fff;
      line-height: 15px;
    }
  }
  .citylist1{
    position: fixed;
    top: 4.1rem;
    width: 100%;
    bottom: 0;
    background: #fff;
  }
  .citylist{
    position: absolute;
    top: 15px;
    width: 100%;
    bottom: 0;
    overflow: hidden;
    background: #fff;
    .allCity{
      ul{
        list-style: none;
        li{
          width: 100%;
          margin: 0 auto;
          height: 33px;
          line-height: 33px;
        }
      }
      .city-active{
        color:#b1b1b1;
      }
      h2{
        background:#f6f4f4;
        padding-left: .34rem;
      }
    }

    .letter-title{
      width: 100%;
      height: 40px;
      line-height: 40px;
    }
    .letter{
      display: inline-block;
      width: 7%;
      height: 25px;
      line-height: 25px;
      text-align: center;
      background-color: #F7F7F7;
      color: #9A9A9A;
      border-radius: 50px;
      vertical-align: text-top;
    }
    .title-line{
      display: inline-block;
      box-sizing: border-box;
      width:90%;
      height: 1px;
      background-color: #F7F7F7;
    }
  }
  @media screen and (max-width: 400px) {
    .citylist1 {
      top: 4.2rem;
    }
  }
</style>
