// pages/realName/index.js
let app = getApp();
Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		level: 1,
		isFinish: false,
		user: {
			sex: "",
			sexStr: "",
			IDCard: "",
			realName: "",
			idcardImgFrontm: "", // 正面mini照
			idcardImgFront: "", // 正面标准照
			idcardImgBackm: "", // 反面mini照
			idcardImgBack: "", // 反面标准照
		},
		canFinish: false,
		switch1Checked: false,

		sexArr: [
			{
				text: "男",
				id: 1,
			},
			{
				text: "女",
				id: 2,
			},
		],
	},
	switch1Change: function (e) {
		console.log("radio发生change事件，携带value值为：", e.detail.value);
		console.log(e.detail.value);

		var check = this.data.switch1Checked;
		if (check) {
			this.data.switch1Checked = false;
			console.log("已取消选中");
			wx.showToast({
				title: "请先阅读并同意《服务协议》及《隐私政策》",
				icon: "none",
				duration: 2000,
			});
		} else {
			this.data.switch1Checked = true;
			console.log("已选中");
		}
		this.setData({
			switch1Checked: this.data.switch1Checked,
		});

		// if(!e.detail.value){

		// }
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad(options) {
		// if (app.globalData.isLogin) {
		// 	this.setData({
		// 		isLogin: app.globalData.isLogin,
		// 		user: app.globalData.user,
		// 	});
		// 	if (this.data.user.idcardImgBack && this.data.user.idcardImgFront) {
		// 		this.setData({
		// 			btnDisabled: false,
		// 		});
		// 	}
		// 	this.data.user["IDCard"] = this.data.user["IDCard"];
		// } else {
		// 	// 由于 userLogin 是网络请求，可能会在 Page.onLoad 之后才返回
		// 	// 所以此处加入 callback 以防止这种情况
		// 	app.userLoginCallback = (res) => {
		// 		this.setData({
		// 			isLogin: app.globalData.isLogin,
		// 			user: app.globalData.user,
		// 		});
		// 		if (this.data.user.idcardImgBack && this.data.user.idcardImgFront) {
		// 			this.setData({
		// 				btnDisabled: false,
		// 			});
		// 		}
		// 		this.data.user["IDCard"] = this.data.user["idcard"];
		// 	};
		// }
	},

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

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

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

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

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

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

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage1() {},
	getId(e) {
		console.log(e);
		let user = "user.IDCard";
		this.setData({
			[user]: e.detail.value,
		});
		console.log(this.data.user.IDCard);
		this.idverify();
	},
	getRealName(e) {
		console.log(e);
		let user = "user.realName";
		this.setData({
			[user]: e.detail.value,
		});
		this.idverify();
	},
	// toNext(data) {
	// 	console.log(data);
	// 	if (data.currentTarget.dataset.level == 1) {
	// 		if (this.isNotEmptyCheck(this.data.user.idcardImgFront)) {
	// 			this.setData({
	// 				level: 2,
	// 			});
	// 		}
	// 	} else {
	// 		if (this.isNotEmptyCheck(this.data.user.idcardImgBack)) {
	// 			this.setData({
	// 				level: 3,
	// 			});
	// 		}
	// 	}
	// 	this.idverify();
	// 	// this.setData({
	// 	//   level : this.data.level <= 2 ? this.data.level + 1 : this.data.level
	// 	// })
	// 	// wx.navigateTo({
	// 	//   url: '../realName2/index',
	// 	// })
	// 	// console.log(123);
	// },
	idverify() {
		var username = /^[\u4E00-\u9FA5\uf900-\ufa2d·s]{2,20}$/;
		if (this.data.user.IDCard.length == 18 && username.test(this.data.user.realName)) {
			this.setData({
				canFinish: true,
			});
		} else {
			this.setData({
				canFinish: false,
			});
		}
	},
	goBack() {
		// this.data.level = this.data.level - 1
		this.setData({
			level: this.data.level >= 1 ? this.data.level - 1 : this.data.level,
			isFinish: false,
		});
		if (this.data.level == 0) {
			wx.navigateBack({
				delta: 1,
			});
		}
		// this.onLoad()
	},
	toFinish() {
		let that = this;
		this.idverify();
		console.log(that.data.canFinish);
		if (!that.data.switch1Checked) {
			wx.showToast({
				title: "请先阅读并同意《服务协议》及《隐私政策》",
				icon: "none",
				duration: 2000,
			});
			return;
		}
		if (!that.data.user.idcardImgFront || !that.data.user.idcardImgBack) {
			wx.showToast({
				title: "请上传身份证照片",
				icon: "none",
				duration: 2000,
			});
			return;
		}
		if (that.data.canFinish) {
			wx.showLoading({
				title: "保存中...",
				mask: true,
			});

			var realName = that.data.user.realName;
			var IDCard = that.data.user.IDCard;

			wx.request({
				url: app.globalData.ip + "/commons/validatecard",
				data: {
					name: realName,
					cardno: IDCard,
				},
				header: app.globalData.headers,
				method: "POST",
				success: function (res) {
					console.log(res);

					// if (res.data.status == 9999) {
					//   app.dialogNotLogin();
					//   return;
					// }

					var state = res.data.data.state;
					// wx.navigateTo({
					// 	url: `/pages/returnMessage/index?from=real&type=success&msg=实名认证成功`,
					// });
					// app.globalData.loginUserInfo.user.idauth = 1;
					// return;
					if (state == 101) {
						wx.hideLoading();
						that.dialog("已被占用", "你输入的身份证号已经被其他人占用了", "知道了");
					} else if (state == 102) {
						wx.hideLoading();
						that.dialog("次数超限", "你今天已经认证失败3次，明天再认证吧", "知道了");
					} else if (state == 5 || state == 14 || state == 96) {
						wx.hideLoading();
						that.dialog("认证失败", "姓名或身份证号错误，认证失败", "知道了");
					} else if (state == 0) {
						that.saveIDCard(realName, IDCard);
					} else {
						wx.hideLoading();
						that.dialog("认证失败", res.data.msg, "知道了");
					}
				},
			});
		} else {
			wx.showToast({
				icon: "none",
				title: "请确保信息完整",
				duration: 2000,
			});
		}
	},
	saveIDCard: function (realName, IDCard) {
		let that = this;
		wx.request({
			url: app.globalData.ip + "/user/auth/authIDCard",
			data: {
				realName: realName,
				IDCard: IDCard,
			},
			header: app.globalData.headers,
			method: "POST",
			success: function (res) {
				// console.log(res);
				if (res.data.status == 200) {
					wx.showToast({
						title: "保存成功",
						icon: "success",
						image: "",
						duration: 1000,
						mask: true,
						success: function (res) {
							wx.hideLoading();
							that.updateSex();
							app.globalData.loginUserInfo.user.idauth = 1; //如果身份证上传成功，登录缓存的实名认证状态更新为已实名
							// that.makeInfoSuccess();
							wx.navigateTo({
								url: `../returnMessage/index?from=real&type=success&msg=实名认证成功`,
							});
						},
						fail: function (res) {
							wx.hideLoading();
						},
						complete: function (res) {},
					});
				} else {
					wx.navigateTo({
						url: `../returnMessage/index?from=real&type=fail&msg=实名认证失败&status=${res.data.status}`,
					});
					// app.showTips(that, res.data.msg);
				}
			},
		});
	},
	dialog: function (title, content, btxt) {
		wx.showModal({
			title: title,
			content: content,
			showCancel: false,
			confirmColor: "#ff4400",
			confirmText: btxt,
			success: function (res) {
				if (res.confirm) {
					console.log("用户点击确定");
				} else if (res.cancel) {
					console.log("用户点击取消");
				}
			},
		});
	},
	uploadCard(data) {
		var that = this;
		// return
		let type = data.currentTarget.dataset.type;
		console.log(type);
		wx.chooseImage({
			count: 1, // 默认9
			sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
			sourceType: ["album", "camera"], // 可以指定来源是相册还是相机，默认二者都有
			success: function (res) {
				wx.showLoading({
					title: "上传中",
					mask: true,
				});
				// 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
				var tempFilePaths = res.tempFilePaths;
				var formData = {
					type: type,
					userId: app.globalData.userId,
				};
				wx.uploadFile({
					url: app.globalData.ip + "/user/auth/uploadImage",
					filePath: res.tempFilePaths[0],
					name: "uploadFile",
					header: app.globalData.headers2, // 设置请求的 header
					formData: formData, // HTTP 请求中其他额外的 form data
					success: function (res1) {
						var result = JSON.parse(res1.data);
						console.log(result);
						if (result.status == 200) {
							if (type == 2) {
								that.data.user["idcardImgFrontm"] = result.data.miniUrl;
								that.data.user["idcardImgFront"] = result.data.url;
								that.data.user["IDCard"] = result.data.IDCard;
								that.data.user["realName"] = result.data.realName;
								console.log(that.data.user.IDCard);
								if (that.data.user.IDCard) {
									if (that.data.user.IDCard.slice(16, 17) % 2 == 0) {
										that.data.user.sex = 2;
										that.data.user.sexStr = "女";
									} else {
										that.data.user.sex = 1;
										that.data.user.sexStr = "男";
									}
								}
							} else if (type == 3) {
								that.data.user["idcardImgBackm"] = result.data.miniUrl;
								that.data.user["idcardImgBack"] = result.data.url;
							}
							console.log(that.data.user);
							that.setData({
								user: that.data.user,
							});
						} else {
							wx.showToast({
								icon: "none",
								title: result.msg,
								duration: 2000,
							});
						}
						//判断是否可以进入下一步
						// if (!that.isEmptyCheck(that.data.user.idcardImgFront) && !that.isEmptyCheck(that.data.user.idcardImgBack)) {
						// 	that.setData({
						// 		btnDisabled: false,
						// 	});
						// }
						wx.hideLoading();
					},
					fail: function (res2) {
						wx.hideLoading();
					},
				});
			},
		});
	},
	updateSex() {
		// that.updateSex(that.data.user["IDCard"]);

		var formData = {
			userId: app.globalData.user.id,
			sex: this.data.user.sex,
		};
		wx.request({
			url: app.globalData.ip + "/user/updateSex",
			method: "POST",
			header: app.globalData.headers,
			data: formData,
			success: function (res) {
				console.log(res);

				if (res.data.status == 200) {
					// let data = "user.sex";
					// app.({
					// 	[data]: formData.sex,
					// });
					app.globalData.user.sex = formData.sex;
					console.log(app.globalData.user.sex);
				} else {
					wx.showToast({
						icon: "none",
						title: res.data.msg,
						duration: 2000,
					});

					that.setData({
						btnLoading: false,
					});
				}
			},
		});
	},
	isEmptyCheck: function (str) {
		if (str == null || str == "" || str == "null" || str == "undefined" || typeof str == "undefined") {
			return true;
		}
		return false;
	},
	isNotEmptyCheck: function (str) {
		return !this.isEmptyCheck(str);
	},
	tomine() {
		wx.navigateBack({
			delta: 1,
		});
	},
	changeDateTime(e) {
		console.log(e);
		console.log(this.data.sex);
		if (e.detail.value == 0) {
			this.data.user.sexStr = "男";
			this.data.user.sex = 1;
		} else {
			this.data.user.sexStr = "女";
			this.data.user.sex = 2;
		}
		this.setData({
			user: this.data.user,
		});
	},
	changeDateTimeColumn(e) {
		console.log(e);
	},
});
