const Service = require('../../../utils/service.js');
const Util = require('../../../utils/util.js');
Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		showClose: true,
		name: '',
		phone: '',
		list: [],
		receiveAddress: '',
		tel: '',
		agree: true, //同意知情书
		iPhoneX: false,
		item: '',
		id: '',
		ishow: true,
		paySuccess: false,
		errshow: false
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		let that = this
		that.checkModal();
		if (Util.isEmpty(options)) {
			wx.showModal({
				title: '提示',
				content: '网络故障，请重新扫码。错误码：4002',
				showCancel: false,
				success(res) {
					if (res.confirm) {
						console.log('用户点击确定')
					}
				}
			})
			return;
		}
		console.log("options", options)
		that.data.options = options
	},
	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {
		var that = this
		that.login = that.selectComponent("#login");
		that.modal = that.selectComponent("#modal");
		that.answer = that.selectComponent("#answer");
		if (wx.getStorageSync('data').unionid == undefined || wx.getStorageSync('data').unionid == '') {
			wx.login({
				success: function (msg) {
					Service.getOpenId(msg.code).then((res) => {
						wx.setStorageSync('user', res)
						return Service.getUserData(res.openid)
					}).then((res) => {
						if (Util.isEmpty(res.unionid)) {
							that.login.showLogin();
						} else {
							wx.setStorageSync('data', res)
							if (that.data.options.isQuick == 0) {
								// 正常开药
								that.getPrescribe(that.data.options.scene, res.unionid)
							} else {
								that.getQuick(that.data.options.scene, res.unionid)
							}
						}
					})
				}
			})
		} else {
			if (that.data.options.isQuick == 0) {
				// 正常开药
				that.getPrescribe(that.data.options.scene, wx.getStorageSync('data').unionid)
			} else {
				that.getQuick(that.data.options.scene, wx.getStorageSync('data').unionid)
			}
		}
	},
	// 处方笺
	getPrescribe: function (id, patient_unionid) {
		let that = this
		if (that.data.paySuccess) {
			return;
		}
		let data = {};
		data.prescription = id;
		data.patient_unionid = patient_unionid;
		Service.getRecipeDetails(data).then((res) => {
			console.log("getDetail", res);
			if (res.code == 2 || res.code == 3) {
				wx.showModal({
					content: res.msg,
					showCancel: false,
					success(res) {
						if (res.confirm) {
							wx.switchTab({
								url: '/pages/index/index'
							})
						}
					}
				})
			}
			if (res.data != null) {
				that.setData({
					list: res.data,
					receiveAddress: res.data.address ? res.data.address : '',
					tel: res.data.address != null ? res.data.address.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') : ""
				})
				if (that.data.item == "") {
					that.setData({
						item: res.data.user,
					})
				}
				if (res.data.healthcare.length > 0) {
					that.isChecked(res.data.healthcare);
				}
			}
		})
	},
	// 快速开药
	getQuick: function (quickid, patient_unionid) {
		var that = this
		if (that.data.paySuccess) {
			return;
		}
		let data = {};
		data.prescription = quickid;
		data.patient_unionid = patient_unionid;
		Service.getQuick(data).then((res) => {
			if (res.code == 2 || res.code == 3) {
				wx.showModal({
					content: res.msg,
					showCancel: false,
					success(res) {
						if (res.confirm) {
							wx.switchTab({
								url: '/pages/index/index'
							})
						}
					}
				})
			}
			if (res.data != null) {
				that.setData({
					list: res.data,
					receiveAddress: res.data.address ? res.data.address : '',
					tel: res.data.address != null ? res.data.address.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') : ""
				})
				if (that.data.item == "") {
					that.setData({
						item: res.data.user,
					})
				}
				if (res.data.healthcare.length > 0) {
					that.isChecked(res.data.healthcare);
				}
			}
		})
	},
	//如果有医生推荐药品加上选中状态
	isChecked(healthcare) {
		var list = new Array();
		var healthcareArr = new Array();
		for (var i = 0; i < healthcare.length; i++) {
			healthcare[i].checked = true;
			list.push(healthcare[i]);
			healthcareArr.push(healthcare[i].id)
		}
		this.setData({
			'list.healthcare': list,
			healthcare: healthcareArr
		})
	},
	updataRadio(e) {
		var that = this;
		var list = that.data.list;
		var index = e.currentTarget.dataset.index;
		if (list.healthcare[index].checked) {
			list.healthcare[index].checked = false;
			list.drug_money = (Number(list.drug_money) - Number(list.healthcare[index].drugPrice)).toFixed(2);
			list.money = (Number(list.money) - Number(list.healthcare[index].drugPrice)).toFixed(2);
		} else {
			list.healthcare[index].checked = true;
			list.drug_money = (Number(list.drug_money) + Number(list.healthcare[index].drugPrice)).toFixed(2);
			list.money = (Number(list.money) + Number(list.healthcare[index].drugPrice)).toFixed(2);
		}
		var agree = that.data.agree;

		if (Number(list.drug_money) == 0) {
			agree = false
		} else {
			agree = true
		}
		that.setData({
			list: list,
			agree: agree
		})
	},
	myDetails: function (e) {
		var that = this;
		if (wx.getStorageSync('data').unionid == undefined) {
			that.login.showLogin();
			return
		}
		if (that.data.item == null) {
			wx.navigateTo({
				url: e.currentTarget.dataset.src + "?type=2&iShow=undefined",
			})
		} else {
			wx.navigateTo({
				url: e.currentTarget.dataset.src + "?type=2&iShow=" + that.data.item.id + "&item=" + JSON.stringify(that.data.item),
			})
		}
	},
	tel: function () {
		wx.makePhoneCall({
			phoneNumber: '95338'
		})
	},
	//知情同意书
	goConsent: function (e) {
		wx.navigateTo({
			url: '/packageA/consent/consent'
		})
	},
	//同意知情同意书
	agree: function (e) {
		var that = this;
		var agree = that.data.agree ? false : true;
		that.setData({
			agree: agree
		})
	},
	//选择地址
	gosite() {
		wx.navigateTo({
			url: '/packageA/site/site',
		})
	},
	//判断是否是iPhonex
	checkModal: function () {
		let that = this;
		wx.getSystemInfo({
			success: (res) => {
				// iPhone X   iPhone XR  iPhone XS Max     iPhone XS
				if (/^iPhone X.*/i.test(res.model) || /^iPhone XR.*/i.test(res.model) || /^iPhone XS.*/i.test(res.model) || /^iPhone 11*/i.test(res.model) || /^iPhone 11 Pro Max*/i.test(res.model)) {
					that.setData({
						iPhoneX: true,
					})
				} else {
					that.setData({
						iPhoneX: false,
					})
				}
			}
		});
	},
	/**
	 * applyPay 立即支付
	 */
	applyPay: Util.debouce(function () {
		let that = this;
		that.setData({
			agree: false
		})
		if (that.data.receiveAddress.id == undefined) {
			wx.showToast({
				title: '请填写收货地址',
				icon: 'none'
			})
			that.setData({
				agree: true
			})
			return
		}
		if (that.data.ishow == true) {
			if (that.data.item == null) {
				wx.showToast({
					title: '请补充患者信息',
					icon: 'none'
				})
				that.setData({
					agree: true
				})
				return
			}
			if (Util.isEmpty(that.data.item.card)) {
				wx.showModal({
					title: '提示',
					content: '根据互联网医院管理规定，请您填写患者身份证号码。',
					confirmText: '去填写',
					success(res) {
						if (res.confirm) {
							that.setData({
								agree: true
							})
							wx.navigateTo({
								url: "/packageA/editPatientInfo/editPatientInfo?item=" + JSON.stringify(that.data.item) + "&btid=1",
							})
						}
					}
				})
				that.setData({
					agree: true
				})
				return;
			}
		}
		if (that.data.receiveAddress == '') {
			wx.showModal({
				title: '提示',
				showCancel: false,
				content: '请选择收货地址！',
			})
		} else {
			wx.showLoading({
				title: '正在拉起支付',
				mask: true
			})
			that.prescriptionPay();
		}
	}, 1000, true),
	prescriptionPay: function () {
		let that = this;
		let hstr = new Array();
		let healthcare = that.data.list.healthcare;
		for (let i = 0; i < healthcare.length; i++) {
			if (healthcare[i].checked) {
				hstr.push(healthcare[i].id);
			}
		}
		let data = {
			payid: that.data.list.payid,
			patient_unionid: that.data.item.unionid,
			modular: that.data.list.modular,
			lastid: that.data.item.id,
			address: that.data.receiveAddress.id,
			isywlx: that.data.list.isywlx,
			money: that.data.list.money,
			hstr: hstr.toString(),
			isgd: 1
		}
		Service.prescriptionPay(data).then((res) => {
			console.log('res1', res);
			switch (res.code) {
				case 1:
					var orderNumber = res.data.dealarr.out_trade_no;
					wx.hideLoading();
					that.data.main = false;
					wx.requestPayment({
						timeStamp: res.data.parameter.timeStamp,
						nonceStr: res.data.parameter.nonceStr,
						package: res.data.parameter.package,
						signType: 'MD5',
						paySign: res.data.parameter.paySign,
						success(res) {
							console.log('res')
							if (res.errMsg && res.errMsg == "requestPayment:ok") {
								console.log("requestPayment:ok")
								wx.reLaunch({
									url: '/packageA/drugOrder/drugOrder'
								})
								that.data.paySuccess = true;
								return;
							} else {
								wx.showLoading({
									title: '支付中',
									mask: true
								})
								that.paySuccess(orderNumber);
							}
						},
						fail(res) {
							wx.showToast({
								title: '支付失败',
								icon: 'none'
							})
							that.setData({
								agree: true
							})
							that.data.main = true;
							that.onShow();
						},
						complete: function (res) {
							if (res.errMsg == "requestPayment:ok") {
								console.log('支付成功')
								that.data.paySuccess = true;
							}
						}
					})
					wx.hideToast();
					return;
				case -1: //参数异常
				case 2: //药方过期
				case 3: //二维码无法使用
				case 4: //请选择需要购买的药物
				case 6:
				case 10001: //参数异常
				case 10032: //请选择患者
				case 10036: //请选择药方
				case 30008: //请选择地址
					wx.hideLoading();
					wx.showModal({
						title: '提示',
						showCancel: false,
						content: res.msg,
					})
					that.setData({
						agree: true
					})
					return;
				case 5:
				case 7: //药方作废、下架提示
					wx.hideLoading();
					this.setData({
						errshow: true,
						errmsg: res.msg,
						errList: res.data
					})
					that.setData({
						agree: true
					})
					return;
			}
		})
	},
	//支付成功回调
	paySuccess(ordernumber) {
		var that = this;
		var data = {
			ordernumber: ordernumber,
			fromwhere: 3,
			inquiry_id: 0
		}
		Service.paySucceedCallback(data).then((res) => {
			if (res.code == 1) {
				setTimeout(function () {
					wx.hideLoading();
					wx.showToast({
						title: '购买成功',
					})
					wx.reLaunch({
						url: '/packageA/drugOrder/drugOrder'
					})
				}, 500)
			} else {
				setTimeout(function () {
					that.paySuccess(ordernumber);
				}, 200)
			}
		})
	},
	//登陆后组件回调方法刷新当前页面
	_refreshEvent() {
		console.log("刷新");
		this.onShow();
	},
	//客服电话
	dial(e) {
		let tel = e.currentTarget.dataset.tel;
		wx.makePhoneCall({
			phoneNumber: tel,
		})
	},
})