// packageH/newDraw/components/yz_addressList/yz_addressList.js
const app = getApp();
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    show: {
      value: false,
      type: Boolean
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    addressData: [],
    form: {},
    create: true,
    popAddAddress: false,
    addressName: {},
    districtVal: '',
    strShow: false,
    provinceData: [],
    pickerValue: [0, 0, 0],
  },
  pageLifetimes: {
    show: function () {
      this.getAddress();
      //加载地址数据初始化
      this._initAddressInfo();
    },
  },

  /**
   * 组件的方法列表
   */
  methods: {
    //获取收货地址
    getAddress() {
      this.addressData = [];
      let that = this;
      let urlStr = app.getNetAddresss("member.member-address.index");
      app._getNetWork({
        url: urlStr,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            let defaultAddress = res.data;
            defaultAddress = res.data.filter(function (item) {
              return item.isdefault === 1;
            });

            that.setData({
              popupSpecs: true,
              addressData: res.data,
              defaultAddress: defaultAddress
            });
          } else {
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });
    },
    goLocation_ro(){
      wx.showToast({
        icon: 'none',
        title: 'error::\packageH\newDraw\components\yz_addressList\yz_addressList.js',
        duration: 1500
      });
    },
    selectAddress(e) {
      let item = e.currentTarget.dataset.addr;
      this.triggerEvent('confirm', item);
    },
    editAddress(e) {
      console.log(e);
      let loc = e.currentTarget.dataset.item;
      this.setData({
        "form.address_id": this.data.defaultAddress[0].id,
        "form.username": this.data.defaultAddress[0].username,
        "form.mobile": this.data.defaultAddress[0].mobile,
        "form.province": this.data.defaultAddress[0].province,
        "form.city": this.data.defaultAddress[0].city,
        "form.district": this.data.defaultAddress[0].district,
        "form.address": this.data.defaultAddress[0].address,
        "form.street": this.data.defaultAddress[0].street,
        "form.isDefault": this.data.defaultAddress[0].isDefault === 0 ? false : true,
        'is_point.lng': loc.longitude,
        'is_point.lat': loc.latitude,
      });
      this.setData({
        create: false,
        popAddAddress: true,
      });
      this._getStreet(this.data.defaultAddress[0].district_id);
      this.setData({
        addressName: this.data.form.province + " " + this.data.form.city + " " + this.data.form.district

      });

    },
    //关闭增加地址
    popAddressClose() {
      this.setData({
        popAddAddress: false
      });
    },
    //收件人输入绑定
    usernameinp: function (e) {
      let nameval = e.detail.value;
      this.setData({
        "form.username": nameval
      });
    },
    //联系电话输入绑定
    mobileinp: function (e) {
      let mobileval = e.detail.value;
      this.setData({
        "form.mobile": mobileval
      });
    },
    //默认地址开关值绑定
    isDefaultChange: function (e) {
      let isDefault = e.detail;
      this.setData({
        "form.isDefault": isDefault
      });
    },
    //详细地址绑定输入
    addressinp: function (e) {
      let addressval = e.detail.value;
      this.setData({
        "form.address": addressval
      });
    },
    // 关闭选择收货地址
    _closeDateLw: function () {
      this.setData({
        openDateLw: false
      });
    },
    //地址选择器数据初始化
    _initAddressInfo: function () {
      var that = this;
      var _keyName = 'provinceData';
      wx.getStorage({
        key: _keyName,
        success: function (res) {
          console.log("地址信息准备就绪");
          that._getProvinceData();
        },
        fail: function (res) {
          console.log("省fail");
          app._getNetWork({
            url: app.getNetAddresss("member.member-address.address"),
            success: function (res) {
              var response = res.data;
              var province = response.data.province;
              var city = response.data.city;
              var district = response.data.district;
              wx.setStorage({
                key: 'provinceData',
                data: province
              });
              wx.setStorage({
                key: 'cityData',
                data: city
              });
              wx.setStorage({
                key: 'districtData',
                data: district
              });
              that._initAddressInfo();
            },
            fail: function (res) {},
            state: true
          });
        }
      });
    },
    // 读取省key
    _getProvinceData: function () {
      var that = this;
      var _keyName = 'provinceData';
      wx.getStorage({
        key: _keyName,
        success: function (res) {
          // console.log("省读取成功", res.data);
          that.setData({
            provinceData: res.data
          });
          that.setData({
            "selectAddressData[0].name": res.data[that.data.pickerValue[0]].areaname,
            "selectAddressData[0].id": res.data[that.data.pickerValue[0]].id,
            "selectAddressData[0].index": that.data.pickerValue[0]
          });
          that._getCityData();
        }
      });
    },
    // 读取城市key，筛选城市data
    _getCityData: function () {
      var _data = this.data.selectAddressData[0];
      // console.log("城市", "_data", _data);
      var that = this;
      var _keyName = 'cityData';
      wx.getStorage({
        key: _keyName,
        success: function (res) {
          // console.log("城市读取成功", res);

          var _json = [];
          for (var i = 0; i < res.data.length; i++) {
            if (res.data[i].parentid == _data.id) {
              _json.push(res.data[i]);
            }
          }
          // console.log("城市数据筛选", _json);
          that.setData({
            cityData: _json
          });
          that.setData({
            "selectAddressData[1].name": _json[that.data.pickerValue[1]].areaname,
            "selectAddressData[1].id": _json[that.data.pickerValue[1]].id,
            "selectAddressData[1].index": that.data.pickerValue[1]
          });
          that._getDistrictData();
        }
      });
    },
    // 读取地区key，筛选地区data
    _getDistrictData: function () {
      var _data = this.data.selectAddressData[1];
      // console.log("地区", "_data", _data)
      var that = this;
      var _keyName = 'districtData';
      wx.getStorage({
        key: _keyName,
        success: function (res) {
          console.log("地区读取成功");
          var _json = [];
          for (var i = 0; i < res.data.length; i++) {
            if (res.data[i].parentid == _data.id) {
              _json.push(res.data[i]);
            }
          }
          // console.log("地区数据筛选", _json);
          that.setData({
            districtData: _json
          });
          // console.log("districtData", _json);
          that.setData({
            "selectAddressData[2].name": _json[that.data.pickerValue[2]].areaname,
            "selectAddressData[2].id": _json[that.data.pickerValue[2]].id,
            "selectAddressData[2].index": that.data.pickerValue[2]
          });
          // console.log("over", that.data.selectAddressData);
        }
      });
    },
    //打开地址选择器
    openDateLwtbtn: function () {
      this.setData({
        openDateLw: true
      });
    },
    // 收货地址滚动事件
    bindChange: function (e) {
      var val = e.detail.value;
      if (this.data.pickerValue[0] != val[0]) {
        val[1] = 0;
        val[2] = 0;
      }
      if (this.data.pickerValue[1] != val[1]) {
        val[2] = 0;
      }
      this.setData({
        "pickerValue[0]": val[0],
        "pickerValue[1]": val[1],
        "pickerValue[2]": val[2]
      });
      this._initAddressInfo();
    },
    // 确定选择收货地址
    _okAddress: function () {
      let seleData = this.data.selectAddressData;
      this.setData({
        "form.street": "",
        "districtVal": "",
        "addressName": seleData[0].name + ' ' + seleData[1].name + ' ' + seleData[2].name,
        "form.province": seleData[0].name,
        "form.city": seleData[1].name,
        "form.district": seleData[2].name
      });
      this._getStreet(seleData[2].id);
      this._closeDateLw();
    },
    //获取街道
    _getStreet(param) {
      let that = this;
      let urlStr = app.getNetAddresss("member.memberAddress.street");
      urlStr += "&district_id=" + param;
      app._getNetWork({
        url: urlStr,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1 && !app._isTextEmpty(res.data)) {
            if (!app._isTextEmpty(res.data) && res.data.length > 0) {
              that.setData({
                districtVal: res.data,
                strShow: true
              });
            } else {
              that.setData({
                strShow: false
              });
            }
          } else {
            that.setData({
              strShow: false
            });
          }
        },
        fail: function (res) {
          that.setData({
            strShow: false
          });
          console.log(res);
        }
      });
    },
    streetChoose() {
      if (this.data.is_region == 1 && app._isTextEmpty(this.data.addressName)) {
        wx.showToast({
          icon: 'none',
          title: '请先选择所在地区',
          duration: 1500
        });
      } else {
        this.setData({
          streetShow: true,
          opren: false
        });
      }
    },
    //关闭选择街道弹窗
    streetClose: function () {
      this.setData({
        streetShow: false,
        opren: true
      });
    },
    //选择街道
    streetConfirm(e) {
      let strname = e.target.dataset.strname;
      this.setData({
        "form.street": strname,
        "streetShow": false,
        opren: true
      });
    },
    //增加地址
    appendAddress(e) {
      let that = this;
      let apptype = e.currentTarget.dataset.apptype;
      if (app._isTextEmpty(this.data.form.username)) {
        wx.showToast({
          icon: 'none',
          title: "请输入收货人姓名",
          duration: 1500
        });
        return;
      }
      if (app._isTextEmpty(this.data.form.mobile)) {
        wx.showToast({
          icon: 'none',
          title: "请输入联系电话",
          duration: 1500
        });
        return;
      }
      if (!/^[0-9]{1,}$/.test(this.data.form.mobile)) {
        wx.showToast({
          icon: 'none',
          title: "请输入联系电话",
          duration: 1500
        });
        return;
      }
      if (this.data.is_region == 1 && app._isTextEmpty(this.data.addressName)) {
        wx.showToast({
          icon: 'none',
          title: "请选择所在区域",
          duration: 1500
        });
        return;
      }
      if (this.data.is_region == 1 && this.data.strShow && app._isTextEmpty(this.data.form.street)) {
        wx.showToast({
          icon: 'none',
          title: "请选择所在街道",
          duration: 1500
        });
        return;
      }
      if (app._isTextEmpty(this.data.form.address)) {
        wx.showToast({
          icon: 'none',
          title: "请输入详细地址",
          duration: 1500
        });
        return;
      }
      let json = {};
      json = {
        username: this.data.form.username,
        mobile: this.data.form.mobile,
        province: this.data.form.province,
        city: this.data.form.city,
        district: this.data.form.district,
        address: this.data.form.address,
        isdefault: this.data.form.isDefault ? 1 : 0,
        address_id: this.data.form.address_id
      };
      if (this.data.is_point) {
        json.longitude = this.data.is_point.lng;
        json.latitude = this.data.is_point.lat;
      }
      if (this.data.strShow) {
        json.street = this.data.form.street;
      }
      let urlStr = '';
      if (apptype === 'update') {
        urlStr = app.getNetAddresss('member.member-address.update');
      } else {
        urlStr = app.getNetAddresss('member.member-address.store');
      }
      app._postNetWork({
        url: urlStr,
        showToastIn: false,
        data: json,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
            that.triggerEvent('confirm', that.data.form);
            that.popAddressClose();
            that.setData({
              "form.username": '',
              "form.mobile": '',
              "form.province": '',
              "form.city": '',
              "form.district": '',
              "form.street": '',
              "form.address": '',
              "form.isDefault": false,
              addressName: '',
            });
          } else {
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
        },
        fail: function (res) {

        }
      });
    },
    onCloseAdd(){
      this.setData({
        show: false
      });
    },
    //跳转到新增地址
    addAddress() {
      this.getIsOpenAddress();
      //新增地址 本地处理
      this.showAddAddress();
    },
    getIsOpenAddress() {
      var that = this;
      let urlStr = app.getNetAddresss("member.member-address.is-region");
      app._getNetWork({
        url: urlStr,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1 && !app._isTextEmpty(res.data)) {
            that.setData({
              is_region: res.data.is_region
            });
          } else {
            console.log(res.msg);
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });
    },
    //显示增加地址
    showAddAddress() {
      this.setData({
        "form.username": '',
        "form.mobile": '',
        "form.province": '',
        "form.city": '',
        "form.district": '',
        "form.street": '',
        "form.address": '',
        "form.isDefault": false,
        addressName: '',
        popAddAddress: true,
        create: true
      });
    },
  }
});