<template>
  <div class="address-list">
    <template v-if="mainData.list.length > 0">
      <a-card
        v-for="item in mainData.list"
        :key="item.userAddressId"
        size="small"
        style="margin-bottom: 10px;"
      >
        <template #title>
          <a-tag v-if="item.defaultAddr" color="processing">默认</a-tag>
          <span>{{item.province}} {{item.city}} {{item.area}} {{item.street}}</span>
        </template>
        <template #extra>
          <a-button v-if="showSelect" size="small" type="link" @click="handleSelect(item)">选择</a-button>
          <a-button v-if="showEdit" size="small" type="link" @click="handleEdit(item)">编辑</a-button>
          <a-popconfirm
            title="是否确定删除?"
            ok-text="确定"
            cancel-text="取消"
            @confirm="handleDelete(item)"
          >
            <a-button size="small" type="link" danger>删除</a-button>
          </a-popconfirm>
        </template>
        <div>{{item.address}}{{item.houseNo}}</div>
        <div>{{item.name}} {{item.phone}}</div>
      </a-card>
      <div v-if="mainData.total > mainData.list.length" style="text-align: center;">
        <a-button type="link" :disabled="mainData.disabled" @click="handleLoadMore">点击查看更多</a-button>
      </div>
    </template>
    <a-empty v-else />
  </div>
</template>

<script setup lang="js">
import { message } from 'ant-design-vue';
import { reactive, onMounted } from 'vue';
import { getAddressList, delAddress } from '@/api/user';
import { useUserStore } from '@/store/user';

const props = defineProps({
  showEdit: {
    type: Boolean,
    default: true
  },
  showSelect: {
    type: Boolean,
    default: false
  }
})

const emits = defineEmits(['select', 'edit', 'delete'])

const userStore = useUserStore();

const mainData = reactive({
  list: [],
  pageNum: 1,
  total: 0,
  disabled: false
})

const fetchAddressList = async () => {
  getAddressList({
    pageNum: mainData.pageNum,
    pageSize: 20,
    userId: userStore.userInfo?.userId || ''
  }).then(res => {
    mainData.list = mainData.list.concat(res.data?.records || []);
    mainData.total = res.data?.total;
  }).finally(() => {
    mainData.disabled = false
  })
}

const handleLoadMore = () => {
  mainData.disabled = true
  mainData.pageNum += 1
  fetchAddressList()
}

const handleSelect = row => emits('select', row)

const handleEdit = row => emits('edit', row)

const handleDelete = row => {
  delAddress({
    userAddressId: row.userAddressId
  }).then(() => {
    mainData.list = []
    mainData.pageNum = 1
    mainData.total = 0
    fetchAddressList()
    message.success('删除成功')
    emits('delete')
  })
}

onMounted(() => {
  fetchAddressList()
})

</script>