<template>
  <view class='content'>
    <scroll-view :scroll-y='true'>
      <item v-for='(item,index) in addressList' :key='index' :item='item'
            @on-checked='onChecked(item)'
            @on-edit='args => goPath(`create?bean=${encodeURIComponent(JSON.stringify(args))}`)'
            @on-delete='args => {handleDelete(args)}' />
      <u-empty v-if='addressList.length === 0' text='暂无数据' margin-top='100' />
    </scroll-view>

    <view class='bottom-button-view'>
      <button class='primary-button' @click.stop='goPath("create")'>+新增地址</button>
    </view>
  </view>
</template>

<script lang='ts' setup>

import Item from './components/item.vue';
import { goPath } from '@/utils';
import { addressDelete, getAddressList } from '@/api/user';
import { useUserStore } from '@/store';

const userStore = useUserStore();

const addressList = ref<{
  name: string,
  mobile: string,
  addr: string,
  status: number,
  defaultstatus: number,
}[]>([]);

onLoad((e) => {
  // fetchAddressList();
});

onShow(() => {
  fetchAddressList();
});

const fetchAddressList = async () => {
  addressList.value = await getAddressList();
};

const handleDelete = async (item: any) => {
  uni.showModal(
    {
      title: '提示',
      content: '确定删除该地址吗？',
      success: async (res) => {
        if(res.confirm) {
          const result = await addressDelete(item?.addrid);
          if(result) {
            await fetchAddressList();
          }
        }
      }
    }
  );
};

const onChecked = (e: any) => {
  const pages = getCurrentPages();
  if(pages.length >= 2 && pages[pages.length - 2].route?.includes('pages/mall/subs/order/order-confirm')) {
    userStore.setDeliveryAddress(e);
    uni.navigateBack();
  }
};
</script>

<style lang='scss' scoped>
</style>
