/**
 * 地址编辑页面
 * 支持新增和编辑已有地址
 */
const api = require('../../utils/api');

Page({
  data: {
    id: null,  // 编辑时传入
    name: '',
    phone: '',
    province: '',
    city: '',
    district: '',
    detail: '',
    zipCode: '',
    regionText: '',
    isDefault: false,
    saving: false
  },

  onLoad(options) {
    if (options.address) {
      try {
        const addr = JSON.parse(decodeURIComponent(options.address));
        this.setData({
          id: addr.id,
          name: addr.name || '',
          phone: addr.phone || '',
          province: addr.province || '',
          city: addr.city || '',
          district: addr.district || '',
          detail: addr.detail || '',
          zipCode: addr.zip_code || '',
          isDefault: !!addr.is_default,
          regionText: [addr.province, addr.city, addr.district].filter(Boolean).join(' ')
        });
      } catch(e) {}
    }
  },

  onNameInput(e) { this.setData({ name: e.detail.value }); },
  onPhoneInput(e) { this.setData({ phone: e.detail.value }); },
  onDetailInput(e) { this.setData({ detail: e.detail.value }); },
  onZipInput(e) { this.setData({ zipCode: e.detail.value }); },
  onDefaultChange(e) { this.setData({ isDefault: e.detail.value }); },

  onRegionPicker() {
    wx.chooseLocation({
      success: (res) => {
        // 解析地址
        const address = res.address || '';
        this.setData({
          regionText: res.name ? (address + ' ' + res.name) : address,
          province: address.split(/省|市/)[0] || '',
          city: '',
          district: ''
        });
      },
      fail: () => {
        // 如果chooseLocation失败（未配置key等），回退到手动输入
        wx.showToast({ title: '请手动输入地址', icon: 'none' });
      }
    });
  },

  async onSave() {
    const { name, phone, province, city, district, detail, zipCode, isDefault, id, saving } = this.data;
    if (saving) return;
    
    if (!name) { wx.showToast({ title: '请输入收件人', icon: 'none' }); return; }
    if (!/^1\d{10}$/.test(phone)) { wx.showToast({ title: '手机号格式不正确', icon: 'none' }); return; }
    if (!detail) { wx.showToast({ title: '请输入详细地址', icon: 'none' }); return; }

    this.setData({ saving: true });
    try {
      await api.saveAddress({
        id: id || undefined,
        name, phone, province, city, district, detail, zip_code: zipCode, is_default: isDefault
      });
      wx.showToast({ title: '保存成功', icon: 'success' });
      wx.navigateBack();
    } catch (err) {
      // handled
    } finally {
      this.setData({ saving: false });
    }
  }
});
