<template>
	<view class="login">
		<view class="status_bar">
		</view>
		<view class="top">
			<image class="icon-logo" src="../../static/image/logo@3x.png" mode="aspectFit"></image>
			<text class="title">五粮液易商</text>
		</view>
		<view class="middle">
			<view class="account-block" v-show="loginType==='password'">
				<input class="account" type="text" v-model="account" placeholder="请输入账号"
					placeholder-class='placeholder-text' />
			</view>
			<view class="password-block" v-show="loginType==='password'">
				<input ref="password" class="password" :cursor='cursorNumber' type='text' :password="!passwordVisible"
					v-model="password" placeholder="请输入密码" placeholder-class='placeholder-text' />
				<template v-if="passwordVisible">
					<image class="icon-visible" src="../../static/image/visible@3x.png" mode="aspectFit"
						@click="handlePasswordVisible"></image>
				</template>
				<template v-else>
					<!-- 	<input class="password" type="text" v-model="password" placeholder="请输入密码"
						placeholder-class='placeholder-text' /> -->
					<image class="icon-visible" src="../../static/image/invisible@3x.png" mode="aspectFit"
						@click="handlePasswordVisible"></image>
				</template>
			</view>
			<!-- <view class="account-block" v-show="loginType==='phone'">
				<input class="account" type="tel" v-model="phone" placeholder="请输入手机号"
					placeholder-class='placeholder-text' />
			</view> -->
		</view>
		<view class="mui-input-row mui-checkbox remember-all">
			<view class="remember-num">
				<checkbox-group @change="checkboxChangeNum">
					<checkbox
						color="#FF1D32"
						id="chkRemNum"
						type="checkbox"
						:checked="rememberAt"
						@tap="rememberAt = !rememberAt"
						class="remember-check"
					>
					</checkbox>
					<text for="chkRemNum" class="remember-pass">记住账号</text>
				</checkbox-group>
			</view>
			<view class="">
				<checkbox-group @change="checkboxChange">
					<checkbox
						color="#FF1D32" 
						id="chkRem"
						type="checkbox"
						:checked="rememberPsw"
						@tap="rememberPsw = !rememberPsw"
						class="remember-check"
					>
					</checkbox>
					<text for="chkRem" class="remember-pass">记住密码</text>
				</checkbox-group>
			</view>
		</view>
		<view class="bottom">
			<button class="btn" type="default" @click="loginBtn" :class="{ 'btn-disabled': disabled }"
				:disabled="disabled"><text class="btn-text">{{loginBtnText}}</text></button>
			<!-- <view class="actions">
				<navigator url="/pages/forgetpassword/forgetpassword">
					<text class="forgetpassword-btn">忘记密码</text>
				</navigator>
				<text class="phone-btn" @click="fnChangeLogin">{{loginWayText}}</text>
			</view> -->
		</view>
	</view>
</template>

<script>
	import {
		mapMutations,
		mapState
	} from 'vuex'

	import {
		apiLogin,
		getIdToken
	} from '@/servers/user.js'
	
	const ToastPlusModule = uni.requireNativePlugin("ToastPlus") || uni.requireNativePlugin("UUMbsAgentPlugin-Test")
	export default {
		data() {
			return {
				accessToken: "",
				account: '',
				// password: 'DO1tjHPW0Z',
				password: '',
				phone: '',
				code: '',
				loginType: 'password',
				passwordVisible: false,
				disabled: false,
				cursorNumber: 0,
				rememberPsw: true,
				rememberAt: true,
				flag: false
			}
		},
		computed: {
			...mapState(['userInfo']),
			loginWayText() {
				return this.loginType === 'phone' ? '密码登录' : '手机号登录'
			},
			loginBtnText() {
				return this.loginType === 'phone' ? '获取验证码' : '登录'
			}
		},
		watch: {
			phone: {
				handler: function(val) {
					if (this.loginType === 'password') {
						this.disabled = false
						return
					}
					if (/^1\d{10}$/.test(val)) {
						this.disabled = false
					} else {
						this.disabled = true
					}
				},
				immediate: true
			}
		},
		onLoad() {
			ToastPlusModule && this.initEx()
		},
		onShow() {
			// 判断是否正在等待authEx的返回结果，第一次进入页面默认是false
			if (!this.flag && !this.accessToken) {
				ToastPlusModule && this.authEx()
			}
		},
		//页面初始加载
		mounted() {
			let that = this;
			//缓存的账号
			const username = uni.getStorageSync('username') || '';
			//缓存的密码
			const password = uni.getStorageSync('password') || '';
			console.log("密码",password,username)
			//有缓存就赋值给文本没有就清空
			that.account = username || ''
			that.password = password || ''
			that.handlePasswordVisible()
			that.$nextTick(()=>{
				setTimeout(function() {
					that.handlePasswordVisible()
				}, 100);
			})
		},
		methods: {
			initEx(){
				uni.showLoading({
					title: '加载中'
				});
				// 调用同步方法
				var obj = ToastPlusModule.registerSyncFunc({
					appKey: 'com.wuliangye.emobilewlycrm',
					secretKey: '9ab24ae4bfb349cca739ab15b78f1c7f8737eb73',
					packageName: 'com.uusafe.portal.wly'
				})
				console.log(obj)
			},
			checkboxChangeNum(){
				if (e.detail.value.length == 1) {
					//获取缓存的账号
					 uni.getStorageSync('username',this.account);
					 // uni.getStorageSync('password',this.password);
				} else {
					  uni.removeStorageSync('username');
					  // uni.removeStorageSync('password');              
				}
			},
			//复选框
			checkboxChange: function(e) {
				if (e.detail.value.length == 1) {
					//获取缓存的账号
					 // uni.getStorageSync('username',this.account);
					 uni.getStorageSync('password',this.password);
				} else {
					  // uni.removeStorageSync('username');
					  uni.removeStorageSync('password');
				}
			},
			// 切换密码可见性
			handlePasswordVisible() {
				this.passwordVisible = !this.passwordVisible;
				this.$refs.password.blur()
			},
			authEx(){
				uni.showLoading({
					title: '加载中'
				});
				// 开启等待被唤醒
				this.flag = true
				ToastPlusModule.registerExSyncFunc({}, res => {
					this.flag = false
					this.accessToken = res.data?.token || res
					this.getIdToken()
				})
			},
			
			async getIdToken(){
				uni.showLoading({
					title: '加载中'
				});
				const params ={
					// "uuid": "f3eea700a3686e47038a4b047af6d934DsRudwTZSRY", //测试环境
					// "uuid": "13a384b65f030d9a0a6636702ca6b0e5ygV3eEOmHBy", //生产环境
					// "uuid": "6fd9f0edf0f9ba7835458874f660e70cXvIY7K6wM6E", //新测试环境
					"uuid": "66f17cba953444c862cef50a3f58262fv4feQA1ghLm", //新生产环境
					"accessToken": this.accessToken
				}
				try{
					const res = await getIdToken(params)
					console.log(res,res.errorNumber-0===0)
						if(res.errorNumber - 0 === 0){
							uni.hideLoading();
							const parmasObj = {
								account: res.accounts[0].account,
								idToken: res.accounts[0].idToken,
								loginType: 'ystoken',
								idp: 4
							}
							this.goLogin(parmasObj, false)
						}else{
							uni.hideLoading();
							uni.showToast({
								title: res.errors && res.errors[0] || res.errorMessage,
								icon: 'none',
								duration: 1500
							});
							return
						}
						
				}catch(e){
					uni.showToast({
						title: e,
						icon: 'none',
						duration: 1500
					});
					//TODO handle the exception
				}
			},
			// 登录
			loginBtn(){
				if (this.flag) {
					this.authEx() 
					return
				}
				const parmas = {
					username: this.account,
					password: this.password,
					loginType: 'App',
					idp: 4
					// account: this.account,
					// idToken: this.password,
					// loginType: 'ystoken'
				}
				this.goLogin(parmas)
			},
			async goLogin(parmas,isValidate = true) {
				if (this.loginType === 'phone') {
					uni.navigateTo({
						url: `/pages/forgetpassword/get-captcha?phone=${this.phone}&loginType=${this.loginType}`
					});
				} else {
					const ispass = isValidate ? await this.validate() : true;
					if (!ispass) return;
					const res = await apiLogin(parmas)
					if (res.status === 1) {
						//缓存账号和密码
						if (this.rememberPsw) {
							uni.setStorageSync('password', this.password);
						} else {
							uni.removeStorageSync('password');   
						}
						if(this.rememberAt){
							uni.setStorageSync('username', this.account);
						} else {
							uni.removeStorageSync('username');
						}
						// uni.setStorageSync('username', this.account);
						// uni.setStorageSync('password', this.password);
						this.$uStore({
							name: 'userInfo',
							value: {
								...res.data.operator
							}
						});
						this.$uStore({
							name: 'userBpData',
							value: {
								...res.data.userBpData
							}
						});
						const isChildCustomer = res.data.userBpData.ROLES.some(user => user.ROLE_ID === 'WLY027');
						this.$uStore({
							name: 'isChildCustomer',
							value: isChildCustomer
						});
						this.$uStore({
							name: 'vuex_token',
							value: res.data.token
						});
						uni.switchTab({
							url: '/pages/home/home'
						});
					}else{
                        uni.showToast({
                            title: res.msg,
                            icon: 'none',
                            duration: 1500
                        });
					}
				}
			},
			fnChangeLogin() {
				if (this.loginType === 'phone') {
					this.loginType = 'password'
					this.disabled = false
				} else {
					this.loginType = 'phone'
					this.disabled = true
				}

			},
			// 校验input
			validate() {
				return new Promise((resolve, reject) => {
					let flag = true;
					if (this.account == "") {
						flag = false;
						uni.showToast({
							title: '输入账户不规范',
							icon: 'none',
							duration: 1500
						});
					} else if (this.password == '') {
						flag = false;
						uni.showToast({
							title: '输入密码不规范',
							icon: 'none',
							duration: 1500
						});
					}

					resolve(flag);
				})
			},
			...mapMutations(["$uStore"]),
		}
	}
</script>

<style lang="scss" scoped>
	.mui-checkbox input[type='checkbox']:checked:before {
	    color: #00bbb1;
	}
	.login {
		display: flex;
		flex-direction: column;
		padding: 0 40rpx;
	}

	.top {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.icon-logo {
		width: 128rpx;
		height: 128rpx;
		margin: 88rpx 0 48rpx;
	}

	.title {
		font-size: 20px;
		color: $text-base-color;
	}

	.middle {
		display: flex;
		flex-direction: column;
		margin: 100rpx 0 26rpx;
	}

	.placeholder-text {
		font-size: 34rpx;
		color: $wly-palcehold-color;
	}

	.account {
		flex: 1;
		color: $text-base-color;
		height: 100rpx;
		border-bottom: 1px solid #cfcfcf;
		padding-left: 12rpx;
	}

	.password {
		flex: 1;
		color: $text-base-color;
		height: 100rpx;
		border-bottom: 1px solid #cfcfcf;
		padding-left: 12rpx;
	}

	.password-block {
		position: relative;
		height: 100rpx;
	}

	.icon-visible {
		position: absolute;
		right: 24rpx;
		top: 50rpx;
		z-index: 10;
		width: 21px;
		height: 14px;
		margin-top: -7px;
	}

	.bottom {
		display: flex;
		flex-direction: column;
	}

	.btn {
		height: 92rpx;
		background: $wly-primary-color;
		border-radius: 46rpx;
	}

	.btn-disabled {
		background: rgba(255, 29, 50, 0.50) !important;
		color: #fff !important;
	}

	.btn-text {
		color: #fff;
		font-size: 34rpx;
	}

	.actions {
		margin-top: 36rpx;
		justify-content: space-between;
	}

	.forgetpassword-btn {
		font-size: 28rpx;
		color: $wly-palcehold-color;
	}

	.phone-btn {
		font-size: 28rpx;
		color: #666660;
	}
	.remember-all{
		margin-bottom: 28rpx;
	}
	.remember-num{
		margin-right: 60rpx;
	}
	.remember-check{
		margin-right: 10rpx;
	}
	.remember-pass {
	    color: #adadad;
	    margin-top: 8rpx;
		font-size: 32rpx;
	}
	::v-deep  .uni-checkbox-input{
		width: 40rpx;
		height: 40rpx;
	}
</style>
