<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5" type="home">
	{
	style: {
	navigationStyle: 'custom',
	navigationBarTitleText: '登录页',
	},
	}
</route>

<template>
	<PageLayout :navbarShow="false">
		<view class="page-container">
			<view class="text-center">
				<image src="@/static/sinopec.png" mode="aspectFit" class="logo"></image>
				<view class="enter-area">
					<view class="account-login-area">
						<view class="box account">
							<wd-icon name="user" size="15px"></wd-icon>
							<wd-text text=""></wd-text>
							<wd-input class="uni-input" placeholder="统一身份/劳动合同号" v-model.trim="userName"></wd-input>
						</view>
						<view class="box password">
							<wd-icon name="lock-on" size="15px"></wd-icon>
							<wd-text text=""></wd-text>
							<input class="uni-input" placeholder="密码" :password="showPassword"
								v-model.trim="password" />
							<wd-icon v-if="showPassword" name="eye-close" size="18px"
								@click="handleChangePassword"></wd-icon>
							<wd-icon v-else name="view" size="18px" @click="handleChangePassword"></wd-icon>
						</view>
						<view class="remPW">
							<wd-icon v-if="remPW" name="check-circle" @click="handleChangeRemPW"></wd-icon>
							<wd-icon v-else name="circle1" @click="handleChangeRemPW"></wd-icon>
							<wd-text text="记住密码"></wd-text>
						</view>
					</view>
				</view>
				<view class="btn-area text-center">
					<wd-button :loading="loading" @click="handleLogin">
						{{ loading ? '登录...' : '登录' }}
					</wd-button>
				</view>
				<view class="version">
					<text style="display: block;">Copyright (c) 2024 天然气产销厂</text>
					<text>版本号:{{version}}</text>
				</view>
				<wd-notice-bar type="danger" text="本平台为非涉密平台，严禁处理、传输国家秘密和企业核心商密等涉密敏感事项" wrapable :scrollable="false"
					prefix="warn-bold" style="text-align: left;display: flex;align-items: flex-start;" />
			</view>
		</view>
	</PageLayout>
</template>

<script setup>
	import {
		useToast
	} from 'wot-design-uni'
	import {
		ref
	} from 'vue'
	import {
		useUserStore
	} from '@/store/user'
	import {
		http
	} from '@/utils/http'
	import {
		HOME_PAGE
	} from '@/common/constants'
	import {
		useRouter
	} from '@/plugin/uni-mini-router'
	import Base64 from 'base-64';
	import {
		loginApi
	} from '@/api/system';
	import {
		queryUsernameByLdhth
	} from '@/api/system/user';

	defineOptions({
		name: 'login',
		options: {
			styleIsolation: 'shared',
		},
	})
	const router = useRouter()
	const loading = ref(false)
	const userName = ref()
	const password = ref()
	const showPassword = ref(true) //是否显示明文
	const remPW = ref(false) //是否记住密码
	/**h5系统信息中没有appWgtVersion值*/
	const version = uni.getSystemInfoSync().appWgtVersion ? uni.getSystemInfoSync().appWgtVersion : uni.getSystemInfoSync()
		.appVersion
	const toast = useToast()
	const userStore = useUserStore()
	const handleChangePassword = () => {
		showPassword.value = !showPassword.value
	}
	const handleChangeRemPW = () => {
		remPW.value = !remPW.value
	}
	const savePwd = () => {
		let localObj = {
			un: userName.value,
			pw: remPW.value ? password.value : ''
		}
		uni.setStorageSync('accountpassword', JSON.stringify(localObj))
		uni.setStorageSync('savePwd', remPW.value)
	}
	const handleLogin = async () => {
		if (userName.value.length === 0) {
			toast.warning('请输入统一身份/劳动合同号')
			return
		}
		if (password.value.length === 0) {
			toast.warning('请输入密码')
			return
		}
		let params = {
			username: userName.value,
			password: password.value,
		};
		/*判断是否是六位纯数字*/
		if (userName.value.match(/^\d{6}$/)) {
			await queryUsernameByLdhth(userName.value).then(res => {
				if (res) {
					params = {
						username: Base64.encode(encodeURIComponent(res)),
						password: Base64.encode(encodeURIComponent(password.value)),
					};
				} else {
					params.captcha = 'app';
				}
			})
		} else {
			/*开发环境 */
			params.captcha = 'app';
			/*生产环境 */
			// params = {
			// 	username: Base64.encode(encodeURIComponent(userName.value)),
			// 	password: Base64.encode(encodeURIComponent(password.value)),
			// };
		}
		login(params)
	}

	const login = async (params) => {
		loading.value = true
		try {
			// 调用API
			const res = await loginApi(params);
			if (res.success) {
				const {
					result
				} = res
				const userInfo = result.userInfo
				userStore.setUserInfo({
					...userInfo,
					token: result.token,
					userid: userInfo.id,
					username: userInfo.username,
					realname: userInfo.realname,
					avatar: userInfo.avatar,
					post: userInfo.post,
					tenantId: userInfo.loginTenantId,
					localStorageTime: +new Date(),
				})
				savePwd() //记住账号密码
				uni.setStorageSync('logintime', Date.now()) //缓存登录时间
				router.pushTab({
					path: HOME_PAGE
				})
			} else {
				res.message == '数据库中已存在该记录' ? res.message = '请使用统一身份账号登录' : res.message
				if (!res.success) {
					try {
						// 尝试解析 JSON（仅当 message 可能是 JSON 时）
						const response = JSON.parse(res.message);
						if (response.error_description === '用户名或密码错误') {
							res.message = '用户名或密码错误';
						}
					} catch (e) {}
				}
				toast.warning(res.message)
			}
		} finally {
			loading.value = false;
		}
	}

	onLoad(() => {
		if (uni.getStorageSync('accountpassword')) {
			let obj = JSON.parse(uni.getStorageSync('accountpassword'))
			userName.value = obj.un
			password.value = obj.pw
		}
		if (uni.getStorageSync('savePwd')) {
			remPW.value = uni.getStorageSync('savePwd')
		}
	})
</script>

<style lang="scss" scoped>
	.page-container {
		padding: 0 20upx;
		padding-top: 100upx;
		position: relative;
		font-size: 15px;
		color: var(--UI-FG-0);
		min-height: 100vh; // 确保容器撑满整个屏幕高度
		background-color: #fff;

		.logo {
			width: 400upx;
			height: 200px;
		}

		.enter-area {
			padding-top: 30px;
			width: 87%;
			margin: 0 auto 60upx;

			.box {
				display: flex;
				align-items: center;
				min-height: 100upx;
				color: #000;
				border: 1px solid #eee;
				background-color: #F8F8F8;
				padding: 0 20upx;
				margin-bottom: 30upx;
				box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
				line-height: 34px;

				:deep(.wd-text) {
					margin: 0 10upx;
				}

				:deep(.wd-input),
				:deep(.uni-input) {
					flex: 1;
					background-color: #F8F8F8;

					&::after {
						height: 0;
					}
				}

				.uni-input {
					text-align: left;
					font-size: var(--wot-input-fs, var(--wot-cell-title-fs, 14px));
					height: var(--wot-input-inner-height, 34px);
					color: var(--wot-input-color, #262626);

					.uni-input-placeholder {
						color: var(--wot-input-placeholder-color, #bfbfbf);
					}
				}
			}

			:deep(.sendSMSBtn) {
				margin-left: 20upx;
			}

			:deep(.wd-icon-view),
			:deep(.wd-icon-eye-close) {
				color: #555;
			}

			.remPW {
				display: flex;
				justify-content: flex-end;
				align-items: center;
			}
		}

		.btn-area {
			:deep(.wd-button) {
				--wot-button-medium-height: 41px;
				--wot-button-medium-fs: 16px;
				--wot-button-plain-bg-color: transparent;
				min-width: 100px;
				box-shadow: 3px 3px 4px rgba(0, 102, 204, 0.2);
			}
		}

		.version {
			margin-top: 63rpx;
			font-size: 12px;
			margin-bottom: 60rpx;
		}
	}
</style>