import * as Api from './service';
Component({
  props: {
    componentData: {}
  },
  data: {
    addressData: null,
    addressDefault: {
      name: '',
      mobile: '',
      region: [],
      regionCode: [],
      address: '',
      isDefault: false,
      latitude: '',
      longitude: '',
      addressNumber: ''
    } // 收货地址信息

  },

  didMount() {
    const {
      type = '',
      ...rest
    } = this.props.componentData;
    const {
      addressDefault
    } = this.data;
    this.setData({
      addressData: type === 'edit' ? rest : addressDefault
    });
  },

  methods: {
    async onComplete(e) {
      const params = {
        userPhone: e.mobile || '',
        userName: e.name || '',
        detail: e.address || '',
        longitude: e.longitude || '',
        latitude: e.latitude || '',
        status: e.isDefault || false,
        addressNumber: e.addressNumber || '',
        provinceName: e.region[0] || '',
        provinceCode: e.regionCode[0] || '',
        cityName: e.region[1] || '',
        cityCode: e.regionCode[1] || '',
        districtName: e.region[2] || '',
        districtCode: e.regionCode[2] || ''
      };

      try {
        const {
          type = ''
        } = this.props.componentData;
        const {
          addressData
        } = this.data;

        if (type === 'edit') {
          await Api.updateAddressApi({ ...params,
            id: addressData.id
          });
        } else {
          await Api.updateAddressApi(params);
        }

        my.navigateBack();
      } catch (err) {
        my.showToast({
          content: err.msg || '更新失败'
        });
      }
    }

  }
});