<template>
	<view class="padding-top">
		<form @submit="formSubmit">
			
			<view class="cu-form-group">
				<view class="title">姓名</view>
				<input placeholder="请输入姓名"  :class="personFlag?'text-right':''" :disabled="personFlag" :value="form.name" name="input" @input="updateInputVal($event,'name')"></input>
			</view>
			
			<view class="cu-form-group margin-top">
				<view class="title">身份证</view>
				<input placeholder="请输入身份证"  :class="personFlag?'text-right':''" :disabled="personFlag" :value="form.IDCard" name="input" @input="updateInputVal($event,'IDCard')"></input>
			</view>
			
			<view class="cu-form-group margin-top">
				<view class="title">手机号码</view>
				<input :placeholder="placeholder" type="number" :class="personFlag?'text-right':''" :disabled="personFlag" :value="form.phone" name="input" @input="updateInputVal($event,'phone')"></input>
				<button class='cu-btn shadow' v-show="!personFlag" :disabled="captchaFlag" @click="getCaptcha"> {{ personFlag ? '修改' : captchaFlag?count+'s后重新获取':'获取验证码' }}</button>
			</view>
			
			<view class="cu-form-group margin-top" v-show="captchaFlag">
				<view class="title">验证码</view>
				<input placeholder="请输入验证码" type="number" name="input" @input="updateInputVal($event,'verfiyCode')"></input>
			</view>
			
			<view class="padding">
				<button form-type="submit" class="cu-btn block bg-blue margin-tb-sm lg">{{personFlag?'修&ensp;改':'保&ensp;存'}}</button>
			</view>
			
		</form>
	</view>
</template>

<script>
	import validate from '@/utils/validate.js'
	import personInfo from '@/components/personInfo';
	export default {
		components: {
			personInfo
		},
		data() {
			return {
				personFlag:false,
				placeholder:'请输入手机号码',
				captchaFlag: false,
				count: 60,
				url: '',
				timer: null,
				form: {
					name: '',
					phone: '',
					IDCard:'',
					verfiyCode: ''
				},
			};
		},
		mounted() {
			this.personFlag = Boolean(this.$store.getters.userInfo.name)
			this.form.name = this.$store.getters.userInfo.name
			this.form.IDCard = this.$store.getters.userInfo.idCard || this.$store.getters.userInfo.idcard
			this.form.phone = this.$store.getters.userInfo.phoneNumber
		},
		onLoad(option) {
			console.log()
			if (option.url) {
				this.url = JSON.parse(decodeURIComponent(option.url))
			}
			uni.setNavigationBarTitle({
				title: option.name ? option.name : '个人信息'
			});
		},
		methods: {
			// 更新输入框绑定的表单内容
			updateInputVal(event, props) {
				this.form[props] = event.target.value
			},
			
			// 更新下拉框绑定的表单内容
			updatePickerVal(event, props, a) {
				this.form[props] = event.detail.value
			},
			// 提交信息
			formSubmit(e) {
				if(this.personFlag){
					this.personFlag = false
				}else{
					let loginRules = [{
							name: 'name',
							required: true,
							errmsg: '请输入姓名'
						},
						{
							name: 'IDCard',
							required: true,
							errmsg: '请输入身份证'
						},
						{
							name: 'phone',
							required: true,
							type: 'phone',
							errmsg: '请输入手机号码'
						},
						{
							name: 'verfiyCode',
							required: true,
							type: 'number',
							errmsg: '请输入验证码'
						},
					]
					console.log(this.form)
					let valLoginRes = validate.validate(this.form, loginRules)
					if (!valLoginRes.isOk) {
						uni.showToast({
							icon: 'none',
							title: valLoginRes.errmsg
						})
						return false
					} else {
						this.$http.post(`/gastric-cancer-user/sms/verify?phone=${this.form.phone}&code=${this.form.verfiyCode}`).then(
							res => {
								const d = res.data
								if (d.code == 1) {
									this.saveInfo()
								}else{
									uni.showToast({
										icon: 'none',
										title: "验证码不正确！"
									})
								}
							}).catch(err => {
								console.log(err)
						})
					}
				}
			},
			// 保存信息
			saveInfo() {
				const data = {
					phone:this.form.phone,
					name:this.form.name,
					idCard:this.form.IDCard,
					accessWay:this.$store.getters.userInfo.accessWay,
					openid:this.$store.getters.userInfo.openid || this.$store.getters.userInfo.openId || this.$store.getters.userInfo.userId
				}
				this.$http.put(
					`/gastric-cancer-user/wechat/user/rename`,data
				).then(
					res => {
						const d = res.data
						if (d.code == 1) {
							uni.showToast({
								icon: 'none',
								title: "保存成功！"
							})

							// 更新store信息
							this.$store.dispatch('user/setInfo', {
								name: this.form.name,
								idCard: this.form.IDCard,
								phoneNumber: this.form.phone
							})
							this.updateInfo()
						} else {
							uni.showToast({
								icon: 'none',
								title: d.message
							});
						}
					}).catch(err => {
					console.log(err)
				})
			},
			updateInfo(){
				let openId = this.$store.getters.userInfo.openid || this.$store.getters.userInfo.openId || this.$store.getters.userInfo.userId
				this.$http.post(`/gastric-cancer-user/wechat/user/login/${openId}`).then(res => {
					const d = res.data
					if (d.code == 1) {
						let userInfo = d.object
						if(d.object.hospitals && d.object.hospitals.length>0){
							this.$store.dispatch('user/setInfo', { hospitalId:d.object.hospitals[0].hospitalId ,hospitalName:d.object.hospitals[0].hospitalName})
						}
						let obj = Object.assign({}, this.$store.getters.userInfo)
						if (obj.avatarUrl) {
							userInfo.avatarUrl = obj.avatarUrl
						}
						this.$store.dispatch('user/setInfo', Object.assign(obj, userInfo))
						this.$store.dispatch('user/setToken', d.result)
						this.getFamilyRelation()
						this.getHospital()
					}
				}).catch(err => {
					console.log(err)
				})
			},
			// 获取家庭成员关系
			getFamilyRelation() {
				this.$http.get(`/gastric-cancer-data/enumerate/familyRelation`).then(res => {
					const d = res.data
					if (d.code == 1) {
						let arr = []
						if (d.object.items.length > 0) {
							d.object.items.forEach(item => {
								arr.push({
									label: item.itemName,
									value: item.itemCode
								})
							})
						}
						this.$store.dispatch('enumerate/setFamilyRelation', arr)
					}
				}).catch(err => {
					console.log(err)
				})
			},
			getHospital() {
				const data = {
					params: {
						pageNum: 1,
						pageSize: 500,
						isUse: 1
					}
				}
				this.$http.get(`/gastric-cancer-user/hospital/page`, data).then(res => {
					const d = res.data
					if (d.code == 1) {
						let obj = Object.assign({}, this.$store.getters.userInfo)
						obj.hospitalList = d.object.list
						obj.hospitals = d.object.list
						this.$store.dispatch('user/setInfo', obj)
						console.log(this.$store.getters.userInfo)
						
						let that = this
						setTimeout(function() {
							if (that.url) {
								uni.navigateTo({
									url: that.url
								});
							} else {
								uni.switchTab({
								    url: '/pages/person/index',
									success: function(e) {
										let page = getCurrentPages().pop();
										if (page == undefined || page == null) return;
										page.onLoad();
									}
								});
							}
						}, 1500);
						
					}
				}).catch(err => {
					console.log(err)
				})
			},
			getCaptcha() {
				if(this.personFlag){
					this.form.phone = ''
					this.placeholder = '请输入新的手机号码'
					this.personFlag = false
				}else{
					let loginRules = [{
							name: 'name',
							required: true,
							type: 'regex',
							regex: /^[\u4E00-\u9FA5A-Za-z]+$/,
							errmsg: '请输入姓名'
						},
						{
							name: 'phone',
							required: true,
							type: 'phone',
							errmsg: '请输入手机号码'
						},
					]
					let valLoginRes = validate.validate(this.form, loginRules)
					if (!valLoginRes.isOk) {
						uni.showToast({
							icon: 'none',
							title: valLoginRes.errmsg
						})
						return false
					} else {
						this.captchaFlag = true
						this.timer = setInterval(() => {
							this.setTimer()
						}, 1000)

						const data = {
							params: {
								phone: this.form.phone
							}
						}
						this.$http.get(`/gastric-cancer-user/sms/code`, data).then(res => {
							const d = res.data
							if (d.code == 1) {
								this.code = d.object
							} else {
								uni.showToast({
									icon: 'none',
									title: d.message
								});
							}
						}).catch(err => {
							console.log(err)
						})
					}
				}
			},
			setTimer() {
				this.count = this.count - 1
				while (this.count == 0) {
					clearInterval(this.timer)
					this.count = 60
					this.captchaFlag = false
				}
			}
		}
	}
</script>

<style lang="scss">

</style>
