<template>
  <view class="address-page">
    <empty v-if="addressList.length === 0 && !loading" :text="$t('address.empty')" />
    <view class="margin-top-bj">
      <view class="cu-list menu-avatar">
        <view class="cu-item" :class="modalName == 'move-box-' + index ? 'move-cur' : ''"
          v-for="(item, index) in addressList" :key="item.id" @tap="checkAddress(item)" @touchstart="ListTouchStart"
          @touchmove="ListTouchMove" @touchend="ListTouchEnd" :data-target="'move-box-' + index">
          <view class="cu-avatar round lg wanl-bg-orange">{{ item.name.substring(0, 1) }}</view>
          <view class="content">
            <view>
              <text class="wanl-pip margin-right-sm text-lg">{{ item.name }}</text>
              <text class="wanl-gray-light text-sm">{{ item.mobile }}</text>
            </view>
            <view class="text-sm wanl-pip text-cut-2" style="line-height: 1.3">
              <text class="wlIcon wlIcon-dizhi text-red margin-right-xs" v-if="item.default == 1"></text>
              {{ item.province }} {{ item.city }} {{ item.district }} {{ item.address }}
            </view>
          </view>
          <view class="action" @tap.stop="addAddress('edit', item)">
            <text class="wlIcon wlIcon-xiugaioryijian text-xl"></text>
          </view>
          <view class="move">
            <view class="bg-grey" @tap.stop="addAddress('edit', item)">{{ $t('mine.edit') }}</view>
            <view class="bg-red" @tap.stop="delAddress(item.id, index)">{{ $t('mine.delete') }}</view>
          </view>
        </view>
      </view>
    </view>

    <view class="safeAreaBottom"></view>
    <view class="wanlian cu-bar tabbar foot flex flex-direction">
      <button @tap="addAddress('add')" class="cu-btn wanl-bg-orange lg">{{ $t('address.addNew') }}</button>
    </view>
  </view>
</template>

<script>
import { pullAddressList, postAddressDelete, postOrderEditAddress } from '@/features/mall/mall-gateway'
export default {
  data() {
    return {
      source: 0,
      orderId: 0,
      addressList: [],
      modalName: null,
      listTouchStart: 0,
      listTouchDirection: null,
      loading: true
    }
  },
  onLoad(option) {
    this.source = option.source || 0
    this.orderId = option.order_id || 0
    if (!this.$store.state.user.isLogin) {
      uni.showToast({ title: this.$t('common.pleaseLogin'), icon: 'none' })
      setTimeout(() => {
        uni.navigateTo({ url: '/pages/passport/signin' })
      }, 500)
      return
    }
    // this.loadData()
  },
  onShow() {
    // 每次顯示頁面時都刷新數據
    this.loadData()

    
  },
  methods: {
    async loadData() {
      this.loading = true
      try {
        this.addressList = await pullAddressList()
      } catch (e) {
        this.addressList = []
      }
      this.loading = false
    },
    async delAddress(id, key) {
      uni.showModal({
        title: this.$t('common.tip'),
        content: this.$t('address.confirmDelete'),
        success: async (res) => {
          if (res.confirm) {
            this.addressList.splice(key, 1)
            try {
              await postAddressDelete({ id })
            } catch (e) {
              this.loadData()
            }
          }
        }
      })
    },
    checkAddress(item) {
      if (this.source == 1) {
        const pages = getCurrentPages()
        const prevPage = pages[pages.length - 2]
        if (prevPage && prevPage.$vm && prevPage.$vm.loadData) {
          prevPage.$vm.loadData(item.id)
        }
        uni.navigateBack({ delta: 1 })
      } else if (this.source == 2) {
        uni.showModal({
          title: this.$t('common.tip'),
          content: this.$t('address.confirmChange'),
          success: async (res) => {
            if (res.confirm) {
              uni.showLoading({ title: this.$t('common.updating'), mask: true })
              try {
                await postOrderEditAddress({ id: this.orderId, address_id: item.id })
                uni.hideLoading()
                uni.showToast({ title: this.$t('common.updateSuccess'), icon: 'success' })
                uni.$emit('orderAddressUpdated')
                setTimeout(() => {
                  uni.navigateBack({ delta: 1 })
                }, 500)
              } catch (e) {
                uni.hideLoading()
                const msg = (e && e.msg) || (e && e.message) || this.$t('common.updateFailed')
                uni.showToast({ title: msg, icon: 'none', duration: 500 })
              }
            }
          }
        })
      }
    },
    addAddress(type, item) {
      let url = `/pages/user/address/addressManage?type=${type}`
      if (type === 'edit' && item) {
        url += `&data=${JSON.stringify(item)}`
      }
      uni.navigateTo({ url: url })
    },
    ListTouchStart(e) {
      this.listTouchStart = e.touches[0].pageX
    },
    ListTouchMove(e) {
      this.listTouchDirection = e.touches[0].pageX - this.listTouchStart > 0 ? 'right' : 'left'
    },
    ListTouchEnd(e) {
      if (this.listTouchDirection == 'left') {
        this.modalName = e.currentTarget.dataset.target
      } else {
        this.modalName = null
      }
      this.listTouchDirection = null
    },
  }
}
</script>

<style scoped>
.address-page {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 140rpx;
}

.cu-bar.fixed {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  display: flex;
  align-items: center;
  height: 44px;
  padding: 0 20rpx;
  background: #fff;
}

.cu-bar.fixed .action:first-child {
  margin-left: 0;
}

.cu-bar .action text {
  font-size: 40rpx;
  color: #333;
}

.cu-avatar.lg {
  width: 90rpx;
  height: 90rpx;
  font-size: 1.5em;
}

.wanl-bg-orange {
  background-color: #fe6600 !important;
  color: #fff !important;
}

.cu-list.menu-avatar>.cu-item {
  height: 160rpx;
}

.wanlian.cu-bar.tabbar {
  background-color: transparent;
}

.wanlian.cu-bar.tabbar .cu-btn {
  width: calc(100% - 50rpx);
}

.wanlian.cu-bar.tabbar .cu-btn.lg {
  font-size: 32rpx;
  height: 86rpx;
}
</style>