const app = getApp();
import { isEmptyCheck } from "../../../utils/commonUtil";
var QQMapWX = require("../../../utils/qqmap-wx-jssdk.min.js");
var qqmapsdk;
// pages/addAddress/index.js
Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		multiSelected: false,
		multiIndex: [0, 0, 0],
		multiIndexTemp: [0, 0, 0],
		// multiArray: [['无脊柱动物', '脊柱动物'], ['扁性动物', '线形动物', '环节动物', '软体动物', '节肢动物'], ['猪肉绦虫', '吸血虫']],
		multiArray: [[], [], []],
		multiArrayTemp: [[], [], []],
		multiArrayRecord: [[], [], []],
		title: "添加地址",
		btnLoading: false,
		address: {
			contacts: "",
			contactsTel: "",
		},
		addressClassify: "",
		addressStr: "",
		recordId: "",
		locationObj: {
			provinceName: "",
			cityName: "",
			districtName: "",
		},
		// provinceId: '',
		// cityId: '',
		// districtId: '',
  },
  
  delAddress:function(e){
    var that = this;
    // var record = e.currentTarget.dataset.record;
    // console.log(record);

    wx.showModal({
      title: '提示',
      content: `确定要删除该地址吗？`,
      cancelColor:"#666666",
			confirmColor: "#ff4400",
      success (res) {
        if (res.confirm) {
          console.log('用户点击确定')

          wx.request({
              url: app.globalData.ip + "/user/address/deleteUserAddress",
              method: "POST",
              header: app.globalData.headers,
              data: {
                id: that.data.recordId
              },
              success: function(res) {
                console.log(res);
                wx.showToast({
                  title: '删除成功',
                  icon: 'success',
                  duration: 2000,
                 
                })
                setTimeout(()=>{
                  wx.navigateBack({
                    delta: -1,
                  })
                },2000)
            
              }

          });

        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
	getProvinceByPid: function () {
		var that = this;
		wx.request({
			url: app.globalData.ip + "/city/getProvince",
			data: {},
			header: app.globalData.headers,
			method: "POST",
			success: function (res) {
				console.log(res);
				if (res.data.status == 200) {
					that.data.multiArrayRecord[0] = [{ id: -1, name: "请选择" }].concat(res.data.data);

					var nameArray = ["请选择"];
					res.data.data.forEach((item, index) => {
						nameArray.push(item.name);
					});
					that.data.multiArrayTemp[0] = nameArray;
					that.setData({
						multiArrayTemp: that.data.multiArrayTemp,
					});

					//如果有省市回显处理
					if (app.isNotEmptyCheck(that.data.address.provinceId) && app.isNotEmptyCheck(that.data.address.cityId) && app.isNotEmptyCheck(that.data.address.districtId)) {
						that.data.multiArrayRecord[0].forEach((item, index) => {
							if (item.id == that.data.address.provinceId) {
								that.data.multiIndex[0] = index;
							}
						});

						that.setData({
							multiArray: that.data.multiArrayTemp,
							multiIndex: that.data.multiIndex,
							multiIndexTemp: that.data.multiIndex,
						});

						that.getCityByPid2(1, that.data.address.provinceId);
					}
				} else {
					app.showTips(that, res.data.msg);
				}
			},
		});
	},
	bindMultiPickerChange: function (e) {
		console.log("picker发送选择改变，携带值为", e.detail.value);
		var that = this;
		var multiSelected = false;
		if (e.detail.value[0] > 0 && e.detail.value[1] > 0 && e.detail.value[2] > 0) {
			multiSelected = true;
		}

		this.setData({
			multiIndex: e.detail.value,
			multiSelected: multiSelected,
			multiArray: that.data.multiArrayTemp,
		});
	},
	bindMultiPickerColumnChange: function (e) {
		console.log("修改的列为", e.detail.column, "，值为", e.detail.value);
		var that = this;
		if (e.detail.column == 0) {
			that.data.multiIndexTemp[0] = e.detail.value;
			that.data.multiIndexTemp[1] = 0;
			that.data.multiIndexTemp[2] = 0;
			that.data.multiArrayTemp[1] = [];
			that.data.multiArrayTemp[2] = [];
			this.setData({
				multiIndexTemp: that.data.multiIndexTemp,
				multiArrayTemp: that.data.multiArrayTemp,
			});
		}
		if (e.detail.column < 2) {
			this.getCityByPid(e.detail.column, e.detail.value);
		}
	},

	getCityByPid: function (column, value) {
		var that = this;
		// var pid = that.data.userDetails.bankProvinceCode;
		console.log(that.data.multiArrayRecord[column][value]);
		var pid = that.data.multiArrayRecord[column][value].id;
		wx.request({
			url: app.globalData.ip + "/city/getCityByPid",
			data: {
				pid: pid,
			},
			header: app.globalData.headers,
			method: "POST",
			success: function (res) {
				console.log(res);
				if (res.data.status == 200) {
					that.data.multiArrayRecord[column + 1] = [{ id: -1, name: "请选择" }].concat(res.data.data);

					var nameArray = ["请选择"];
					res.data.data.forEach((item, index) => {
						nameArray.push(item.name);
					});
					that.data.multiArrayTemp[column + 1] = nameArray;

					that.setData({
						multiArrayTemp: that.data.multiArrayTemp,
					});
				} else {
					app.showTips(that, res.data.msg);
				}
			},
		});
	},

	getCityByPid2: function (column, pid) {
		var that = this;
		wx.request({
			url: app.globalData.ip + "/city/getCityByPid",
			data: {
				pid: pid,
			},
			header: app.globalData.headers,
			method: "POST",
			success: function (res) {
				console.log(res);
				if (res.data.status == 200) {
					that.data.multiArrayRecord[column] = [{ id: -1, name: "请选择" }].concat(res.data.data);

					var nameArray = ["请选择"];
					res.data.data.forEach((item, index) => {
						nameArray.push(item.name);
					});
					that.data.multiArrayTemp[column] = nameArray;

					that.data.multiArrayRecord[column].forEach((item, index) => {
						if (column == 1 && item.id == that.data.address.cityId) {
							that.data.multiIndex[column] = index;
						} else if (column == 2 && item.id == that.data.address.districtId) {
							that.data.multiIndex[column] = index;
						}
					});

					that.setData({
						multiArray: that.data.multiArrayTemp,
						multiArrayTemp: that.data.multiArrayTemp,
						multiIndex: that.data.multiIndex,
						multiIndexTemp: that.data.multiIndex,
					});

					if (column == 1) {
						that.getCityByPid2(2, that.data.address.cityId);
					}
				} else {
					app.showTips(that, res.data.msg);
				}
			},
		});
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		console.log(options);
		if (!isEmptyCheck(options.id)) {
			this.data.recordId = options.id;
      this.data.title = "修改地址";
      this.setData({
        recordId:options.id
      })

			this.getDetail();
		} else {
			this.getProvinceByPid();
		}

		wx.setNavigationBarTitle({
			title: this.data.title,
		});
		qqmapsdk = new QQMapWX({
			key: "5PTBZ-YI7C6-MZGS3-ES7QN-4T5O2-EJFVR",
		});
		console.log(123);
	},
	selectAddressClassify: function (e) {
		var that = this;

		var classify = e.currentTarget.dataset.classify;
		console.log(classify);

		that.setData({
			addressClassify: classify,
		});
	},
	getDetail() {
		var that = this;

		wx.request({
			url: app.globalData.ip + "/user/address/getUserAddressDetail?id=" + that.data.recordId,
			method: "GET",
			header: app.globalData.headers,
			data: {},
			success: function (res) {
				console.log(res);

				if (app.isNotEmptyCheck(res.data.data)) {
					that.setData({
						address: res.data.data,
						addressClassify: res.data.data.classify,
						addressStr: res.data.data.address,
					});
					if (app.isNotEmptyCheck(res.data.data.provinceId) && app.isNotEmptyCheck(res.data.data.cityId) && app.isNotEmptyCheck(res.data.data.districtId)) {
						that.setData({
							multiSelected: true,
						});
					}
					that.getProvinceByPid();
				}
			},
		});
	},
	onSubmit(e) {
		console.log(e);

		var that = this;

		that.setData({
			btnLoading: true,
		});

		if (app.isEmptyCheck(e.detail.value.contacts)) {
			wx.showToast({
				icon: "none",
				title: "请输入姓名",
				duration: 3000,
			});

			that.setData({
				btnLoading: false,
			});
			return;
		}

		var myreg = /^[1][3456789][0-9]{9}$/;
		if (!myreg.test(e.detail.value.contactsTel) || e.detail.value.contactsTel == "") {
			wx.showToast({
				icon: "none",
				title: "请输入正确手机号",
				duration: 3000,
			});

			that.setData({
				btnLoading: false,
			});
			return;
		}
		// if (that.data.multiIndex[0] == 0 || that.data.multiIndex[1] == 0 || that.data.multiIndex[2] == 0) {
		// 	wx.showToast({
		// 		icon: "none",
		// 		title: "请选择详细地区",
		// 		duration: 3000,
		// 	});

		// 	that.setData({
		// 		btnLoading: false,
		// 	});
		// 	return;
		// }

		if (!e.detail.value.address) {
			wx.showToast({
				icon: "none",
				title: "请输入详细地址",
				duration: 3000,
			});

			that.setData({
				btnLoading: false,
			});
			return;
		}
		// if (app.isEmptyCheck(that.data.addressClassify)) {
		// 	wx.showToast({
		// 		icon: "none",
		// 		title: "请选择标签",
		// 		duration: 3000,
		// 	});

		// 	that.setData({
		// 		btnLoading: false,
		// 	});
		// 	return;
		// }

		var formData = e.detail.value;
		formData["id"] = that.data.recordId;
		formData["classify"] = that.data.addressClassify;

		if (that.data.locationObj.provinceName) {
			// formData["provinceId"] = that.data.multiArrayRecord[0][that.data.multiIndex[0]].id;
			// formData["cityId"] = that.data.multiArrayRecord[1][that.data.multiIndex[1]].id;
			// formData["districtId"] = that.data.multiArrayRecord[2][that.data.multiIndex[2]].id;
			formData["provinceName"] = that.data.locationObj.provinceName;
			formData["cityName"] = that.data.locationObj.cityName;
			formData["districtName"] = that.data.locationObj.districtName;
		} else {
			wx.showToast({
				icon: "none",
				title: "请选择地区",
				duration: 3000,
			});
		}

		console.log(formData);

		that.setData({
			btnLoading: false,
		});

		wx.request({
			url: app.globalData.ip + "/user/address/addOrUpdateUserAddress",
			method: "POST",
			header: app.globalData.headers,
			data: formData,
			success: function (res) {
				console.log(res);

				if (res.data.status == 200) {
					wx.navigateBack({
						delta: 1,
					});
				} else {
					wx.showToast({
						icon: "none",
						title: res.data.msg,
						duration: 2000,
					});

					that.setData({
						btnLoading: false,
					});
				}
			},
		});
	},

	chooseMap: function () {
		var that = this;
		console.log("1111111");
		// wx.chooseLocation({
		wx.chooseLocation({
			success: function (res) {
				console.log("res", res);
				that.data.addressStr = res.name;
				qqmapsdk.reverseGeocoder({
					location: `${res.latitude},${res.longitude}`,
					success: function (res) {
						console.log(res.result);
						let address = res.result.address_component;
						that.data.addressStr = `${address.province} ${address.city} ${address.district} ` + that.data.addressStr;
						that.setData({
							addressStr: that.data.addressStr,
							locationObj: {
								provinceName: res.result.address_component.province,
								cityName: res.result.address_component.city,
								districtName: res.result.address_component.district,
							},
						});
					},
					fail: function (res) {
						console.log(res);
					},
				});
			},
			fail: function (e) {
				console.log(e);
			},
		});
	},
	goAddAddress: function () {
		wx.navigateTo({
			url: "/pages/addressBook/index",
		});
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function () {},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function () {},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage1: function () {},
});
