<template>
  <div class="search">
    <div style="overflow:hidden">
      <div class="address-input">
        <div class="switch-city" @click='selectCity' v-if="region">
            <span class="region-name">{{region}}</span>
            <img class="icon-img" src="../assets/img/dropdowncity.png">
            <span>|</span>
        </div>
        <div class="switch-city" @click='selectCity' v-else>
            请选择
            <img class="icon-img" src="../assets/img/dropdowncity.png">
            <span>|</span>
        </div>
        <div class="search-input">
            <img class="icon-img" src="../assets/img/search-icon.png">
            <input v-model="locationKeyword" type="text" placeholder="请输入收货地址" @focus="searchFocus" @keyup="searchInputing" @blur="flodHistory"/>
        </div>
      </div>
    </div>

      <!-- //历史记录 -->
  <div class="sentTo content-block" v-if='showHistory'>
      <div>
        <div class="sentTo-title">
          <img class="icon-img" src="../assets/img/history.png"><span>历史记录</span>
        </div>
        <span class="title-feature" @click="clearHistory"><img class="icon-img" src="../assets/img/empty.png">清空</span>
      </div>
      <div class="search-item" v-show='searchList.length > 0' v-for='item in searchList' :key='item.id' @click="transferPosition(item)">
        <p class="search-item-name">{{item.title}}</p>
        <p class="search-item-detail">{{item.address}}</p>
      </div>
  </div>
  <!-- 搜索地址 -->
  <div class="sentTo content-block" v-if="showResult">
      <div>
        <div class="sentTo-title">
          <img class="icon-img" src="../assets/img/result.png"><span>搜索结果</span>
        </div>

      </div>
      <div class="search-item" v-for="site in nearbySite" :key="site.id" @click="transferPosition(site)">
          <div class="search-item-detail-inline">
              <p class="search-item-name">{{site.title}}</p>
              <p class="search-item-detail">{{site.address}}</p>
          </div>
          <div class="search-item-distance">
              {{formatDistance(site._distance)}}
          </div>
      </div>
  </div>
   <!-- 城市选择弹窗 -->
  <popup v-model="cityPicker" height="100%">
    <div class="cityPicker" v-if="cityPicker">
      <CityPicker @cityChecked="cityChecked" :currentCity = "positionObj"></CityPicker>
    </div>
  </popup>
  </div>
</template>
<script>
import {Popup} from 'vux'
import CityPicker from 'city-picker-bake'
import {mapKey, TMap, TmapSuggestion} from '@/assets/js/common'
var lodash = require('lodash')
export default {
  name: 'searchLocation',
  props: ['keyword'],
  watch: {
    keyword (val) {
      this.locationKeyword = val
      this.getResult()
      this.showHistory = false
      this.showResult = true
    }
  },
  components: {Popup, CityPicker},
  data () {
    return {
      showHistory: true,
      showResult: false,
      locationKeyword: '',
      region: this.localStorage.getItem('currentCity'),
      nearbySite: [],
      geolocation: {},
      coordinate: this.localStorage.getItem('getPosition'),
      previous: '',
      cityPicker: false, // 城市选择弹窗
      searchList: [],
      positionObj: JSON.parse(this.localStorage.getItem('positionObj'))
    }
  },
  mounted () {
    this.previous = this.$route.query.previous
    this.locationKeyword = this.$route.query.keyword
    var that = this
    that.$nextTick(() => {
      this.loadSearchHistoryData()
    })
    console.log(this.positionObj)
  },
  computed: {
    reverseSearchList () {
      return this.searchList.reverse()
    }
  },
  methods: {
    selectCity () {
      this.cityPicker = true
    },
    cityChecked (val) {
      this.region = val.name
      this.cityPicker = false
    },
    getStore (data) {
      this.deliveryInfo.storeName = data.name
      this.deliveryInfo.targetStoreId = data.storeId
    },
    searchFocus: function () {
      // this.showHistory = false
      // this.showResult = true
      this.getResult()
    },
    searchInputing: lodash.debounce(function () {
      this.showHistory = false
      this.showResult = true
      this.getResult()
    }, 500),
    // 清除历史数据
    clearHistory () {
      this.localStorage.removeItem('SearchHistoryOfAddress')
      this.searchList = []
    },
    // 加载历史数据
    loadSearchHistoryData () {
      let searchHistory = this.localStorage.getItem('SearchHistoryOfAddress')
      if (searchHistory && searchHistory.length > 0) {
        this.searchList = JSON.parse(searchHistory)
      }
    },
    // 添加搜索记录
    addSearchHistory (searchObj) {
      let that = this
      let searchHistory = that.searchList
      let isNewSearch = true // 标志是不是已经有过的搜索
      if (searchHistory && searchHistory.length > 0) {
        searchHistory.forEach(function (item) {
          if (item.id === searchObj.id) {
            isNewSearch = false
          }
        })
      }
      if (isNewSearch) {
        // 只保留最近10次搜索
        if (searchHistory.length >= 5) {
          searchHistory.pop()// 弹出第一个
        }
        searchHistory.unshift(searchObj)
        that.localStorage.setItem('SearchHistoryOfAddress', JSON.stringify(searchHistory))
      }
    },
    getResult: function () {
      var that = this
      if (this.locationKeyword) {
        let region = (this.region === '重庆市辖区' || this.region === '重庆市辖县') ? '重庆' : this.region
        console.log(this.locationKeyword, that.coordinate, region)
        TmapSuggestion(this.locationKeyword, that.coordinate, region, function (res) {
          res.data.sort((a, b) => a._distance - b._distance)
          that.nearbySite = res.data
        }, function () {})
      }
    },
    flodHistory: function () {
    },
    showPosition: function (position) {
      this.coordinate = position.lat + ',' + position.lng
    },
    errCallback: function (error) {

    },
    formatDistance: function (meter) {
      var kilometer = (meter / 1000).toFixed(2)
      return kilometer + 'km'
    },
    transferPosition: function (site) {
      let info = {
        province: site.province,
        district: site.district,
        city: site.city,
        latitude: site.location.lat,
        longitude: site.location.lng,
        districtTitle: site.title,
        adcode: site.adcode,
        previous: 'searchLocation'
      }
      this.addSearchHistory(site)
      this.$emit('select', info)
    }
  }
}
</script>
<style scoped>
.search{
  height: 93%;
  background-color: #F9F9F9;
  font-size: 13px
}
.address-input{
    box-sizing: border-box;
    width: 95%;
    height: 30px;
    margin: 15px auto;
    background-color: #F1F1F1;
    border-radius: 20px;
    padding: 0 10px;
}
.switch-city{
    display: inline-block;
    width: 77px;
    height: 100%;
    line-height: 0.833333rem;
    color: #6E6E6E;
    vertical-align: top;
}
.switch-city span{
  color: #DADADA;
}
.switch-city .region-name{
    display: inline-block;
    width: 51px;
    overflow: hidden;
    color: #6E6E6E;
    vertical-align: middle;
    white-space: nowrap;
        text-overflow: ellipsis;
}
.search-input{
  display: inline-block;
  width: 70%;
  height: 100%;
  line-height: 32px;
}
.search-input input{
  border: none;
  outline: none;
  width: 88%;
  height: 27px;
  color: #6E6E6E;
  vertical-align: top;
  background-color: #F1F1F1;
}
.search-item{
  width: 100%;
  height: 60px;
  margin-top: 15px;
}
.search-item-name{
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.search-item-distance{
  display: inline-block;
  width: 20%;
  color: #6E6E6E;
  line-height: 60px;
  vertical-align: bottom;
  text-align: right;
}
.sentTo-title{
  display: inline-block;
  font-size: 12px;
  color: #8F8F8F;
}
.icon-img{
  width: 13px;
  height: 13px;
  margin-right: 5px;
}
.sentTo-title{
  display: inline-block;
  font-size: 12px;
  color: #8F8F8F;
}

.search-item-detail{
  font-size: 12px;
  margin-top: 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #6E6E6E;
}
.distance{
  float: right;
  color: #6E6E6E;
}
.search-item-detail-inline{
    display: inline-block;
  width: 76%;
}
</style>
