<template>
  <el-dialog title="选择城市" :append-to-body="true" :visible="isShow" width="650px">
    <div class="third-city-selector">
      <div>
        <el-input v-model="cityFilterTxt" placeholder="输入城市名称（支持城市名称首字母缩写）" prefix-icon="el-icon-search"></el-input>
        <div class="cities-wrap">
          <el-row class="dl-cities cleearfix" v-for="(item,index) in showCites" :key="index">
            <el-col :span="2">
              <span v-text="item.province!=='特别区'?item.province+':':' '"></span>
            </el-col>
            <el-col :span="22" class="city-list">
              <span v-for="(city,cityIdx) in item.cities" :class="{'city-checked':city.showName===checkedCity}" :title="city.searchName"
                @click="changeCity(city,item.province)" :key="cityIdx">{{city.showName}}</span>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="isShow = false">取 消</el-button>
      <el-button type="primary" v-loading="confirmLoading" :disabled="checkedCity === ''" @click="confirm">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
/* global BMap _ */
import util from '@src/common/util.js'
import cities from './cities.json'
export default {
  data() {
    return {
      confirmLoading: false,
      cityFilterTxt: '',
      cities: cities,
      province: '',
      checkedCity: '',
      checkedCitySearch: ''
    }
  },
  props: {
    value: {
      type: String,
      default: ''
    },
    show: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    isShow: {
      get() {
        return this.show
      },
      set(val) {
        this.$emit('update:show', val)
      }
    },
    convertedCity() {
      var cityArr = []
      for (let i = 0, len = this.cities.length; i < len; i++) {
        let province = this.cities[i]
        let cities = this.cities[i].cities
        let cArr = []
        for (let j = 0, lenj = cities.length; j < lenj; j++) {
          let cityName = cities[j]
          if (_.contains(cityName, '|')) {
            cArr.push({
              showName: cityName.split('|')[0],
              searchName: cityName.split('|')[1]
            })
          } else {
            cArr.push({
              showName: cityName,
              searchName: cityName
            })
          }
        }
        cityArr.push({
          province: province.province,
          cities: cArr
        })
      }
      return cityArr
    },
    showCites() {
      if (this.cityFilterTxt === '') {
        return this.convertedCity
      } else {
        let res = []
        this.convertedCity.forEach(item => {
          let filterData = _.filter(item.cities, (city) => {
            return city.showName.indexOf(this.cityFilterTxt) !== -1 || window.util.getSpell(city.showName, true).indexOf(
              this.cityFilterTxt) !== -1
          })
          if (filterData.length > 0) {
            res.push({
              'province': item.province,
              cities: filterData
            })
          }
        })
        return res
      }
    }
  },
  async mounted() {
    this.checkedCity = this.value
    window.initBaiduMapData = this.initBaiduMap
    if (typeof window.BMap === 'undefined') {
      try {
        await util.loadJS('http://api.map.baidu.com/api?v=1.2&callback=initBaiduMapData')
      } catch (e) {
        console.error('http://api.map.baidu.com/api is missing', e.toString())
        return null
      }
    } else {
      this.initBaiduMap()
    }
  },
  methods: {
    initBaiduMap() {
      window.projection = new BMap.MercatorProjection()
      window.setCurrentCity = (d) => {
        if (!d.content || d.content.error === 0) {
          setTimeout(function () {
            alert('请输入正确的中文城市名称')
          }, 0)
        } else {
          var tmpArr = (((d.content.geo).split('|')[2]).split(';')[0]).split(',')
          var b = tmpArr[0]
          var a = tmpArr[1]
          var c = window.projection.pointToLngLat(new BMap.Pixel(b, a))
          var cityObj = {
            province: this.province,
            city: this.checkedCity,
            point: c,
            level: d.content.level || 5
          }
          this.$emit('cityPicked', cityObj)
          this.isShow = false
        }
        this.confirmLoading = false
      }
    },
    changeCity(city, province) {
      this.checkedCity = city.showName
      this.checkedCitySearch = city.searchName
      this.province = province
    },
    confirm() {
      // var cityName = this.province !== '' && this.province !== '直辖市' ? this.province +'省'+ this.checkedCity : this.checkedCity
      var b = encodeURIComponent(this.checkedCitySearch)
      var a = 'http://map.baidu.com/?newmap=1&qt=cur&callback=setCurrentCity&ie=utf-8&wd=' + b + '&oue=1&res=jc'
      util.loadJS(a)
    }
  }
}

</script>
<style>
  .third-city-selector {}

  .cities-wrap {
    margin-top: 10px;
    height: 260px;
    overflow-y: auto;
  }

  .third-city-selector .city-list span {
    margin-right: 8px;
    cursor: pointer;
    color: #00C;
    text-decoration: underline;
    display: inline-block
  }

  .third-city-selector .city-list span.city-checked {
    background: #409EFF;
    color: #fff;
  }

</style>
