<template>
	<view class="normal-login-container">
		<view class="top">
			<view class="title">作业管控智慧平台</view>
		</view>
		<view class="content">
			<view class="top-msg">
				<view class="msg1">今日消息</view>
				<view class="msg2">
					<view class="msg-content">
						<u-notice-bar :text="msgList" direction="column" icon="" bgColor="" color="#000"
							font-size="16"></u-notice-bar>
					</view>
					<view class="box">
						<u-badge max="99" :value="value" shape="horn" bgColor="red"></u-badge>
					</view>
				</view>
			</view>
			<view class="yy-box">
				<view class="bt">我的应用</view>
				<view class="yy-list">
					<view class="yy-one" @click="gotoYy(item.appName)" v-for="(item,index) in myApp" :key="index">
						<view class="yy-img">
							<image :src="item.base64Url"></image>
						</view>
						<view class="yy-name">{{item.appName}}</view>
					</view>
				</view>
			</view>
			<view class="yy-box">
				<view class="bt">全部应用</view>
				<view class="yy-list">
					<view class="yy-one" @click="gotoYy(item.appName)" v-for="(item,index) in allApp" :key="index">
						<view class="yy-img">
							<image :src="item.base64Url"></image>
						</view>
						<view class="yy-name">{{item.appName}}</view>
					</view>
				</view>
			</view>

		</view>


		<view>
			<!-- 普通弹窗 -->
			<uni-popup ref="popup" background-color="#fff" :is-mask-click="false">
				<view style="text-align: center;font-size: 40rpx;padding-top: 30rpx;">密码修改</view>
				<view class="popup-content">
					<u--form :model="restForm" ref="uForm3" :rules="rules3" labelWidth="60">
						<view
							style="color: red;line-height: 30rpx;font-size: 24rpx;padding-top: 20rpx;text-align: center;">
							您是第一次登录系统，需要修改密码！
						</view>
						<u-form-item label="新密码" prop="password">
							<u-input class="login-input" :type="isOpen?'text':'password'" placeholder="请输入密码" prefixIcon="lock"
								v-model="restForm.password" save="false" autocomplete="new-password">
								<template slot="suffix">
									<image @click="isOpen=!isOpen"
										style="width: 40rpx;height: 40rpx;margin-right: 10rpx; z-index: 999;"
										:src="isOpen?'../../static/images/design_ic_visibility.png':'../../static/images/design_ic_visibility_off.png'">
									</image>
								</template>
							</u-input>
						</u-form-item>
						<u-form-item label="新密码" prop="passwordA">
							<u-input class="login-input" :type="isOpen2?'text':'password'" placeholder="请再次输入密码" prefixIcon="lock"
								v-model="restForm.passwordA" save="false" autocomplete="new-password">
								<template slot="suffix">
									<image @click="isOpen2=!isOpen2"
										style="width: 40rpx;height: 40rpx;margin-right: 10rpx; z-index: 999;"
										:src="isOpen2?'../../static/images/design_ic_visibility.png':'../../static/images/design_ic_visibility_off.png'">
									</image>
								</template>
							</u-input>
						</u-form-item>
						<view style="color: red;line-height: 30rpx;font-size: 24rpx;padding-top: 20rpx;">
							注：密码必须至少包含一个大写字母、一个小写字母、一个数字和一个特殊符号，并且长度在8到16个字符之间
						</view>
						<view style="display: flex;">
							<u-button class="loginBtn" style="margin-top: 30rpx;width: 30%;color: black;"
								@click="logout" color="#d0d2d5">退出</u-button>
							<u-button class="loginBtn" style="margin-top: 30rpx;width: 30%;" @click="submit"
								color="#00367a">确认</u-button>
						</view>

					</u--form>
				</view>
			</uni-popup>
		</view>
		<u-toast ref="uToast"></u-toast>
		<m-tabbar fixed fill :current="1" :tabbar="tabbar"></m-tabbar>
	</view>
</template>

<script>
	import TabbarConfig from '@/totalTabbar.js'
	import config from '@/config'

	import {
		getDayNoticeAnnoByUserId,
		getAppList,
		getMyAppByUser,
		updatePwdByApp,
		getNoticeAnnoByUserId
	} from "@/api/index.js"
	export default {
		data() {
			const equalToPassword = (rule, value, callback) => {
				if (this.restForm.password !== value) {
					callback(new Error("两次输入的密码不一致"));
				} else {
					callback();
				}
			};
			// 密码校验 长度不能小于8位且不能大于16位字符,必须包含大写字母、小写字母、数字和特殊符号
			var ISPWD =
				/^(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*,\._\+(){}])[0-9a-zA-Z!@#$%^&*,\\._\+(){}]{8,16}$/;
			// 密码校验
			const validatePassword = (rule, value, callback) => {
				if (!ISPWD.test(this.restForm.password)) {
					callback(new Error("用户密码必须包含大写字母、小写字母、数字和特殊符号"));
				} else {
					callback();
				}
			}
			return {
				tabbar: TabbarConfig,
				value6: 0,
				type: "error",
				value: 0,
				allApp: [],
				myApp: [],
				msgList: [],
				restForm: {
					password: "",
					passwordA: ""
				},

				rules3: {
					password: [{
							required: true,
							trigger: "blur",
							message: "请输入您的密码"
						},
						{
							min: 8,
							max: 16,
							message: '用户密码长度必须介于 8 和 16 之间',
							trigger: 'blur'
						},
						{
							required: true,
							validator: validatePassword,
							trigger: 'blur'
						}
					],
					passwordA: [{
							required: true,
							message: '请再次输入新密码',
							trigger: ['blur', 'change']
						},
						{
							required: true,
							validator: equalToPassword,
							trigger: "blur"
						}
					]
				},
				isOpen:false,
				isOpen2:false,
			}
		},
		onShow() {
			this.getDayNoticeAnnoByUserId()
			this.getAppList()
			this.getMyAppByUser()
			this.getNoticeAnnoByUserId()
		},
		methods: {
			//判断是否有未读消息
			getNoticeAnnoByUserId(){
				getNoticeAnnoByUserId({status:0}).then(res=>{
					if(res.data.length>0){
						//有未读消息
						uni.setTabBarItem({
							index:0,
							iconPath:"static/images/dh1.png"
						})
					}
					
				})
			},
			gotoYy(name) {
				const params = {
					username: uni.getStorageSync('userPhone'),
					jwtToken: uni.getStorageSync('App-Token')
				}
				const tjparams = {
					username: '17681010134', // 15912575796
					password: 'YNsbd@123456'
				}
				console.log('🚀 ~ gotoYy ~ tjparams:', tjparams)
				if (name == '考试培训移动端') {
					uni.request({
						url: config.login + '/login',
						method: 'POST',
						data: JSON.stringify(params),
						header: {
							'Content-Type': 'application/json'
						},
						success: res => {
							console.log(res)
							let req = res.data
							console.log('🚀 ~ getUserInfo ~ req:', req)
							if (req.code == 200) {
								uni.setStorageSync('access_token', req.data.access_token)
								uni.setStorageSync('userId', req.data.loginUser.userId)
								uni.setStorageSync('userName', req.data.loginUser.userName)
								uni.setStorageSync('className', req.data.loginUser.sysUser.className)
								uni.setStorageSync('facePath', req.data.loginUser.sysUser.facePath)
								setTimeout(() => {
									uni.reLaunch({
										url: '/pages/YNEduApp/index/index'
									})
								}, 500)
							} else {
								uni.showToast({
									title: req.msg,
									icon: 'none'
								})
							}
						},
						fail: err => {
							console.log('🚀 ~ gotoYy ~ err:', err)
							uni.showToast({
								title: err.msg,
								icon: 'none'
							})
						}
					})
				} else if( name == '健康体检移动端') {
					uni.request({
						url: config.tjBaseUrl + '/login',
						method: 'POST',
						data: tjparams,
						header: {
							'Content-Type': 'application/x-www-form-urlencoded'
						},
						success: res => {
							console.log('🚀 ~ gotoYy ~ res:', res,)
							console.log('🚀 ~ gotoYy ~ res:', res.data.token)
							if (res.statusCode == 200) {
								uni.removeStorageSync('tjToken')
								uni.removeStorageSync('tjPhone')
								uni.setStorageSync('tjToken', res.data.token)
								uni.setStorageSync('tjPhone', tjparams.username)
								setTimeout(() => {
									uni.reLaunch({
										url: '/pages/HealthExaminationApp/index/index'
									})
								}, 500)
							} else {
								uni.showToast({
									title: res.msg,
									icon: 'none'
								})
							}
						},
						fail: err => {
							console.log('🚀 ~ gotoYy ~ err:', err)
							uni.showToast({
								title: err.message,
								icon: 'none'
							})
						}
					})
				}
				
			},
			getDayNoticeAnnoByUserId() {
				getDayNoticeAnnoByUserId({}).then(response => {
					console.log(response);
					if (response.code == 200) {
						this.msgList = response.data.map(item => item.noticeTitle);
						this.value = this.msgList.length
					} else {
						uni.$u.toast('获取今日消息失败');
					}
				});
			},
			getAppList() {
				getAppList({}).then(response => {
					console.log(response);
					if (response.code == 200) {
						this.allApp = response.data

						//TODO 第一次登录 弹出修改密码框
						/* if (this.$store.state.user.isFirstLogin == '0') {
							this.$refs.popup.open("center")
						} */
					} else {
						uni.$u.toast('获取全部应用失败');
					}
				});

			},
			getMyAppByUser() {
				getMyAppByUser({}).then(response => {
					console.log(response);
					if (response.code == 200) {
						this.myApp = response.data
					} else {
						uni.$u.toast('获取我的应用失败');
					}
				});
			},
			logout() {
				this.$store.dispatch('LogOut').then(res => {
					uni.redirectTo({
						url: "/pages/login"
					})
				})
			},
			closePwd() {
				// open 方法传入参数 等同在 uni-popup 组件上绑定 type属性
				this.$refs.popup.close("center")
			},
			submit() {
				let _this = this
				this.$refs.uForm3.validate().then(res => {
					let form = {
						id: this.$store.state.user.userId,
						pd: this.restForm.password,
						type:3
					}
					updatePwdByApp(form).then(res => {
						if (res.code == 200) {
							this.closePwd()
							this.$refs.uToast.show({
								type: 'success',
								message: "密码修改成功",
							})
							// setTimeout(_this.logout(), 50000);
						} else {
							uni.$u.toast(res.msg)
						}
					})
				}).catch(errors => {
					// uni.$u.toast('校验失败')
				})
			},
		},
	}
</script>

<style lang="scss">
	page {
		background-color: rgb(238, 243, 250) !important;
	}

	.popup-content {
		@include flex;
		align-items: center;
		justify-content: center;
		padding: 15px;
		height: 480rpx;
		background-color: #fff;
		max-width: 600rpx;
	}

	.u-badge--horn {
		border-bottom-left-radius: 0 !important;
		border-top-right-radius: 0 !important;
		margin-top: 20rpx;
	}

	.normal-login-container {
		.top {
			height: 40vh;
			background-image: url("../../static/images/bg-top.png");
			background-size: 100% 100%;
			background-repeat: no-repeat;
			background-position: center;

			.title {
				color: white;
				font-size: 30rpx;
				text-align: center;
				padding-top: 60rpx;
			}
		}

		.content {
			margin-top: 20rpx;

			.top-msg {
				width: 95%;
				height: 60rpx;
				background-color: white;
				display: flex;
				border-radius: 10rpx;
				margin: auto;
				margin-bottom: 20rpx;

				.msg1 {
					width: 160rpx;
					text-align: center;
					color: rgb(154, 154, 154);
					font-size: 26rpx;
					border-right: 1px solid #efefef;
					margin: 10rpx 0;
					line-height: 40rpx;
				}

				.msg2 {
					width: calc(100% - 160rpx);
					font-size: 32rpx;
					line-height: 60rpx;
					display: flex;
					justify-content: space-between;
					padding: 0rpx 10rpx;

					.msg-content {
						width: calc(100% - 60rpx);
						white-space: nowrap;
						/* 确保文本在一行内显示 */
						overflow: hidden;
						/* 隐藏溢出的内容 */
						text-overflow: ellipsis;
						/* 使用省略号表示文本溢出 */
					}

				}
			}

			.yy-box {
				background-color: white;
				min-height: 150rpx;
				padding: 30rpx;
				margin-bottom: 20rpx;

				.bt {
					font-weight: 600;
					font-size: 30rpx;
				}

				.yy-list {
					display: flex;
					flex-wrap: wrap;
					justify-content: start;

					.yy-one {
						font-size: 24rpx;
						margin-top: 20rpx;
						width: calc(100% / 3);
						height: 200rpx;
						text-align: center;

						.yy-img image {
							width: 150rpx;
							height: 150rpx;
						}
					}
				}
			}
		}
	}
</style>