/**
 * 地址管理
 */
const api = require('../../utils/api');

Page({
  data: {
    addressList: [],
    loading: true
  },

  onShow() {
    this.loadAddressList();
  },

  async loadAddressList() {
    this.setData({ loading: true });
    try {
      const list = await api.getAddressList();
      this.setData({ addressList: Array.isArray(list) ? list : [] });
    } catch (err) {
      console.error('地址加载失败:', err);
    } finally {
      this.setData({ loading: false });
    }
  },

  onAdd() {
    wx.navigateTo({ url: '/pages/address-form/address-form' });
  },

  onEdit(e) {
    const address = e.currentTarget.dataset.address;
    wx.navigateTo({
      url: '/pages/address-form/address-form?address=' + encodeURIComponent(JSON.stringify(address))
    });
  },

  async onSetDefault(e) {
    const id = e.currentTarget.dataset.id;
    try {
      await api.setDefaultAddress(id);
      wx.showToast({ title: '已设为默认', icon: 'success' });
      this.loadAddressList();
    } catch (err) {}
  },

  async onDelete(e) {
    const id = e.currentTarget.dataset.id;
    wx.showModal({
      title: '确认删除',
      content: '确定删除该地址？',
      success: async (res) => {
        if (res.confirm) {
          try {
            await api.deleteAddress(id);
            wx.showToast({ title: '已删除', icon: 'success' });
            this.loadAddressList();
          } catch (err) {}
        }
      }
    });
  }
});
