<template>
	<view class="login-ctn">
		<view class="login-bg">
			<image src="http://static.drgyen.com/app/hc-app-power/images/login-header.png" mode=""></image>
		</view>
		<view class="login-header">
			<view class="login-header-img-box">
				<!-- #ifdef APP-PLUS -->
				<image class="login-header-img" :src="appConfig.logo" mode=""></image>
				<!-- #endif -->
				<!-- #ifndef APP-PLUS -->
				<image class="login-header-img" :src="appConfig.logo" mode=""></image>
				<!-- #endif -->
			</view>
			<view class="login-header-text">{{appConfig.name}}</view>
		</view>
		<view class="login-form-ctn">
			<view class="login-form">
				<u-form :model="form" :rules="rules" ref="uForm">
					<u-form-item v-if="tenantEnabled && isTenant" label=" " label-width="60" prop="tenantId" left-icon="account"
						:left-icon-style="{ color: '#ccc', fontSize: '30rpx' }">
						<view style="width: 100%;display: flex;align-items: center;justify-content: space-between;" @click="tenantShow=true">
							<text>{{activeTenantObj.companyName}}</text>
							<u-icon name="arrow-down"></u-icon>
						</view>
					</u-form-item>
					<u-form-item label=" " label-width="60" prop="username" left-icon="account"
						:left-icon-style="{ color: '#ccc', fontSize: '30rpx' }">
						<u-input v-model="form.username" placeholder="请输入手机号/账号" />
					</u-form-item>
					<u-form-item label=" " label-width="60" prop="password" left-icon="lock-open"
						:left-icon-style="{ color: '#ccc', fontSize: '36rpx' }">
						<u-input class="password-input" v-model="form.password" type="password" placeholder="请输入密码" />
					</u-form-item>
					<!-- <u-form-item label=" " label-width="60" prop="code" left-icon="chat"
						:left-icon-style="{ color: '#ccc', fontSize: '34rpx' }">
						<u-image slot="right" mode="scaleToFill" width="160" height="60" @click="getCodeImageFn"
							:src="'data:image/jpg;base64,' + captchaData.img"></u-image>
						<u-input v-model="form.code" placeholder="请输入验证码" />
					</u-form-item> -->
				</u-form>
				<view class="login-function-ctn">
					<text class="text--base--grey" @click="goPhoneLogin">我要注册</text>
				</view>
				<view class="login-button-ctn">
					<u-button shape="circle" :custom-style="{ background: 'linear-gradient(270deg, #0066CC 8%, #1890FF 100%)' , height:'100rpx'  }"
						@click="submit" type="primary">立即登录</u-button>
				</view>
				<view class="protocol-box">
					<!-- <u-checkbox v-model="protocolStatus">阅读并同意以下协议<text @click.stop="goPolicy">《用户协议》</text></u-checkbox> -->
				</view>
				<view class="other-login-box">
					<view class="other-login-item"  @click="goPhoneLogin">
						<view class="other-login-bg">
							<u-icon name="phone-fill" color="#fff" size="56"></u-icon>
						</view>
						<text class="other-login-name">手机登录</text>
					</view>
				</view>
			</view>

		</view>
		<view class="login-version-info">
			<view>Copyright 2022-2025. {{ icpLicense ? ' 备案号：' + icpLicense : '' }}</view>
		</view>
		<u-select v-model="tenantShow" :list="tenantList" label-name="companyName" value-name="tenantId" @confirm="changeTenant"></u-select>
		<u-toast ref="uToast" />
	</view>
</template>

<script>
	let userToken = '';
	import config from "@/common/api/config.js"
	export default {
		data() {
			return {
				protocolStatus: true,
				usetTypeValue: '企业用户',
				list: [{
						name: '普通用户',
					},
					{
						name: '企业用户',
					}
				],
				captchaData: null,
				current: 0,
				form: {
					clientId:  "",
					grantType: "password",
					rememberMe: false,
					tenantId: "",
					username: "",
					password: ""
				},
				mode:null,
				rules: {
					// 字段名称
					username: [{
						required: true,
						message: '请输入手机号/账号',
						trigger: ['change', 'blur'],
					}],
					password: [{
						required: true,
						message: '请输入密码',
						trigger: ['change', 'blur'],
					}],
					code: [{
						required: true,
						message: '请输入验证码',
						trigger: ['change', 'blur'],
					}]
				},
				tenantShow:false,
				tenantList:[],
				activeTenantObj:{
					tenantId: "",
					companyName: "",
					domain: "",
					logo: null,
					registerEnable: false
				},
				// 租户是否已启用
				tenantEnabled:true,
				query:{},
				isTenant: true,
				appIdMini:'',
				icpLicense:'',
				homePage:"/pages/tabBar/order"
			}
		},
		computed: {
			appConfig() {
				return this.$store.state.app.appConfig
			},
		},
		onLoad(e) {
			// #ifdef MP-WEIXIN
			const accountInfo = uni.getAccountInfoSync();
			this.appIdMini = accountInfo.miniProgram.appId;
			// #endif
			if(e){
				this.query = e;
			}
			if(e.tenantId){
				this.form.tenantId = e.tenantId;
			}
			// 普通二维码参数转小程序参数
			if (e.q  && e.q != "undefined") { //扫码进入
				const qrUrl = decodeURIComponent(e.q) // 获取到二维码原始链接内容
				//GetWxMiniProgramUrlParam() 这个方法是解析链接地址中的参数方法
				e = this.GetWxMiniProgramUrlParam(qrUrl); //此处就是我们要获取的参数 json
			}
			console.log("当前参数",e)
			if(e.mode){
				this.mode = e.mode;
			}
			this.getTenantList();
			if(e.mode == '1'){ //mode:1 带密码参数直接登录
				this.form.username = e.user || '';
				this.form.password = e.pwd || '';
				// this.autoLogin()
			}else{
				userToken = uni.getStorageSync('userToken');
				console.log("userToken", userToken)
				if (userToken) {
					uni.switchTab({
						url: this.homePage
					})
				} else {
					// this.getCodeImageFn();
				}
			}
			
			// this.usetTypeValue = e.userType == "user" ? "普通用户" : "企业用户";

		},
		onShow() {
			if(this.mode != '1'){
				uni.getStorage({
					key: 'username',
				}).then(res => {
					// 如果返回数组为两位就是正确
					if (res.length == 2) {
						this.form.username = res[1].data;
					}
					return uni.getStorage({
						key: 'password',
					})
				}).then(res => {
					if (res.length == 2) {
						this.form.password = res[1].data;
					}
				})
			}
			
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		methods: {
			getTenantList(){
				uni.request({
					url: config.baseUrl + "/auth/tenant/list",
					method: "GET",
					data: {},
					header: {
						Clientid: config.clientId
					},
					success: (res) => {
						console.log("res11",res);
						if(res.data.code == 200){
							let data = res.data.data;
							this.tenantEnabled = data.tenantEnabled === undefined ? true : data.tenantEnabled;
							if(this.tenantEnabled){
								this.tenantList = data.voList || [];
								let logo = '';
								let title = '';
								let icpLicense = '';
								let appIdPublic = '';
								// #ifdef H5
								if(this.query.tenantId){
									this.form.tenantId = this.query.tenantId;
									data.voList.forEach((item) => {
										if (item.tenantId === this.query.tenantId) {
											logo = item.logo;
											title = item.companyName;
											icpLicense = item.icpLicense || '';
											appIdPublic = item.appIdPublic || '';
										}
									});
									this.isTenant = false;
								} else if (data.voList != null && data.voList.length === 1 && data.voList[0].domain === window.location.host) {
									this.form.tenantId = data.voList[0].tenantId;
									logo = data.voList[0].logo;
									title = data.voList[0].companyName;
									icpLicense = data.voList[0].icpLicense || '';
									appIdPublic = data.voList[0].appIdPublic || '';
									this.isTenant = false;
								} else if (data.voList != null && data.voList.length !== 0) {
									this.form.tenantId = data.voList[0].tenantId;
									this.activeTenantObj = data.voList[0] ;
									logo = data.voList[0].logo;
									title = data.voList[0].companyName;
									icpLicense = data.voList[0].icpLicense || '';
									appIdPublic = data.voList[0].appIdPublic || '';
								}
								// #endif
								// #ifdef MP-WEIXIN
								if(this.appIdMini){
									let isAppid = true;
									data.voList.forEach((item) => {
										if (item.appId === this.appIdMini) {
											console.log("appId",item)
											this.form.tenantId = item.tenantId;
											logo = item.logo;
											title = item.companyName;
											icpLicense = item.icpLicense || '';
											appIdPublic = item.appIdPublic || '';
											isAppid = false;
										}
									});
									if(isAppid){
										this.form.tenantId = data.voList[0].tenantId;
										this.activeTenantObj = data.voList[0] ;
										logo = data.voList[0].logo;
										title = data.voList[0].companyName;
										icpLicense = data.voList[0].icpLicense || '';
										appIdPublic = data.voList[0].appIdPublic || '';
									}else{
										this.isTenant = false;
									}
								}else if (data.voList != null && data.voList.length !== 0) {
									this.form.tenantId = data.voList[0].tenantId;
									this.activeTenantObj = data.voList[0] ;
									appIdPublic = data.voList[0].appIdPublic || '';
									logo = data.voList[0].logo;
									title = data.voList[0].companyName;
									icpLicense = data.voList[0].icpLicense || '';
									appIdPublic = data.voList[0].appIdPublic || '';
								}
								// #endif
								console.log("title",title,logo)
								if(title){
									this.appConfig.logo = logo;
									this.appConfig.name = title;
									this.appConfig.appIdPublic = appIdPublic;
								}else{
									this.appConfig.logo = '';
									this.appConfig.name = this.$store.state.app.appConfig;
									this.appConfig.appIdPublic = appIdPublic;
								}
								if(icpLicense){
									this.icpLicense = icpLicense;
								}
							}
						}
					}
				});
			},
			changeTenant(e){
				console.log("e",e[0].value)
				this.tenantList.forEach((item) => {
					if (item.tenantId == e[0].value) {
						this.activeTenantObj = item;
						this.form.tenantId = item.tenantId;
						this.appConfig.logo = item.logo;
						this.appConfig.name = item.companyName;
						this.appConfig.appIdPublic = item.appIdPublic;
						this.icpLicense = item.icpLicense || '';
					}
				});
			},
			GetWxMiniProgramUrlParam(url) {
			  let theRequest = {};
			  if (url.indexOf("#") != -1) {
			    const str = url.split("#")[1];
			    const strs = str.split("&");
			    for (let i = 0; i < strs.length; i++) {
			      theRequest[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
			    }
			  } else if (url.indexOf("?") != -1) {
			    const str = url.split("?")[1];
			    const strs = str.split("&");
			    for (let i = 0; i < strs.length; i++) {
			      theRequest[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
			    }
			  }
			  return theRequest;
			},
			// 跳转密码登录页
			goPhoneLogin(){
				uni.reLaunch({
					url: './codeLogin'
				});
			},
			goPolicy() {
				uni.navigateTo({
					url: '/pages/tabBar/my/userPolicy'
				})
			},
			// goForgotPasswordFn() {
			// 	uni.navigateTo({
			// 		url: `./forgotPassword?userType=${this.usetTypeValue=="普通用户"?"user":"company"}`
			// 	})
			// },
			// 获取验证码
			getCodeImageFn() {
				this.$get("/captchaImage").then((res) => {
					console.log(res, "resss");
					this.captchaData = res;
				})
			},
			// 自动登录
			autoLogin(){
				uni.request({
					url: config.baseUrl + "/login",
					method: "POST",
					data: {
						username: this.form.username,
						password: this.form.password,
					},
					header: {
						// UserType: this.usetTypeValue == "普通用户" ? "PERSONAL" : "TENANT",
					},
					success: (res) => {
						console.log(res);
						if (res.data.token) {
							this.$refs.uToast.show({
								title: '登录成功',
								type: 'success',
							})
							this.$store.dispatch('setLogin', res.data.token);
							uni.setStorage({
								key: 'appIdPublic',
								data: this.appConfig.appIdPublic,
							}).then(res => {
								return uni.setStorage({
									key: 'username',
									data: this.form.username,
								})
							}).then(res => {
								return uni.setStorage({
									key: 'password',
									data: this.form.password,
								})
							}).then(res => {
								setTimeout(() => {
									// if (this.usetTypeValue == "普通用户") {
									// 	uni.reLaunch({
									// 		url: "../oneselfUser/index"
									// 	})
									// } else {
										uni.switchTab({
											url: this.homePage
										})
									// }
								}, 1000)
							})
						} else {
							this.$u.toast(res.data.msg)
							this.form.code = "";
							// this.getCodeImageFn();
						}
					}
				});
			},
			submit() {
				if(!this.protocolStatus){
					this.$refs.uToast.show({
						title: '请先阅读并同意用户协议',
					})
				}else{
					this.$refs.uForm.validate(valid => {
						 if (valid) {
							uni.request({
								url: config.baseUrl + "/auth/login",
								method: "POST",
								data: {
									...this.form,
									clientId: config.clientId,
								},
								header: {
									Clientid: config.clientId
								},
								success: (res) => {
									console.log(res);
									
									if (res.data.code == 200 && res.data.data.access_token) {
										this.$refs.uToast.show({
											title: '登录成功',
											type: 'success',
										})
										this.$store.dispatch('setLogin', res.data.data.access_token);
										uni.setStorage({
											key: 'appIdPublic',
											data: this.appConfig.appIdPublic,
										}).then(res => {
											return uni.setStorage({
												key: 'tenantId',
												data: this.form.tenantId,
											})
										}).then(res => {
											return uni.setStorage({
												key: 'username',
												data: this.form.username,
											})
										}).then(res => {
											return uni.setStorage({
												key: 'password',
												data: this.form.password,
											})
										}).then(res => {
											
											setTimeout(() => {
												// if (this.usetTypeValue == "普通用户") {
												// 	uni.reLaunch({
												// 		url: "../oneselfUser/index"
												// 	})
												// } else {
													uni.switchTab({
														url: this.homePage
													})
												// }
											}, 1000)
										})
									} else {
										this.$u.toast(res.data.msg)
										this.form.code = "";
										// this.getCodeImageFn();
									}
								}
							});
						} else {
							console.log('验证失败');
						}
					});
				}
				
			}
		}
	}
</script>

<style lang="scss" scoped>
	.login-ctn {
		width: 100%;
		height: 100%;
    padding-top: 500rpx;
		background: #fff;
		:not(not) {
			box-sizing: border-box;
		}
	}

	.login-bg {
		width: 100%;
		height: 515rpx;
		position: absolute;
		left: 0;
		top: 0;
		z-index: 1;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.login-header {
		width: 100%;
		position: absolute;
		left: 0;
		top: 0;
		z-index: 10;
		height: 500rpx;
		display: flex;
		flex-direction: column;
		align-items: center;

		.login-header-img-box {
			margin-top: 132rpx;
			margin-left: 2rpx;
			border-radius: 50%;
			background: #FFFFFF;
		}

		&-img {
			display: block;
			width: 198rpx;
			height: 198rpx;
		}

		&-text {
			font-size: 40rpx;
			line-height: 40rpx;
			font-family: Source Han Sans CN;
			font-weight: 500;
			color: #FFFFFF;
			margin-top: 40rpx;
		}
	}


	.login-form-ctn {
		margin-bottom: 20rpx;

		.login-form {
			background-color: #fff;
			padding: 20rpx 60rpx;

			&-title {
				text-align: center;
				font-size: 40rpx;
				font-family: Source Han Sans CN;
				font-weight: 800;
				color: #262626;
			}
		}
	}

	.login-button-ctn {
		margin-top: 20rpx;
	}


	.login-function-ctn {
		display: flex;
		// justify-content: flex-end;
		padding: 30rpx 0rpx;
	}

	.login-version-info {
		position: absolute;
		left: 0;
		bottom: 40rpx;
		width: 100%;
		text-align: center;
		font-size: $uni-font-size-sm;
		color: #aaa;
	}

	.protocol-box {
		padding: 20rpx 0;
		color: #f5f5f5;
		font-size: 26rpx;

		text {
			color: #0066cc;
		}
	}

	.other-login-box {
		margin-top: 20rpx;
		display: flex;
		justify-content: center;
		align-items: center;

		.other-login-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			.other-login-bg {
				width: 100rpx;
				height: 100rpx;
				border-radius: 50%;
				background: #0066cc;
				display: flex;
				justify-content: center;
				align-items: center;
				margin-bottom: 10rpx;
			}

			.other-login-name {
				color: #7d7d7d;
				font-weight: bold;
			}
		}
	}
</style>