<template>
  <view>
    <uni-search-bar v-model="keyword" @input="input">
    </uni-search-bar>
    <template v-if="!showSearchResults">
      <uni-notice-bar show-get-more more-text="完善 >" :text="addressesName" @getmore="getMore" />
      <uni-section title="我的收货地址">
        <template v-slot:right>
          <span style="color: red;" @click="addAddress">新增地址</span>
        </template>
        <uni-list :border="false">
          <uni-list-item v-for="item in myAddresses" :key="item.id">
            <template v-slot:header>
              <view @click="chooseLocation(item)">
                <view>
                  <uni-tag text="默认" type="warning" v-if="item.defaultAddress===1" />
                  <text style="margin-left: 10rpx;">{{item.address}}</text>
                </view>
                <view style="margin-top: 20rpx;font-size: 28rpx;color:#555">
                  <text>{{item.consignee}}</text>
                  <text style="margin-left: 10rpx;">{{item.phone}}</text>
                </view>
              </view>
            </template>
            <template v-slot:footer>
              <uni-icons type="paperplane-filled" v-if="item.latitude===lat&&item.longitude==lng"></uni-icons>
              <uni-icons type="gear" @click="editAddress(item)" style="margin-left: 18rpx"></uni-icons>
            </template>
          </uni-list-item>
        </uni-list>
      </uni-section>
      <uni-section title="附近地址">
        <uni-list :border="false">
          <uni-list-item v-for="item in aroundAddresses" :key="item.id">
            <template v-slot:header>
              <view @click="chooseLocation(item)" style="max-width: 70%;">
                <uni-icons type="paperplane-filled" v-if="item.location===location"></uni-icons>
                <text style="margin-left: 10rpx;">{{item.name}}</text>
              </view>
            </template>
            <template v-slot:footer>
              <span style="color: red;" v-if="item.location===location" @click="pickLoaction"><uni-icons
                  type="location"></uni-icons>重新定位</span>
            </template>
          </uni-list-item>
        </uni-list>
      </uni-section>
    </template>

    <template v-else>
      <uni-list :border="false">
        <uni-list-item v-for="item in searchResults" :key="item.id">
          <template v-slot:header>
            <view @click="chooseLocation(item)" style="max-width: 70%;">
              <text style="margin-left: 10rpx;">{{item.name}}</text>
            </view>
          </template>
        </uni-list-item>
      </uni-list>
    </template>
  </view>
</template>

<script>
  import uniSection from '../../components/uni-section/uni-section'
  let getPlaceTimer = null
  export default {
    components: {
      uniSection
    },
    data() {
      return {
        keyword: '',
        lat: null,
        lng: null,
        myAddresses: [],
        aroundAddresses: [],
        addressesName: null,
        searchResults: []
      }
    },
    computed: {
      location() {
        return this.lng + ',' + this.lat
      },
      showSearchResults() {
        return !!this.keyword
      }
    },
    onShow() {
      const {
        lat,
        lng,
        addressesName
      } = uni.getStorageSync('addresses')
      this.addressesName = addressesName
      this.lat = lat
      this.lng = lng
      this.getMyAddresses()
      this.getAroundAddresses()
    },
    methods: {
      getMore() {
        const activeItem = this.myAddresses.find(item =>
            item.latitude === this.lat && item.longitude === this.lng
        );
        const {
          lat,
          lng,
          addressesName
        } = uni.getStorageSync('addresses')
        const item = {
          address: addressesName,
          latitude: lat,
          longitude: lng,
          province: activeItem ? activeItem.province : '',
          city: activeItem ? activeItem.city : '',
          county: activeItem ? activeItem.county : '',
          phone: activeItem ? activeItem.phone : undefined,
          consignee: activeItem ? activeItem.consignee : undefined,
          defaultAddress: activeItem ? activeItem.defaultAddress : undefined,
          id: activeItem ? activeItem.id : undefined // 如果没有匹配项，id 为 undefined
        }
        if(activeItem){
          uni.navigateTo({
            url: '/pages/address/create?type=edit&data=' + JSON.stringify(item)
          })
        }else {
          uni.navigateTo({
            url: '/pages/address/create?type=add&data=' + JSON.stringify(item)
          })
        }

      },
      addAddress() {
        uni.navigateTo({
          url: '/pages/address/create?type=add'
        })
      },
      editAddress(item) {
        uni.navigateTo({
          url: '/pages/address/create?type=edit&data=' + JSON.stringify(item)
        })
      },
      getMyAddresses() {
        this.$api.request('get', 'address/app/getAllAddress').then(res => {
          this.myAddresses = res.data
        })
      },
      getAroundAddresses() {
        var that = this;
        this.$api.request('get', 'https://restapi.amap.com/v5/place/around', {
          key: that.$api.defConfig().mapKey,
          location: this.location
        }).then(res => {
          this.aroundAddresses = res.pois
        })
      },
      getRecentlyStorage(lat, lng, name) {
        this.$api.request('get', 'storage/position/getRecentlyStorage', {
          lng,
          lat
        }).then(res => {
          // 设置距离值
          let addressesInfo = {};
          addressesInfo.lng = lng;
          addressesInfo.lat = lat;
          addressesInfo.distance = res.data.distance;
          addressesInfo.addressesName = name
          uni.setStorageSync('addresses', addressesInfo);
          this.$store.commit('setStorage', res.data.id)

          this.$store.commit('setStorageObj', {
            businessStartTime: res.data.businessStartTime,
            businessState: res.data.businessState,
            businessStopTime: res.data.businessStopTime,
            deliveryStartTime: res.data.deliveryStartTime,
            deliveryStopTime: res.data.deliveryStopTime,
            haveStorage: res.data.haveStorage,
            id: res.data.id
          })
          uni.switchTab({
            url: '/pages/index/index'
          })
        })
      },
      chooseLocation({
        latitude,
        longitude,
        address,
        location,
        name
      }) {
        if (location) {
          const _ = location.split(',');
          latitude = _[1]
          longitude = _[0]
          address = name
        }
        this.getRecentlyStorage(latitude, longitude, address)
      },
      pickLoaction() {
        const that = this
        uni.chooseLocation({
          success({
            errMsg,
            latitude,
            longitude,
            name
          }) {
            // address: "福建省福州市闽侯县甘蔗交通路2号"
            // errMsg: "chooseLocation:ok"
            // latitude: 26.150201
            // longitude: 119.13138
            // name: "中共闽侯县委员会"
            if (errMsg === "chooseLocation:ok") {
              that.getRecentlyStorage(latitude, longitude, name)
            }
          }
        })
      },
      getPlace() {
        if (getPlaceTimer) {
          clearTimeout(getPlaceTimer)
          getPlaceTimer = null
        }
        getPlaceTimer = setTimeout(() => {
          var that = this;
          this.$api.request('get', 'https://restapi.amap.com/v5/place/text', {
            key: that.$api.defConfig().mapKey,
            keywords: this.keyword
          }).then(res => {
            this.searchResults = res.pois
          })
        }, 500)
      },
      input() {
        this.getPlace()
      }
    }
  }
</script>

<style lang="scss" scoped>
  ::v-deep .uni-list-item__container {
    justify-content: space-between;
    align-items: center;
  }
</style>