<template>
	<view class="container">
		<u-form :model="registerForm" ref="registerForm" label-width="160"
			:label-style="{ color: '#000', fontSize: '30rpx'}">
			<u-form-item label="账号" prop="username" required :border-bottom="false">
				<u-input height="80" placeholder="请输入账号" border-color="#d0d0d0" v-model="registerForm.username"
					:border="true" class="form-item-input" />
			</u-form-item>
			<u-form-item label="密码" prop="password" required :border-bottom="false">
				<u-input height="80" placeholder="请输入密码" border-color="#d0d0d0" v-model="registerForm.password"
					:border="true" class="form-item-input" type="password" />
			</u-form-item>
			<u-form-item label="确认密码" prop="checkPwd" required :border-bottom="false">
				<u-input height="80" placeholder="请确认密码" border-color="#d0d0d0" v-model="registerForm.checkPwd"
					:border="true" class="form-item-input" type="password" />
			</u-form-item>
			<u-form-item label="手机号码" prop="phone" required :border-bottom="false" v-if="mode === 'register'">
				<u-input height="80" placeholder="请输入手机号" border-color="#d0d0d0" v-model="registerForm.phone"
					:border="true" class="form-item-input" type="number" />
			</u-form-item>
			<u-form-item label="手机号码" prop="phone" required :border-bottom="false" v-else>
				<u-input height="80" placeholder="请输入手机号" border-color="#d0d0d0" v-model="registerForm.phone"
					:border="true" class="form-item-input" type="number" disabled/>
			</u-form-item>
			<u-form-item label="身份证" prop="userCode"  required :border-bottom="false">
				<u-input height="80" placeholder="请输入身份证" border-color="#d0d0d0" v-model="registerForm.userCode"
					:border="true" class="form-item-input" />
			</u-form-item>
			<u-form-item label="性别" prop="sex" required :border-bottom="false">
				<u-radio-group v-model="registerForm.sex">
					<u-radio v-for="(item, index) in radioList1" :key="index" :name="item.name"
						:disabled="item.disabled">
						{{ item.text }}
					</u-radio>
				</u-radio-group>
			</u-form-item>
			<view class="form-button" @click="submit">
				{{ mode === 'register' ? "注册" : "确认"}}
			</view>
			<view class="form-tip" @click="back" v-if="mode === 'register'">已有账号，立即登录</view>
		</u-form>
	</view>
</template>

<script>
	import {
		msg,
		msgSuccess
	} from "@/utils/common.js"
	import {
		encryptAESCBC
	} from "@/utils/crypto.js"
	import {
		register,
		wxLoginOpenid
	} from "@/api/login.js"
	import {
		useAuthStore
	} from '@/store/authStore.js'
	import {
		me
	} from '@/api/user.js'
	export default {
		data() {
			return {
				mode: "",
				registerForm: {
					username: '', //账号
					password: "", //密码
					checkPwd: '', // 确认密码
					phone: '', // 手机号码
					userCode: '', // 身份证
					sex: '', // 性别
					openid: ''
				},
				radioList1: [{
						name: '1',
						text: '男',
						disabled: false
					},
					{
						name: '2',
						text: '女',
						disabled: false
					}
				],
				rules: {
					username: [{
						required: true,
						message: '请输入账号',
						trigger: ['blur']
					}],
					password: [{
						required: true,
						message: '请输入密码',
						trigger: ['blur']
					},{
						validator: (rule, value, callback) => {
							if (value.length < 8) {
							  callback(new Error('密码长度至少8位'));
							} else if (!/(?=.*[a-z])/.test(value)) {
							  callback(new Error('需包含小写字母'));
							} else if (!/(?=.*[A-Z])/.test(value)) {
							  callback(new Error('需包含大写字母'));
							} else if (!/(?=.*\d)/.test(value)) {
							  callback(new Error('需包含数字'));
							} else {
							  callback(); // 验证通过
							}
						},
						trigger: ['blur', 'change']
					}],
					checkPwd: [{
						required: true,
						message: '请确认密码',
						trigger: ['blur']
					}, {
						required: true,
						message: "密码与确认密码不一致",
						trigger: ['blur'],
						validator: this.validateConfirmPassword
					}],
					phone: [{
						required: true,
						message: '请输入手机号码',
						trigger: ['blur']
					}, {
						pattern: /^1[3-9]\d{9}$/,
						message: '请输入正确的手机号',
						trigger: ['blur']
					}],
					userCode: [{
						required: true,
						message: '请输入身份证号码',
						trigger: ['blur']
					},{
						pattern: /^(?:\d{15}|\d{17}[\dXx])$/,
						transform(value) {
							return String(value);
						},
						message: '请输入正确的身份证',
						trigger: ['blur']
					}],
					sex: [{
						required: true,
						message: '请选择性别',
						trigger: ['change']
					}]
				},
				redirect: null,
			};
		},
		methods: {
			validateConfirmPassword(rule, value, callback) {
				if (value !== this.registerForm.password) {
					callback(new Error('密码与确认密码不一致'));
				} else {
					callback(); // 校验通过
				}
			},
			submit() {
				const that = this;
				that.$refs.registerForm.validate(async (valid) => {
					if(valid){
						const form = {
							...this.registerForm
						};
						form.password = encryptAESCBC(form.password);
						form.checkPwd = encryptAESCBC(form.checkPwd);
						
						const loginRes = await wx.login();
						const code = loginRes.code;
						let wxRes = await wxLoginOpenid({code})
						if(wxRes && wxRes?.data){
							const { openid, sessionKey } = wxRes.data
							// this.useAuthStore.setOpenid(openid)
							this.registerForm.openid = openid
							form.openid = openid
							register(form).then(res => {
								if (res?.data) {
									this.useAuthStore.setAuthToken(res.data.token, res.data.tokenExp);
									msgSuccess("注册成功");
									this.initUser()
								}
							})
						}
					}
				})
			},
			async initUser(){
				// const loginRes = await wx.login();
				// const code = loginRes.code;
				let userRes = await me();
				// let wxRes = await wxLoginOpenid({code})
				// 加载用户信息
				if(userRes && userRes?.code===0){
					this.useAuthStore.setUserInfo(userRes.data)
				}
				this.useAuthStore.setOpenid(this.registerForm.openid)
				// 加载openid
				// if(wxRes && wxRes?.data){
				// 	const { openid, sessionKey } = wxRes.data
				// 	this.useAuthStore.setOpenid(openid)
				// }
				setTimeout(() => {
					if(this.redirect){
						uni.removeStorageSync("redirect")
						uni.reLaunch({
							url: this.redirect.url+'?id='+this.redirect.id+'&title='+this.redirect.title
						})
					}else{
						uni.switchTab({
							url: "/pages/index/index"
						})
					}
				}, 1000)
			},
			// 提示
			showToast(msg, type) {
				uni.showToast({
					icon: type ? type : "none",
					title: msg
				})
			},
			back() {
				uni.navigateBack({
					delta: 1,
					animationType: 'pop-out',
					animationDuration: 200
				})
			}
		},
		onLoad(option) {
			const {
				mode
			} = option;
			if (mode === "refine") {
				uni.setNavigationBarTitle({
					title: "完善信息"
				})
				this.mode = mode;
				this.registerForm.phone = this.useAuthStore.phone;
			}else{
				uni.setNavigationBarTitle({
					title: "账号注册"
				})
				this.mode = 'register'
			}
			if(uni.getStorageSync("redirect")){
				this.redirect = uni.getStorageSync("redirect")
			}
			console.log(this.redirect,"重定")
		},
		onReady() {
			this.$refs.registerForm.setRules(this.rules);
		},
		computed: {
			useAuthStore() {
				return useAuthStore(); // 获取 store 实例
			}
		},
	}
</script>
<style lang="scss">
	.u-form-item {
		padding: 30rpx 0 !important;
	}

	.u-form-item .u-input--border {
		border-radius: 16rpx !important;
	}

	.u-form-item .u-form-item--left__content__label {
		display: block !important;
		text-align: justify;
		text-align-last: justify;
		padding: 0 20rpx 0 10rpx;
	}

	.u-input {
		background-color: #f7f7f7 !important;
	}
</style>
<style lang="scss" scoped>
	.container {
		height: 100vh;
		width: 100vw;
		background-color: #ffffff;
		padding: 0 40rpx;
	}

	.form-item-input {
		width: 100%;
	}

	.form-button {
		background: linear-gradient(90deg, #006af5, #21b0fc);
		border-radius: 20rpx;
		line-height: 80rpx;
		text-align: center;
		color: #fff;
		margin: 20rpx 0 50rpx;
	}

	.form-tip {
		text-align: center;
		color: #000000;
	}
</style>