<template>
  <div class="domain">获取微信地址</div>
  <!-- {{address}}----{{openid}} --{{options}}-->
</template>

<script>
import area from "@/utils/app.area.js";
import addres from "@/api/userAddress";
export default {
  data() {
    return {
      address: wx.getStorageSync("sessionid"),
      openid: wx.getStorageSync("openid"),

      options: "",
      weChatInfo: "",
      userAddressReq: {
        provinceCode: "",
        cityCode: "", //需传入城市code
        districtCode: "",
        zipcode: "",
        consignee: "",
        address: "",
        mobilephone: "",
        isDefaultShipping: 0
      },
      areaResult: {
        provinceName: "",
        cityName: "",
        areaName: ""
      },
      areaList: area,
      province_list: area.province_list,
      city_list: area.city_list,
      county_list: area.county_list,
      provinceTwoKey: 0,
      openSetting: false
    };
  },
  onLoad(options) {
    Object.assign(this.$data, this.$options.data());
    this.options = options;
    if(options.sessionid){
      try {
        wx.setStorageSync('sessionid', options.sessionid)
      } catch (e) { }
    }
    console.log("onload");
    this.init();
  },
  onShow() {
    if (this.openSetting) {
      this.openSetting = false;
      this.init();
    }
  },
  methods: {
    init() {
      wx.showLoading({
        title: "加载中"
      });

      let that = this;
      wx.chooseAddress({
        success: function(res) {
          console.log(4);
          that.disposeAddress(res);
        },
        fail: function(res) {
          // chooseAddress:fail auth deny  ---用户拒绝后msg
          // chooseAddress:fail cancel   ---用户点击取消按钮
          console.log(res, "-------------------65",that.options);
          //用户取消
          console.log(5);
          if (res.errMsg.indexOf("cancel") != -1) {
            wx.navigateBack();
          } else {
            that.getSett();
          }
        }
      });
    },
    getSett() {
      let that = this;
      wx.getSetting({
        success(res) {
          if (!res.authSetting["scope.address"]) {
            that.openConfirm();
          } else {
            console.log(2);
            //打开选择地址
            wx.chooseAddress({
              success: function(res) {
                console.log(4);
                that.disposeAddress(res);
              },
              fail: function(res) {
                //用户取消
                console.log(5);
                wx.navigateBack();
              }
            });
          }
        },
        fail(res) {
          console.log("调用失败");
        }
      });
    },
    openConfirm() {
      wx.hideLoading();

      let that = this;
      wx.showModal({
        content: "检测到您没打开通讯地址的权限,是否去设置打开?",
        confirmText: "确认",
        cancelText: "取消",
        success: function(res) {
          console.log(res);
          //点击“确认”时打开设置页面
          if (res.confirm) {
            console.log("用户点击确认");
            wx.openSetting({
              success: res => {
                that.openSetting = true;
              }
            });
          } else {
            console.log("用户点击取消");
            wx.navigateBack();
          }
        },
        fail: function(res) {
          wx.navigateBack();
        }
      });
    },
    disposeAddress(val) {
      if (val) {
        this.weChatInfo = val;
        this.userAddressReq.address = this.weChatInfo.detailInfo;
        this.userAddressReq.zipcode = this.weChatInfo.postalCode;
        this.userAddressReq.consignee = this.weChatInfo.userName;
        this.userAddressReq.mobilephone = this.weChatInfo.telNumber;
        this.areaResult.provinceName = this.weChatInfo.provinceName;
        this.areaResult.cityName = this.weChatInfo.cityName;
        this.areaResult.areaName = this.weChatInfo.countyName;
        // 省code
        if (this.areaResult.provinceName == "内蒙古自治区") {
          this.areaResult.provinceName = "内蒙古";
        }
        if (this.areaResult.provinceName == "广西壮族自治区") {
          this.areaResult.provinceName = "广西";
        }
        if (this.areaResult.provinceName == "西藏自治区") {
          this.areaResult.provinceName = "西藏";
        }
        if (this.areaResult.provinceName == "宁夏回族自治区") {
          this.areaResult.provinceName = "宁夏";
        }
        if (this.areaResult.provinceName == "新疆维吾尔自治区") {
          this.areaResult.provinceName = "新疆";
        }
        Object.keys(this.province_list).forEach(key => {
          if (this.areaResult.provinceName == this.province_list[key]) {
            this.userAddressReq.provinceCode = key;
            this.provinceTwoKey = key.slice(0, 2);
          }
        });
        // 市code
        Object.keys(this.city_list).forEach(key => {
          if (this.areaResult.cityName == this.city_list[key]) {
            if (this.provinceTwoKey == key.slice(0, 2)) {
              this.userAddressReq.cityCode = key;
            }
          }
        });
        // 区code
        Object.keys(this.county_list).forEach(key => {
          if (this.areaResult.areaName == this.county_list[key]) {
            if (this.provinceTwoKey == key.slice(0, 2)) {
              this.userAddressReq.districtCode = key;
            }
          }
        });


        console.log(this.areaResult,this.userAddressReq,'=====')
        //是否直接返回地址信息
        if (this.options.refresh) {
          // this.options.back+=`&wxAddress=${encodeURIComponent(JSON.stringify(this.userAddressReq))}`
          let url=this.options.back;
          url+=encodeURIComponent(`&wxAddress=${JSON.stringify(this.userAddressReq)}`);
          console.log('refresh',url)
          setTimeout(() => {
            wx.reLaunch({
              url: `../index/main?from=address&backpath=${url}`
            });
          }, 200);
        } else {
          this.addAdressRequest();
        }
      }
    },
    addAdressRequest() {
      addres
        .getUserAddressList()
        .then(res => {
          if (res.data.code == 200) {
            let list = res.data.data.list;
            if (!list.length > 0) {
              this.userAddressReq.isDefaultShipping = 1;
            } else {
              this.userAddressReq.isDefaultShipping = 0;
            }
            addres
              .addOrEditAddress(this.userAddressReq)
              .then(res => {
                if (res.data.code == 200) {
                  console.log("!!!!!!!!!!!!!", this.options.back);
                  console.log("微信地址", this.userAddressReq);
                } else {
                }

                wx.showToast({ title: res.data.msg, icon: "none" });
                wx.navigateBack();
              })
              .catch(err => {
                wx.showToast({ title: err, icon: "none" });
                wx.navigateBack();
              });
          } else {
            wx.showToast({ title: res.data.msg, icon: "none" });
            wx.navigateBack();
          }
        })
        .catch(err => {
          wx.showToast({ title: err, icon: "none" });
          wx.navigateBack();
        });
    }
  }
};
</script>

<style>
.domain {
  text-align: center;
  padding-top: 50%;
}
</style>