<template>
  <div class="position-address">
    <!-- 顶部搜索 -->
    <div class="search-address">
      <div class="left">
        <div
          class="btn-city-pick"
          @click="toCityPick"
        >
          <div class="city-name">{{districtName ? districtName : cityChange}}</div>
          <div class="icon-arraw-bottom"></div>
        </div>
      </div>
      <div class="right">
        <search-input
          placeholder="请输入收货地址"
          :searchBtnShow="false"
          @on-change="keywordChange"
          :focus="false"
        ></search-input>
      </div>
    </div>
    <!-- 列表 -->
    <div
      class="near-address"
      v-if="nearPois.length > 0 && !keyword "
    >
      <!-- 我的收货地址 -->
      <div v-if="showMine && isLogin && isShowShop">
        <div
          class="address-label"
          v-if="addressList.length"
        >
          <div class="icon-home"></div>
          <div class="label-text">我的收货地址</div>
        </div>
        <div
          v-for="item in addressListFilter"
          :key="item.id"
          @click="pickAddress(item)"
        >
        <!-- @click.native="pickAddress(item)" -->
          <AddressItem
            :title="item.address"
            :address="item.consigneeName + ' ' + item.consigneeMobile"
            :distance="item.distance"
          ></AddressItem>
        </div>

        <!-- #ifndef MP-TOUTIAO -->
        <!-- 新增地址 -->
        <div
          v-if="iSExistWeixinApp"
          class="add-newAddress"
          @click="toCreateAddress"
        >
          <div class="add">新增地址</div>
          <div class="right-aw"></div>
        </div>
        <!-- #endif -->
        
      </div>

      <!-- 附近地址 -->
      <div class="address-label">
        <div class="icon-position"></div>
        <div class="label-text">附近地址</div>
      </div>
      <div
        v-for="item in nearPois"
        :key="item.id"
        @click="pickAddress(item)"
      >
      <!--  @click.native="pickAddress(item)" -->
        <AddressItem
          :title="item.title"
          :address="item.address"
          :distance="item.distance"
        ></AddressItem>
      </div>
    </div>
    <!-- 搜索地址 -->
    <div
      class="search-list"
      v-if="keyword"
    >
      <div
        v-for="item in searchPois"
        :key="item.id"
        @click="pickAddress(item)"
      >
      <!-- @click.native="pickAddress(item)" -->
        <AddressItem
          :title="item.title"
          :address="item.address"
          :distance="item.distance"
        ></AddressItem>
      </div>
    </div>
    <!-- loading -->
    <ZyLoading></ZyLoading>
  </div>
</template>

<script>
import ZyLoading from '@/components/Loading/loading'
import SearchInput from '@/components/commonCmp/search-input/search-input.vue'
import { mapGetters, mapMutations } from 'vuex'
import { toast,errToast,jumpPage } from '@/utils/uniapi.js'
import AddressItem from '../addressCmp/address-item.vue'
import  {getDistance}  from '@/utils/index.js'
import {store} from "@/store";
import apiAddress from '@/apis/address'
export default {
  components: {
    ZyLoading, SearchInput, AddressItem
  },
  data() {
    return {
      keyword: '',
      nearPois: [],
      searchPois: [],
      choisePosition: false,
      showMine: true,
      type: '',
      curLat:0,
      curLng:0,
      addressListFilter: [],
      districtName:''
    }
  },
  mounted() {
    this.curLat = this.location.lat
    this.curLng = this.location.lat
  },
  computed: {
    ...mapGetters({
      location: 'indexPage/myLocation',
      vuexPois: 'indexPage/pois',
      cityChange: 'indexPage/cityChange',
      addressList: 'addressVue/addressList',
      isLogin: 'login/isLogin',
      isShowShop: "isShowShop",
      iSExistWeixinApp: "login/iSExistWeixinApp",
    })
  },
  onLoad(query) {
    if (this.addressList && this.addressList.length > 0) {
      this.addressList.sort(this.ArraySort('distance'))
    }
    this.choisePosition = query.choisePosition

    this.districtName = query.districtName || ""
    if (query.showMine) {
      this.showMine = query.showMine && JSON.parse(query.showMine)
    }
    this.type = query.type
  },
  async created() {
    try {
      this.showLoad()
      this.addressListFilter = this.addressList.filter(item => item.detailAddress !== '自提订单：详细地址')
      let latitude = this.location.lat
      let longitude = this.location.lng

      let pois = this.vuexPois && this.vuexPois.length > 0 ? this.vuexPois : (await apiAddress.posToCity({ latitude, longitude, extensions: 1 })).pois

      this.nearPois = pois.map(item => ({
        id: item.id,
        title: item.name,
        address: item.address,
        location: {
          lat: item.location.split(',')[1],
          lng: item.location.split(',')[0]
        },
        distance: getDistance(item.location.split(',')[1],item.location.split(',')[0])
      }))
      this.nearPois.sort(this.ArraySort('distance'))

     
    } catch (e) {
      console.error(e)
      this.nearPois = []
      errToast(e)
    } finally {
      this.hideLoad()
    }
  },
  methods: {
    ...mapMutations({
      storeWaybillAd: 'addressVue/storeWaybillAd',
      updateMapPick: 'waybill/updateMapPick'
    }),
    //新增地址
    toCreateAddress() {
      jumpPage('navigateTo','/pagesAddress/create-address/index')
    },
    async keywordChange(val) {
      try {
        this.keyword = val.trim()
        if (!this.keyword) return false
        this.searchPois = []
        let res = await apiAddress.getSuggestion(this.keyword, this.districtName ? this.districtName : this.cityChange)
        
        res.pois.map((item)=>{
           this.searchPois.push({
            id: item.id,
            title: item.name,
            address: item.address,
            location: {
              lat: item.location.split(',')[1],
              lng: item.location.split(',')[0]
            },
            distance:getDistance(item.location.split(',')[1],item.location.split(',')[0])
          })
        })
        this.searchPois.sort(this.ArraySort('distance'))
      } catch (e) {
        console.error(e)
        this.searchPois = []
        errToast(e)
      }
    },

    // 跳转到城市选择
    toCityPick() {
      if(!this.showMine) return toast('禁止选择城市')
      jumpPage('navigateTo','/pagesAddress/pick-city/index')
    },
    // 选择地址
    pickAddress(address) {
      console.log('选中一个地址信息',address)
      if (this.choisePosition) {
        // console.log(address)
        let reLocation = {}
        if (address.hasOwnProperty('location')) {
          // 其他地址
          reLocation.lat = address.location.lat
          reLocation.lng = address.location.lng
          reLocation.address = address.title
        } else {
          // 我的收货地址
          reLocation.lat = address.lat
          reLocation.lng = address.lng
          reLocation.address = address.address
          this.storeWaybillAd([address])
        }
         // 设置重新加载标识
        store.commit('indexPage/indexNeedReload', true)   // 首页
        store.commit('goodPage/changeIsNeedReload', true) // 分类
        store.commit('cartPage/cartNeedReload', true)    // 购物车
        
        // 存储切换的坐标地址
        store.commit('indexPage/saveReLocation', reLocation)   
      } else {
        if (this.type === 'waybill') {
          // 处理物流地址选择
          this.updateMapPick(address)
        } else {
          this.$store.commit('addressVue/setCurPickAddress', address)
        }
      }
      uni.navigateBack({ delta: 1 })
    },
    // 数组排序
    ArraySort(property){
      return function (a,b){
        let value1=a[property]
        let value2=b[property]
        return value1-value2
      }
    }
  }
}
</script>

<style lang="scss">
@import "./position-address.scss";
</style>