<template>
	<view class="loginContent">
		<page-meta :root-font-size="$pageSize + 'px'"></page-meta>
		<u-icon :style="{
			top: (statusBarHeight + 45) + 'rpx'
		}" @click="gotoback" name="arrow-left" size="40" class="back"></u-icon>
		<!-- <headers class="fixedheader" :showBack="true">
			<view class="headerName">
			</view>
		</headers> -->
		<view class="loginbg">
			<view class="login_logo">
				<view class="logo_box">
					<image src="@/static/bthgIcon/login_icon1.png" mode="" />
					<text>神华包头煤制烯烃升级示范项目</text>
				</view>
				<image src="@/static/bthgIcon/login_bg2.png" mode=""></image>
			</view>
		</view>
		<view v-if="!showForm" class="loginBack"></view>
		<view class="loginForm" v-if="showForm">
			<!-- <view class="Title">登录</view> -->
			<u-form style="width: 100%;" :error-type="['toast']" :model="formData" ref="uForm">
				<u-form-item prop="account" class="uni-form-item" :border-bottom="false">
					<view class="icon_input">
						<image class="account_Icon" src="@/static/bthgIcon/login_icon2.png" mode="" />
					</view>
					<input class="uni-input" name="account" v-model="formData.account" placeholder="请输入您的账号" />
				</u-form-item>
				<u-form-item prop="account" class="uni-form-item" :border-bottom="false">
					<view class="icon_input">
						<image class="password_Icon" src="@/static/bthgIcon/login_icon3.png" mode="" />
					</view>
					<input class="uni-input" name="password" v-model="formData.password" :password="showPassword"
						placeholder="请输入您的密码" />
					<u-icon :name="showPassword ? 'eye-fill' : 'eye-off'"
						@click.stop="isShowPassword"></u-icon>
				</u-form-item>
				<view class="uni-form-item ischecked_box">
					<view class="ischecked">
						<label class="radio">
							<radio @click="isCheckedFn" :checked="formData.checked" />
						</label>
						记住密码
					</view>
				</view>
				<view class="uni-form-item submit">
					<button type="primary" class="btn" @click="formSubmit">登录</button>
				</view>
			</u-form>
			<view class="between">
				<!-- <view class="link" @click="forgetPassword">忘记密码</view> -->
				<!-- <view class="link" @click="goToPage">{{ type == "user" ? "用户账号注册" : "供应商账号注册" }}</view> -->
			</view>
		</view>
		<view class="selectDept" v-else>
			<view class="title">选择组织</view>
			<view class="dpetList">
				<view class="deptItem" v-for="(item,index) in deptList" :key="index" @click="clickDept(item)">
					<image class="icon" mode="heightFix" src="@/static/enterprise.png"></image>
					<view class="name">{{ item.companyName }}</view>
					<view class="next">
						<u-icon name="arrow-right"></u-icon>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import CryptoJS from 'crypto-js'
	export default {
		data() {
			return {
				statusBarHeight: 0,
				showForm: true,
				type: uni.getStorageSync("Type"), // user 用户 supplier 供应商
				showPassword: true,
				saveForm: {},
				formData: {
					account: '',
					password: '',
					checked: false,
				},
				deptList: [],
				isChecked: false,
			};
		},
		methods: {
			isShowPassword(){
				this.showPassword = !this.showPassword;
				console.log(this.showPassword)
			},
			gotoback() {
				// uni.navigateBack({
				// 	delta: 1
				// })
				uni.navigateTo({
				        url: '/pages/projectEnd/projectIndex/projectIndex'
				    })
			},
			clickDept(item) {
				// 选择部门
				console.log(item);
				// uni.setStorageSync("dept", item)
				uni.setStorageSync("company", item); // 最外层的企业ID
				this.init(this.saveForm);
				if (this.type == "user") {
					uni.reLaunch({
						url: '/pages/projectEnd/projectIndex/projectIndex?fromPage=loginPage'
					})
					// uni.reLaunch({
					// 	url: '/pages/homePage/homePage?fromPage=loginPage'
					// })
				} else if (this.type == "supplier") {
					uni.reLaunch({
						url: '/pages/supplier/supplier'
					})
				}

			},
			isCheckedFn() {
				this.formData.checked = !this.formData.checked;
			},
			getDeptList(data, status = false) {
				// 获取改角色的部门
				let params = {
					userId: data.userId
				}
				if (!status) {
					params.headquartersSn = data.headquartersSn
				}
				this.sendRequest({
					// url: "xmgl/company/getTenantOrgTreeList",
					url: "xmgl/company/getMyHeadquarterCompanyList",
					data: params,
					header: {
						Authorization: "Bearer " + data.token
					},
					method: "POST",
					success: (res) => {
						uni.hideLoading()
						if (this.type == "supplier" && res.result.length <= 0) {
							// 如果登录的是供应商并且组织为空 跳转到个人资质页面
							this.init(this.saveForm);
							uni.reLaunch({
								url: "/pages/supplier/qualifications/qualifications?isNull=1"
							})
							return;
						}


						this.showForm = false;
						this.deptList = res.result;
						if (this.deptList.length == 1) {
							this.clickDept(this.deptList[0]);
						}
						console.log(res);
					}
				})
			},
			formSubmit() {
				// 登录
				this.$refs.uForm.validate(valid => {
					if (this.formData.account == "") return uni.showToast({
						title: "请输入账号",
						icon: "none"
					})
					if (this.formData.password == "") return uni.showToast({
						title: "请输入密码",
						icon: "none"
					})
					// if (!this.isChecked) return uni.showToast({
					// 	title: "请勾选隐私政策",
					// 	icon: "none"
					// })
					if (valid) {
						// 验证成功
						let timestamp = Date.now();
						uni.showLoading({
							title: "登录中"
						})
						this.sendRequest({
							url: "xmgl/base/md5/login",
							data: {
								account: this.formData.account,
								md5Password: CryptoJS.MD5(CryptoJS.MD5(this.formData.password).toString() +
									timestamp).toString(),
								timestamp,
								clientId: this.clientid,
								isApp: 1,
							},
							method: "POST",
							success: (res) => {
								let {
									accountType
								} = res.result;
								if (res.result.expire) {
									this.userInfo = {
										userId: res.result.userId,
										account: res.result.account,
										token: res.result.token,
									};
									let that = this;

									uni.showModal({
										title: '提示',
										content: '密码有效期已超过90天，为确保您的账号安全，请重新修改密码！',
										success: function(res) {
											if (res.confirm) {
												uni.navigateTo({
													url: `/pages/my/changePassword/changePassword?userInfo=${JSON.stringify(that.userInfo)}`,
												});

											} else if (res.cancel) {
												console.log('用户点击取消');
											}
										}
									});
									return
								}

								if (this.formData.checked) {
									const encrypted = CryptoJS.AES.encrypt(this.formData.password,
										'secret-key').toString();
									uni.setStorageSync(
										'encryption',
										JSON.stringify({
											...this.formData,
											password: encrypted
										})
									);
								} else {
									uni.removeStorageSync('encryption');
								}


								this.sendRequest({
									url: "xmgl/projectConfig/list",
									data: {
										projectSn: res.result.sn,
									},
									header: {
										Authorization: "Bearer " + res.result.token
									},
									method: "get",
									success: (res) => {
										if (res.result.records.length > 0) {
											console.log(res.result.records[0])
											uni.setStorageSync('projectInfoType', JSON
												.stringify(res.result.records[0]));
										}
									}
								})


								if (accountType == 5 || accountType == 6 || accountType == 10) {
									if (this.type == "user") {
										// 用户端
										this.saveForm = res.result;
										this.getDeptList(res.result);
										// 去选择部门
									} else {
										uni.hideLoading()
										uni.showToast({
											title: "当前登录账号与所选登录方式不符，无法登录",
											icon: "none"
										})
									}
									// uni.redirectTo({
									// 	url: '/pages/workstation/workstationIndex/workstationIndex'
									// })
								} else if (accountType == 11) {
									// 供应商
									uni.hideLoading()
									if (this.type == "supplier") {
										// 供应商端
										this.saveForm = res.result;
										this.getDeptList(res.result, true);
										// this.init(res.result);
										// uni.reLaunch({
										// 	url: '/pages/supplier/supplier'
										// })
									} else {
										uni.showToast({
											title: "当前登录账号与所选登录方式不符，无法登录",
											icon: "none"
										})
									}
								} else {
									// 集团
									uni.hideLoading()
									this.init(res.result);
									uni.redirectTo({
										url: '/pages/projectManage/projectManage'
									})
								}
							}
						})
					}
				});
			},
			init(data) {
				// #ifdef APP-PLUS
				// add:添加登录CID绑定功能  实现推送 2022年4月20日 10:47:41 罗劲章// add:添加登录CID绑定功能  实现推送 2022年4月20日 10:47:41 罗劲章
				plus.push.getClientInfoAsync((info) => {
					const clientId = info["clientid"];
					// console.log(cid,"cidcidcidcidcid")
					// const cid = "f4b3246189fc051c5875a35e198ca223";
					const alias = data.userId;
					//触发绑定请求
					this.sendRequest({
						url: "xmgl/push/bindAlias", //替换掉后端彭定生的接口
						data: {
							clientId,
							alias
						},
						method: "POST"
					})
				});
				// #endif
				uni.setStorageSync('wflow-token', data.token);
				uni.setStorageSync('account', this.formData.account);
				uni.setStorageSync('password', this.formData.password);
				uni.setStorageSync('userInfo', JSON.stringify(data));
				uni.setStorageSync('userInfoObj', data);
			},
			forgetPassword() {
				// 忘记密码
				uni.navigateTo({
					url: `/pages/login/forgetPassword/index?type=${this.type}`
				})
			},
			goToPage() {
				// 判断类型进入不同的注册页面
				uni.navigateTo({
					url: this.type == "user" ? "/pages/login/user/userRegister" :
						"/pages/login/supplier/supplierRegister"
				})
			}
		},
		onLoad(option) {
			let _this = this;
			// #ifdef APP-PLUS
			this.statusBarHeight = uni.getStorageSync('systemInfo').statusBarHeight;
			// add:添加登录CID绑定功能  实现推送 2022年4月20日 10:47:41 罗劲章// add:添加登录CID绑定功能  实现推送 2022年4月20日 10:47:41 罗劲章
			plus.push.getClientInfoAsync((info) => {
				const clientid = info["clientid"];
				console.log(clientid, "cidcidcidcidcid")
				_this.clientid = clientid
			});
			// #endif
			if (option.type) {
				// 获取上个页面传入的类型
				this.type = option.type || uni.getStorageSync("Type");
			}  else {
				this.type = "user";
			}
			
			const encryption = uni.getStorageSync('encryption');
			if (encryption) {
				const form = JSON.parse(encryption);
				const decrypted = CryptoJS.AES.decrypt(form.password, 'secret-key').toString(CryptoJS.enc.Utf8);
				console.log(decrypted, form);
				this.formData = {
					account: form.account,
					password: decrypted,
					checked: form.checked
				};
			}
		}
	}
</script>

<style lang="scss" scoped>
	.fixedheader{
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		z-index: 2;
		:deep( .headerBox ){
			background-color: transparent;
		}
	}
	:deep( uni-radio .uni-radio-input ){
		width: 36rpx;
		height: 36rpx;
	}

	.ischecked {
		display: flex;
		align-items: center;
	}

	a {
		text-decoration: none;
		color: #5181F6;
	}

	.loginContent {

		// padding: 80rpx 30rpx;
		.loginbg {
			width: 100%;
			height: 882rpx;
			background-image: url(@/static/bthgIcon/login_bg1.png);
			background-repeat: no-repeat;
			background-size: 100% 100%;
			position: relative;

			.login_logo {
				width: 100%;
				position: absolute;
				top: 148rpx;
				left: 50%;
				transform: translateX(-50%);
				text-align: center;

				.logo_box {
					display: flex;
					align-items: center;
					justify-content: center;
					font-size: 40rpx;
					color: #707070;

					>image {
						width: 72rpx;
						height: 48rpx;
					}
				}

				>image {
					width: 266rpx;
					height: 62rpx;
					margin-top: 20rpx;
				}
			}
		}

		.back {
			position: fixed;
			left: 15rpx;
			top: 15rpx;
			z-index: 9999;
		}

		.loginBack {
			position: fixed;
			left: 0;
			top: 0;
			right: 0;
			bottom: 0;
			z-index: -1;
			background: url("@/static/WechatIMG15-2.jpg");
			background-size: cover;
		}

		.loginForm {
			padding: 80rpx 80rpx 0;


			.Title {
				font-size: 70rpx;
				font-weight: 700;
				margin-bottom: 40rpx;
			}

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

			.uni-form-item:not(:first-child) {
				margin-top: 44rpx;
			}

			.uni-form-item {
				display: flex;
				justify-content: center;
				width: 100%;
				height: 90rpx;
				background: #F2F2FC;
				border-radius: 32rpx;
				padding: 0 32rpx;

				.icon_input {
					width: 64rpx;
					height: 64rpx;
					text-align: center;

					.account_Icon {
						width: 42rpx;
						height: 42rpx;
					}

					.password_Icon {
						width: 64rpx;
						height: 64rpx;
					}
				}


				&.submit {
					border: none;
					margin-top: 72rpx;
					background-color: transparent;
					padding: 0;

				}

				.uni-input {
					// width: 100%;
					flex: 1;
					padding: 15rpx 0;
					margin-left: 28rpx;
					font-size: 32rpx;
				}

				.btn {
					width: 100%;
					font-size: 32rpx;
					height: 92rpx;
					line-height: 92rpx;
					background: #2D8EF3;
					border-radius: 14rpx;
				}

				&.ischecked_box {
					border: none;
					background-color: transparent;
					justify-content: flex-end;
					padding: 0;
					font-size: 28rpx;
					color: #171717;
				}
			}

			.between {
				display: flex;
				justify-content: space-between;
				margin-top: 30rpx;

				.link {
					color: $uni-color-primary;
				}
			}
		}

		.selectDept {
			position: fixed;
			background-color: #fff;
			left: 40rpx;
			right: 40rpx;
			top: 50%;
			transform: translateY(-50%);
			box-shadow: 2rpx 6rpx 12rpx 1rpx #eee;
			border-radius: 8rpx;

			>.title {
				font-size: 50rpx;
				color: $uni-color-primary;
				padding: 20rpx 0;
				text-align: center;
			}

			.dpetList {
				margin-bottom: 50rpx;
				max-height: 400rpx;
				overflow: auto;

				.deptItem {
					padding: 35rpx 40rpx;
					display: flex;

					&:active {
						background-color: #f8f8f8;
					}

					.icon {
						width: auto;
						height: 35rpx;
						margin: auto 10rpx;
					}

					.name {
						flex: 1;
					}

					.next {}
				}
			}
		}
	}

	// @media screen and (min-width:768px) {
	// 	.loginbg {
	// 		height: 582rpx !important;
	// 	}
	// 	.loginForm {
	// 		padding: 60rpx 60rpx 20rpx !important;
	// 	}
	// }
</style>