<template>
	<view class="page">
		<view :style="{'marginTop':'10rpx'}">
			<u--form labelPosition="left" :model="form" :rules="rules" ref="uForm">
				<u-form-item :labelWidth="80" label="头像：" borderBottom prop="img" ref="item1">
					<view class="photoView" @click="updateAvatar" >
						<image class="photoImage" :src="form.imgUrl || '/static/ud4.png'"></image>
					</view>
				</u-form-item>
				<u-form-item :labelWidth="80" label="姓名：" borderBottom prop="name" ref="item1">
					<u--input v-model="form.name"  placeholder="请输入姓名" border="none"></u--input>
				</u-form-item>
				<u-form-item :labelWidth="80" label="身份证号：" borderBottom prop="idCard" ref="item1">
					<u--input v-model="form.idCard"  placeholder="请输入姓名" border="none"></u--input>
				</u-form-item>
				<u-form-item :labelWidth="80" label="密码：" borderBottom prop="newPassword" ref="item1">
					<u--input v-model="form.newPassword" placeholder="请输入密码" type="password" border="none"></u--input>
				</u-form-item>

				<u-form-item :labelWidth="80" label="确认密码：" borderBottom prop="againPassword" ref="item1">
					<u--input v-model="form.againPassword" placeholder="再次确认密码" type="password" border="none"></u--input>
				</u-form-item>

				<u-form-item :labelWidth="80" label="手机号：" borderBottom prop="phone" ref="item1">
					<u--input v-model="form.phone"  placeholder="请输入手机号" border="none"></u--input>
				</u-form-item>
				<u-form-item :labelWidth="80" label="验证码：" borderBottom prop="code" ref="item1">
					<view class="inputCode">
						<u--input v-model="form.code"  placeholder="请输入验证码" border="none"></u--input>
					</view>
					<u-button slot="right" @tap="getCode" :text="tips" type="success" size="small" :disabled="disabled1"></u-button>
				</u-form-item>

			</u--form>

			<view :style="{'marginTop':'100rpx'}">
				<button class="customStyle"  @click="expandRegister">提交</button>
			</view>

			<view class="flex-row justify-center  register">
				<text>已有账号！</text>
				<text @click="gologin" :style="{color:'#FFE05C'}">切换登录</text>
			</view>

		</view>
		<u-code ref="uCode" @change="codeChange" seconds="60" @start="disabled1 = true" @end="disabled1 = false"></u-code>
		<u-action-sheet
				:show="showSex"
				:actions="actions"
				title="请选择性别"
				@close="showSex = false"
				@select="sexSelect">
		</u-action-sheet>
		<u-datetime-picker
				:show="showBirthday"
				:value="birthday"
				mode="date"
				closeOnClickOverlay
				@confirm="birthdayConfirm"
				@cancel="birthdayClose"
				@close="birthdayClose"
		></u-datetime-picker>
	</view>
</template>
<script>
	export default {
		data() {
			return {
				requestStatus:false,
				disabled1:false,
				showBirthday:false,
				showSex:false,
				birthday: Number(new Date()),
				actions: [{
					name: '男',
					value:'1'
					},
					{
						name: '女',
						value:'0'
					},{
						name: '保密',
						value:'2'
					}
				],
				tips:'',
				form:{
					roleId:'',
					parentId:'',
					img:'',
					imgUrl:'',
					name:'',
					idCard:'',
					newPassword:'',
					againPassword:'',
					phone:'',
					code:'',
				},
				rules: {
					'img': {
						type: 'string',
						required: true,
						message: '请上传头像',
						trigger: ['blur', 'change']
					},
					'name':[
						{
							type: 'string',
							required: true,
							min:2,
							message: '请输入姓名',
							trigger: ['blur']
						}
					] ,
					'idCard': [
						{
							type: 'string',
							required: true,
							min:18,
							max: 18,
							pattern:this.$idCardPattern,
							message: '请输入身份证号',
							trigger: ['blur']
						},
						{
							asyncValidator: async (a,b,callback) => {
								this.$refs.uForm.validateField('name');
								let res = await this.idCardAndName()
								if(res.data.data.respCode !== '0000') {
									callback(new Error(res.data.data.respMessage));
								} else {
									// 如果校验通过，也要执行callback()回调
									callback();
								}
							},
							// 触发器可以同时用blur和change
							trigger: ['blur']
						}
					],
					'phone': {
						type: 'string',
						required: true,
						min:11,
						max: 11,
						pattern:this.$phonePattern,
						message: '请输入正确的电话号码',
						trigger: ['blur', 'change']
					},
					'code': {
						type: 'string',
						required: true,
						min:4,
						max: 6,
						message: '请输入验证码',
						trigger: ['blur', 'change']
					},
					'newPassword': {
						type: 'string',
						min:6,
						max: 16,
						required: true,
						message: '请输入6-18位密码',
						trigger: ['blur', 'change']
					},
					'againPassword': {
						type: 'string',
						min:6,
						max: 16,
						required: true,
						message: '请输入6-18位密码',
						trigger: ['blur', 'change']
					}
				},
			}
		},
		onLoad(e){
			if (e.roleId){
				this.form.roleId = e.roleId
				console.log('获取到的id',e.roleId)
			}
			if (e.parentId){
				this.form.parentId = e.parentId
				console.log('获取到的name',e.parentId)
			}
		},
		methods: {
			idCardAndName(){
				return this.$api.service.idCardAndName({
					name:this.form.name,
					idCard:this.form.idCard,
				}).then(res=>{
					return res
				})
			},

			gologin(){
				uni.redirectTo({
					url:'/pages/login/login'
				})
			},

			updateAvatar(){
				let that = this
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: function (res) {
						let tempUrl = res.tempFiles[0].path
						uni.uploadFile({
							url: that.$baseUrl + '/resource/oss/upload', //仅为示例，非真实的接口地址
							filePath:tempUrl,
							name: 'file',
							header: {
								// "Content-Type": "multipart/form-data",
								// 'X-Access-Token': uni.getStorageSync('token'),
								'Authorization': 'Bearer ' + uni.getStorageSync('accessToken'),
							},
							success: (uploadFileRes) => {
								let res = JSON.parse(uploadFileRes.data)
								console.log('+++++++++++++++++chooseavatar+++++++++++++++++++++++',uploadFileRes.data)
								that.form.imgUrl = res.data.url.replace(/^http:/, "https:")
								that.form.img = res.data.ossId
							}
						});

					}
				})

			},

			birthdayClose() {
				this.showBirthday = false
				// this.$refs.form1.validateField('userInfo.birthday')
			},
			birthdayConfirm(e) {
				console.log(e)
				this.showBirthday = false
				this.form.birthday = uni.$u.timeFormat(e.value, 'yyyy-mm-dd')
				// this.$refs.form1.validateField('userInfo.birthday')
			},

			sexSelect(e) {
				console.log(e)
			},
			expandRegister(){
				console.log(this.form)
				if (this.requestStatus){
					return
				}
				this.requestStatus=true
				this.$refs.uForm.validate().then(res => {
					uni.showLoading({
						title: '正在注册...'
					});

					this.$api.login.expandRegister(this.form).then(res=>{
						uni.hideLoading();
						this.requestStatus=false
						uni.showToast({
							icon: 'success',
							duration: 2000,
							title: '注册成功，即将跳转登录页'
						});
						setTimeout(()=>{
							this.gologin()
						},2000)

					}).catch(err=>{
						this.requestStatus=false
					})
				}).catch(err=>{
					this.requestStatus=false
				})
			},
			logout(){
				this.$api.login.logout().then(res=>{
					uni.clearStorageSync();
					uni.navigateTo({
						url:'/pages/login/login'
					})
				})
			},
			back(){
				uni.navigateBack({
					delta: 1
				});
			},
			codeChange(text) {
				this.tips = text;
			},
			getCode() {
				let regExp=new RegExp(this.$phonePattern);
				let b= regExp.test(this.form.phone)
				if (!b){
					uni.$u.toast('请输入正确的手机号')
					return
				}
				if (this.$refs.uCode.canGetCode) {
					// 模拟向后端请求验证码
					uni.showLoading({
						title: '正在获取验证码'
					})
					this.$api.service.getSmsCode({phonenumber: this.form.phone}).then(res=>{
						uni.hideLoading();
						// 这里此提示会被this.start()方法中的提示覆盖
						uni.$u.toast('验证码已发送');
						// 通知验证码组件内部开始倒计时
						this.$refs.uCode.start();
					})
				} else {
					uni.$u.toast('倒计时结束后再发送');
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	@import './index.rpx.css';
</style>
