<template>
  <view class="Mall4j page-address-list">
    <view class="list-box">
      <block
        v-for="(addressItem, addressIndex) in addressList"
        :key="addressIndex"
      >
        <view
          :class="['item', addressItem.isDefault===1?'default-address':'']"
          @tap.stop="onSelectItem(addressItem)"
        >
          <view class="text-box">
            <view class="address">
              <view
                v-if="addressItem.isDefault===1"
                class="default-flag"
              >
                默认
              </view>
              {{ addressItem.province+addressItem.city+addressItem.area+addressItem.addr }}
            </view>
            <view class="name-phone">
              <view class="name">
                {{ addressItem.consignee }}
              </view>
              <view class="phone">
                {{ addressItem.mobile }}
              </view>
            </view>
          </view>
          <view
            class="edit-icon"
            @tap.stop="onToEditAddress(addressItem.addrId)"
          >
            <image src="@/package-user/static/images/edit.png" />
          </view>
        </view>
      </block>
      <!-- 为空或者加载全部 -->
      <empty-all-tips
        v-if="isLoaded"
        :empty-img="4"
        :is-empty="!addressList.length"
        empty-tips="暂无收货地址"
      />
    </view>
    <view class="new-address">
      <view
        :class="['btn', addressList.length===10?'gray':'']"
        @tap="addAddress"
      >
        {{ addressList.length===10?'收货地址已达上限':'新建收货地址' }}
      </view>
    </view>
  </view>
</template>

<script setup>

const addressList = ref([])
const isSelect = ref(false)
const isLoaded = ref(false) // 列表是否加载完毕
onLoad((options) => {
  if (options.selectAddress) {
    isSelect.value = true
  }
})
onShow(() => {
  onGetAddressList()
})

/**
 * 获取用户地址列表
 */
const onGetAddressList = () => {
  isLoaded.value = false
  const params = {
    url: '/tmerclub_user/user_addr/list',
    method: 'GET',
    data: {}
  }
  http.request(params).then(res => {
    isLoaded.value = true
    addressList.value = res.filter(item => item.isDefault).concat(res.filter(item => !item.isDefault))
  })
}

// 去编辑地址
const onToEditAddress = (addrId) => {
  uni.navigateTo({
    url: '/package-user/pages/edit-address/edit-address?addrId=' + addrId
  })
}

// 选择地址
const onSelectItem = (item) => {
  if (isSelect.value) {
    const obj = {
      name: item.consignee,
      userMobile: item.mobile,
      ...item
    }
    uni.setStorageSync('cloudStationAddress', obj)
    uni.navigateBack(1)
  }
}

/**
 * 新建地址
 */
const addAddress = () => {
  if (addressList.value.length === 10) {
    uni.showToast({
      title: '收货地址已达到上限',
      icon: 'none'
    })
  } else {
    uni.navigateTo({
      url: '/package-user/pages/edit-address/edit-address'
    })
  }
}

</script>

<style lang="scss" scoped>
  @use "./address-list.scss";
</style>
