<!-- 账号绑定 -->
<template>
	<view class="account-bound">
		<view class="main">
			<u--form
				labelPosition="left"
				:model="form"
				:rules="rules"
				labelWidth="100"
				ref="form">
				<u-form-item label="手机号" prop="name" borderBottom :required="true">
					<u--input
						placeholder="手机号"
						v-model="form.name"
						border="none"
						clearable
					></u--input>
				</u-form-item>
				
				<u-form-item label="密码" prop="password" borderBottom :required="true">
					<u--input
						placeholder="密码"
						v-model="form.password"
						border="none"
						clearable
					></u--input>
				</u-form-item>
				
				<u-form-item label="验证码" prop="code" borderBottom :required="true">
					<u--input
						placeholder="验证码"
						v-model="form.code"
						border="none"
					></u--input>
					<view class="code-img-wrapper" @click="updateImageCode">
					  <!-- <canvas style="width: 280rpx;height: 140rpx;" canvas-id="canvas"></canvas> -->
					  <image :src="codeUrl" style="width: 140px;height: 60px;"></image>
					</view>
				</u-form-item>
			</u--form>
		</view>
		<view class="button" @click="submit">确定</view>
		<view class="reister">
			<view> </view>
			<!-- <view @click="changePage('changePassword')">忘记密码</view> -->
			<view @click="changePage('register')">还没账号？去注册</view>
		</view>
	</view>

</template>

<script>
	import { Mcaptcha  } from '../../common/mcaptcha.js';
	import { loginUser,encryption, getCode, decryption } from '../../api/mine.js'
	import { hexMD5, b64Md5} from '../../common/md5.js'
	export default {
		data() {
			return {
				timeStr: '', // 验证码时间戳
				codeUrl: '', // 验证码图片
				rules: {
					// 用户名
					'name': [
						{
							type: 'string',
							required: true,
							message: '请填写用户名',
							trigger: ['blur', 'change']
						},
						{
							// 自定义验证函数
							validator: (rule, value, callback) => {
								// 上面有说，返回true表示校验通过，返回false表示不通过
								// uni.$u.test.mobile()就是返回true或者false的
								return uni.$u.test.mobile(value);
							},
							message: '请输入正确的手机号',
							// 触发器可以同时用blur和change
							trigger: ['change','blur'],
						}
						// {
						// 	min: 8,
						// 	max: 30,
						// 	message: '长度在8-30个字符之间'
						// }
					],
					// 新密码规则
					'password': [
						{
							type: 'string',
							required: true,
							message: '请填写密码',
							trigger: ['blur', 'change']
						},
						{
							min: 8,
							max: 30,
							message: '长度在8-30个字符之间'
						},
					],
					// 验证码规则
					'code': [
						{
							type: 'string',
							required: true,
							message: '请填写验证码',
							trigger: ['blur', 'change']
						},
						{
							// 自定义验证函数
							validator: (rule, value, callback) => {
								let validate = this.mcaptcha.validate(value)
								if(validate) {
									return true
								}
								callback(new Error('验证码错误'));
							},
						}
					],
				},
				form: {
					name: '',  //用户名
					password: '',  //密码
					code: '',  //验证码
					token:''
				},
			}
		},
		onReady() {
			this.$refs.form.setRules(this.rules);
			// this.mcaptcha = new Mcaptcha({
			// 	el: 'canvas',
			// 	width: 140,
			// 	height: 80,
			// 	createCodeImg: ""
			// });
			this.fetchCodeURl() // 获取验证码
		},
		methods: {
			submit() {
				this.$refs.form.validate().then(async (res) => {
					// uni.$u.toast('校验通过')
					// 登录接口
					// 账号密码加密
					const name = await encryption(this.form.name)
                    // 提交信息
					const data = {
						timeStr:this.timeStr,
						'userInfoVo.account': name,
						'userInfoVo.password': hexMD5(this.form.password),
						'userInfoVo.verifyCode': this.form.code,
						token:''
					}
					loginUser(data).then(res => {
						// console.log(res, '用户信息')
						uni.$u.toast('登陆成功')
						const userInfo = res
						decryption(res.account).then(res => {
							wx.setStorageSync('userAccount', res)
						})
						decryption(res.phone).then(res => {
							wx.setStorageSync('userPhone', res)
						})
						wx.setStorageSync('userInfoxj', userInfo)
							wx.switchTab({
							url:'/pages/mine/mine'
						})
					}).catch((error) => {
						console.log(error)
						// 登陆失败更换验证码
						this.updateImageCode()
					})
					// 模拟登录成功
					// const userInfo = {
					// 	id:'b56d2019f49353aa85a93c06228b8d80', 
					// 	account:'test001',
					// 	name:'姓名',
					// 	sex:'性别',
					// 	nation:'民族', 
					// 	IDCard:'身份证号',
					// 	phone:'13712345678', 
					// 	email:'123456789@163.com',
					// 	country:'国家', 
					// 	province:'省', 
					// 	city:'市', 
					// 	county:'县', 
					// 	address:'详细地址', 
					// 	regTime:'注册时间'}
					// wx.setStorageSync('userInfoxj', userInfo)
					// setTimeout(() => {
					// 	wx.switchTab({
					// 		url:'/pages/mine/mine'
					// 	},500)
					// })
				}).catch(errors => {
					console.log(errors, 'errors')
					uni.$u.toast('请将信息填写完整')
				})
			},
			// // 刷新验证码
			// updateImageCode() {
			//   this.mcaptcha.refresh()
			// },
			// 换验证码
			updateImageCode() {
				this.fetchCodeURl()
			},
			// 获取验证码
			fetchCodeURl() {
				var that = this
				that.timeStr = new Date().getTime()
				wx.request({
				  url: `https://www.xjwljb.com/webserver/captchaController/generateVerifyCodeOfReport.do?timeStr=${that.timeStr}`,
				  method: 'POST',
					data: {
						index: '0.6261334077388199'
					},
					header:{
						'content-type': 'application/x-www-form-urlencoded'
					},
				  success(res) {
						if(res.statusCode === 200) {
							that.codeUrl = res.data
						}
				  },
				  fail(err) {
						console.log('fail', err)
				    reject(err);
				  },
				});
			},
			// 忘记密码或注册
			changePage(val) {
				let url = `/packageMine/${val}/${val}`
				wx.navigateTo({
					url: url
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.reister{
		padding: 0 10px;
		display: flex;
		justify-content: space-between;
	}
	.account-bound {
		width: 100%;
		height: 100%;
		padding: 40rpx 20rpx;
		box-sizing: border-box;
		background: linear-gradient(#bed5fe 0%, #eef1fd 100%);
		.main {
			padding: 20rpx 20rpx 40rpx 20rpx;
			box-sizing: border-box;
			background-color: #fff;
			border-radius: 16rpx;
		}
		.button {
			width: 100%;
			display: flex;
			justify-content: center;
			align-items: center;
			padding: 20rpx;
			color: #fff;
			font-weight: 600;
			letter-spacing: 4rpx;
			background-color: #408bf6;
			border: 2rpx solid #408bf6;
			border-radius: 10rpx;
			margin: 64rpx 0 32rpx 0;
			white-space: nowrap;
			box-sizing: border-box;
			&:active {
				background-color: #fff;
				color: #408bf6;
			}
		}
	}
</style>
<style lang="scss">
	.account-bound {
		.u-form-item__body__left__content__label {
			white-space: nowrap;
			font-weight: 600;
		}
		.u-form-item__body__right__content__slot {
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			align-items: center;
		}
		.u-form-item {
			margin-bottom: 20rpx;
		}
	}
</style>
