let App = getApp();
import api from '../../utils/Api.js'

Page({
  data: {
    list: [],
    default_id: null,
  },

  onLoad: function(options) {
    // 当前页面参数
    this.data.options = options;
  },

  onShow: function() {
    // 获取收货地址列表
    this.getAddressList();
  },

  /**
   * 获取收货地址列表
   */
  getAddressList: function() {
    let _this = this;
    api.address.lists().then(res => {
      if (res.code == 0) {
        _this.setData(res.data);
      } else {
        wx.showToast({
          title: '没有更多了',
          icon: 'none'
        })
      }
    })
  },

  /**
   * 添加新地址
   */
  createAddress: function() {
    wx.navigateTo({
      url: './create'
    });
  },

  /**
   * 编辑地址
   */
  editAddress: function(e) {
    wx.navigateTo({
      url: "./detail?address_id=" + e.currentTarget.dataset.id
    });
  },

  /**
   * 移除收货地址
   */
  removeAddress: function(e) {
    let _this = this,
      address_id = e.currentTarget.dataset.id;
    wx.showModal({
      title: "提示",
      content: "您确定要移除当前收货地址吗?",
      success: function(o) {
        o.confirm && api.address.deleteAddr({
          address_id: address_id
        }).then(res => {
          _this.getAddressList();
        })
      }
    });
  },

  /**
   * 设置为默认地址
   */
  setDefault: function(e) {
    let _this = this,
      address_id = e.detail.value;
    _this.setData({
      default_id: parseInt(address_id)
    });
    api.address.setDefault({
      address_id: address_id
    }).then(res => {
      if (res.code == 0) {
        _this.data.options.from === 'flow' && wx.navigateBack();
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
    return false;
  },

});