<template>
	<view>
		<!--prescription/drugUsers/index.wxml-->
		<view class="tips dflex">
			<image src="/prescription/static/prescription/image/guarantee.png" class="guarantee"></image>
			处方药需实名预约，平台会保护您的隐私安全
		</view>
		<view class="bgfff">
			<view class="dflex ipt">
				<text class="red">*</text><label class="name">真实姓名{{form.name}}</label><input :value="form.name"
					placeholder="请输入真实姓名" @blur="checkId" data-index="1"></input>
			</view>
			<view class="dflex ipt">
				<text class="red">*</text><label class="name">手机号码</label><input :value="form.tel" placeholder="请输入手机号码"
					@blur="checkId" data-index="2" type="number"></input>
			</view>
			<view class="dflex ipt">
				<text class="red">*</text><label class="name">身份证号</label><input class="flex" placeholder="请输入身份证号码"
					:value="form.idCard" @blur="checkId" data-index="3" type="idcard"></input>
				<view class="sex" v-if="gender||age">{{gender}} {{age}}</view>
			</view>
		</view>
		<view class="list">
			<view class="li">
				<text>设为默认</text>
				<view class="items she" @tap="setDefault">
					<image :src="isDefault ? '/static/pages/images/gou_h.png' : '/static/pages/images/gou.png'"
						class="check"></image>
				</view>
			</view>
		</view>
		<view class="bgfff relationship dflex">
			<label>关系标签</label>
			<view v-for="(item, index) in TabList" :key="index" :class="'item ' + (item.active?'active':'')"
				@tap="switchTab" :data-index="index">{{item.text}}</view>
		</view>

		<view class="bot fixed bgfff dflex" :style="'padding: ' + (bottomBlankHeight + 20) + 'rpx 0rpx'"
			v-if="!query.id">
			<view class="mbglinear gmbtn" @tap="saveUsers">保存并使用</view>
		</view>
		<view class="btn dflex" v-else>
			<view class="del" @tap="deleteFun">删除</view>
			<view class="submit" @tap="saveUsers">确定</view>
		</view>
	</view>
</template>

<script>
	// prescription/drugUsers/index.js
	const app = getApp();
	const req = require("../../utils/request.js");

	export default {
		data() {
			return {
				TabList: [{
					text: "本人"
				}, {
					text: "家庭成员"
				}, {
					text: "亲戚"
				}, {
					text: "朋友"
				}],
				bottomBlankHeight: app.globalData.isIPhoneX ? 68 : 0,
				isDefault: false,
				form: {name:'',tel:'',idCard:''},
				query: "",
				label: "",
				gender: "",
				sex: "",
				age: "",
				old: "",
				birth: "",
				cardId: ""
			};
		},

		components: {},
		props: {},

		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad: function(options) {
			this.query = options;
			this.setData({
				query: options
			});

			if (options.id) {
				this.getdrugUsers(options.id);
			}

			if (options.add == 1 && !options.id) {
				let d = {};
				d['TabList[0].active'] = true;
				this.setData(d);
				this.setData({
					label: this.TabList[0].text,
					isDefault: !this.isDefault
				});
			} else if (options.add == 2 && !options.id) {
				let d = {};
				d['TabList[1].active'] = true;
				this.setData(d);
				this.setData({
					label: this.TabList[1].text
				});
			}

			// console.log(options);
		},
		methods: {
			switchTab(event) {
				let index = event.currentTarget.dataset.index;
				let def = this.TabList.findIndex(it => it.active || it.actives);
				let d = {};
				// console.log(def, index);
				d['TabList[' + def + '].active'] = false;
				d['TabList[' + index + '].active'] = true;
				d['pageList'] = [];
				this.setData(d);
				this.setData({
					label: this.TabList[index].text
				});
			},
			// 保存用药人
			saveUsers() {
				let form = this.form;
				// console.log(this.form,"保存")
				if (!form.name) {
					return req.msg("请填写姓名");
				}

				if (!form.tel) {
					return req.msg("请填写电话");
				}

				if (!form.idCard) {
					return req.msg("请填写身份证号码");
				}

				if (this.sex) {
					form.sex = this.sex;
				}

				if (this.old) {
					form.age = this.old;
				}

				if (this.label) {
					form.label = this.label;
				}

				if (this.birth) {
					form.birthday = this.birth;
				}

				if (this.query.id) {
					form.id = this.query.id;
				}

				form.isDefault = this.isDefault ? 1 : 0;
				// console.log(form);

				if (form) {
					let isShowLoading = false;

					if (!isShowLoading) {
						req.loadIng('保存中');
						isShowLoading = true;
					}

					req.postRequest('/api/userDrugPeople/save', form, res => {
						// console.log(res);

						if (isShowLoading) {
							uni.hideLoading();
							uni.navigateBack();
							isShowLoading = false;
						}
					}); // if(this.query.id){
					//   req.postRequest('/api/userDrugPeople/',form,res=>{
					//     console.log(res)
					//   })
					// }
				}
			},

			checkId(e) {
				// console.log(e); //  1 名字  2手机号码 3身份证号码
				let that=this
				let index = e.target.dataset.index;
				let value = e.target.value;
				// console.log(value)
				if (index == 1) {
					var regName = /^[\u4e00-\u9fa5]{2,4}$/;
					// console.log(!regName.test(value))
					if (!regName.test(value)) {
						that.form.name=''
						// var username = "form.name";
						// this.setData({
						// 	[username]: ''
						// });
						// console.log(that.form)
						return req.msg('请正确输入您的姓名');
					} else {
						// var username = "form.name";
						// this.setData({
						// 	[username]: value
						// });
						that.form.name=value
						// console.log(that.form)
					}
				}

				if (index == 2) {
					var reg = /^1[3|4|5|6|7|8|9][0-9]{9}$/; //验证规则

					var flag = reg.test(value);

					if (!flag) {
						return req.msg("手机号码格式有误");
					} else {
						var tel = "form.tel";
						this.setData({
							[tel]: value
						});
					}
				}

				if (index == 3) {
					//检查身份证号码 
					if (!value) {
						this.setData({
							gender: '',
							sex: '',
							age: '',
							old: ''
						});
						return req.msg('请输入身份证号码');
					}

					var arrVerifyCode = [1, 0, "X", 9, 8, 7, 6, 5, 4, 3, 2];
					var Wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
					var Checker = [1, 9, 8, 7, 6, 5, 4, 3, 2, 1, 1];
					var Ai;

					if (value.length != 15 && value.length != 18) {
						this.setData({
							gender: '',
							sex: '',
							age: '',
							old: ''
						});
						return req.msg("身份证号共有15位或18位");
					}

					if (value.length == '15') {
						var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
						var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
						var cardTemp = 0,
							i;
						a18 = "";
						a18 = value.substr(0, 6) + '19' + value.substr(6, value.length - 6);

						for (i = 0; i < 17; i++) {
							cardTemp += a18.substr(i, 1) * arrInt[i];
						}

						a18 += arrCh[cardTemp % 11];
						Ai = a18;
						// console.log(a18);
					}

					if (value.length == '18') {
						Ai = value.length == 18 ? value.substring(0, 17) : value.slice(0, 6) + "19" + value.slice(6, 16);
					}

					if (!/^\d+$/.test(Ai)) return req.msg("身份证除最后一位外，必须为数字！");
					var yyyy = Ai.slice(6, 10),
						mm = Ai.slice(10, 12) - 1,
						dd = Ai.slice(12, 14);
					var d = new Date(yyyy, mm, dd),
						now = new Date();
					var year = d.getFullYear(),
						mon = d.getMonth(),
						day = d.getDate();

					if (year != yyyy || mon != mm || day != dd || d > now || year < 1800) {
						this.setData({
							gender: '',
							sex: '',
							age: '',
							old: ''
						});
						return req.msg("身份证输入错误");
					}

					for (var i = 0, ret = 0; i < 17; i++) ret += Ai.charAt(i) * Wi[i];

					Ai += arrVerifyCode[ret %= 11]; // console.log(pId != Ai,pId.length == 18,pId,Ai)
					if (value.indexOf('x') != -1) {
						value = value.replace("x", "X")
					}

					if (value.length == 18 && value != Ai) {
						this.setData({
							gender: '',
							sex: '',
							age: '',
							old: ''
						});
						return req.msg("身份证输入错误！");
					} else {
						// if (isNaN(Ai)) return;
						var ic = String(Ai); //获取出生日期

						var birth = ic.substring(6, 10) + "-" + ic.substring(10, 12) + "-" + ic.substring(12, 14);
						// console.log(birth);
						this.setData({
							birth: birth
						}); //获取性别

						var gender = ic.slice(14, 17) % 2 ? "1" : "0"; // 1代表男性，0代表女性

						let sex = gender == 1 ? '男' : '女';
						this.setData({
							gender: sex,
							sex: gender
						}); //获取年龄

						var myDate = new Date();
						var month = myDate.getMonth() + 1;
						var day = myDate.getDate();
						var age = myDate.getFullYear() - ic.substring(6, 10) - 1;

						if (ic.substring(10, 12) < month || ic.substring(10, 12) == month && ic.substring(12, 14) <= day) {
							age++;
						}

						if (age >= 90 || age <= 0) {
							this.setData({
								gender: '',
								sex: '',
								age: '',
								old: ''
							});
							return req.msg("身份证异常");
						} else if (age <= 7) {
							this.setData({
								gender: '',
								sex: '',
								age: '',
								old: ''
							});
							return req.msg("根据互联网处方药条例，用药人的年龄不得小于8岁，请使用监护人身份信息，开具处方，并告知在线医师");
						}

						let nianling = age + '岁';
						this.setData({
							age: nianling,
							old: age
						});
						var idCard = "form.idCard";
						this.setData({
							[idCard]: Ai
						});
					}
				}
			},
			// 获取用药人详情
			getdrugUsers(id) {
				req.getRequest('/api/userDrugPeople/get', {
					id: id
				}, data => {
					// console.log(data);
					let tablist;

					if (data) {
						tablist = this.TabList.map(it => {
							if (it.text == data.label) {
								it.active = true;
							}

							return it;
						});
						let isDefault = data.isDefault ? 1 : 0;
						// console.log(this.TabList);
						var name = "form.name";
						var tel = "form.tel";
						var cardId = "form.idCard";
						this.setData({
							[name]: data.name,
							[tel]: data.tel,
							[cardId]: data.idCard,
							TabList: tablist,
							label: data.label,
							isDefault: isDefault
						});
					}
				});
			},

			deleteFun() {
				let that = this;
				req.msgConfirm('确定删除该用药人', () => {
					req.postRequest('/api/userDrugPeople/delete', {
						id: this.query.id
					}, () => {
						uni.navigateBack();
					});
				});
			},

			// 是否默认
			setDefault() {
				this.setData({
					isDefault: !this.isDefault
				});
			}

		}
	};
</script>
<style>
	@import "./index.css";
</style>
