<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '%addressBook.title%',
    navigationBarBackgroundColor: '#fff',
  },
}
</route>

<script lang="ts" setup>
// 必须导入需要用到的页面生命周期（即使在当前页面上没有直接使用到）
// eslint-disable-next-line unused-imports/no-unused-imports
import { onPageScroll, onReachBottom } from '@dcloudio/uni-app'
import useZPaging from 'z-paging/components/z-paging/js/hooks/useZPaging.js'
import { addressDel, addressList } from '@/api/mine'
import { bindingAddress } from '@/api/order'
import { t } from '@/locale'
import { getPageParams, goBack, toPage } from '@/utils/page'
import { toast } from '@/utils/toast'

defineOptions({
  name: 'AddressBook', // 地址簿
})

// 页面参数
const pageParams = ref<any>({})
const isSelectMode = computed(() => pageParams.value.selectMode === true)

// z-paging
const paging = ref(null)
// 类似mixins，如果是页面滚动务必要写这一行，并传入当前ref绑定的paging，注意此处是paging，而非paging.value
useZPaging(paging)
// 搜索结果
const dataList = ref([])
async function queryList(pageNo: number, pageSize: number) {
  try {
    const res = await addressList({
      page: pageNo,
      size: pageSize,
    })
    paging.value.complete(res.data.list)
  }
  catch {
    paging.value.complete(false)
  }
}

// 处理地址项点击
function handleAddressClick(item: any) {
  if (isSelectMode.value) {
    // 选择模式：选择地址并绑定到订单
    selectAddressForOrder(item)
  }
  else {
    // 普通模式：编辑地址
    editAddress(item.id)
  }
}

// 编辑地址
function editAddress(id: any) {
  toPage('/pages/mine/addressBookOperate', { id })
}

// 选择地址并绑定到订单
async function selectAddressForOrder(address: any) {
  try {
    uni.showLoading({
      title: t('addressBook.select.binding'),
    })

    const res = await bindingAddress({
      orderId: pageParams.value.orderId,
      addressId: address.id,
    })

    if (res.code === '200') {
      toast.success(t('addressBook.select.success'))
      // 返回上一页
      goBack()
    }
    else {
      toast.error(res.message || t('addressBook.select.failed'))
    }
  }
  catch (error: any) {
    console.error('Bind address error:', error)
    toast.error(t('addressBook.select.networkError'))
  }
  finally {
    uni.hideLoading()
  }
}

// 删除地址
async function deleteAddress(id: any) {
  try {
    await uni.showLoading({
      title: t('addressBook.delete.deleting'),
    })

    const res = await addressDel({ id })

    if (res.code === '200') {
      toast.success(t('addressBook.delete.success'))
      // 刷新列表
      paging.value.reload()
    }
  }
  catch (error: any) {
    console.error('Delete address error:', error)
  }
  finally {
    uni.hideLoading()
  }
}

// 处理滑动操作
function handleAction(action: string, item: any) {
  if (action === 'del') {
    uni.showModal({
      title: t('addressBook.delete.confirm'),
      content: t('addressBook.delete.message'),
      success: (res) => {
        if (res.confirm) {
          deleteAddress(item.id)
        }
      },
    })
  }
}
onShow(() => {
  paging.value.reload(true)
})
// 页面加载时获取参数
onLoad((options) => {
  pageParams.value = getPageParams(options)
})
</script>

<template>
  <z-paging ref="paging" v-model="dataList" use-page-scroll @query="queryList">
    <view class="py-20rpx">
      <wd-swipe-action v-for="item in dataList" :key="item.id">
        <view class="flex items-center justify-between bg-white px-22rpx py-18rpx" @click="handleAddressClick(item)">
          <view class="flex-1">
            <view class="mb-20rpx flex items-center justify-between text-24rpx">
              <view>
                <text class="mr-20rpx">
                  {{ item.realName }}
                </text>
                <text>{{ item.phone }}</text>
              </view>
              <wd-text v-if="item.isDefault" type="primary" :text="t('addressBook.tag.default')" />
            </view>
            <view class="text-22rpx text-#3A444C">
              {{ [item.province, item.city, item.district, item.street].filter(Boolean).join(', ') }} {{ item.postCode }}
            </view>
          </view>
          <wd-icon name="arrow-right" custom-class="flex-shrink-0 ml-8rpx" color="#7D7D7D" size="24rpx" />
        </view>
        <template #right>
          <view class="action">
            <view class="button" style="background:var(--wot-color-theme);" @click="handleAction('del', item)">
              {{ $t('addressBook.delete.button') }}
            </view>
          </view>
        </template>
      </wd-swipe-action>
    </view>
    <template #bottom>
      <view class="bg-white/60 px-28rpx py-30rpx backdrop-blur-20">
        <wd-button plain block @click="toPage('/pages/mine/addressBookOperate')">
          {{ $t('addressBook.button.add') }}
        </wd-button>
      </view>
    </template>
  </z-paging>
</template>

<style lang="scss" scoped>
.action {
  height: 100%;
  .button {
    display: flex;
    align-items: center;
    padding: 0 24rpx;
    height: 100%;
    color: white;
  }
}
</style>
