<template>
    <view class="login-page">
        <!-- 背景图 -->
        <image class="bg-image" src="/static/images/login/1.png" mode="aspectFill"></image>

        <scroll-view class="login-content">
            <!-- Logo 和标题 -->
            <view class="header">
                <image class="logo" src="/static/images/login/2.png" mode="aspectFit"></image>
                <text class="title">工效通APP</text>
            </view>

            <!-- 登录表单卡片 -->
            <view class="form-card">
                <!-- 账号输入 -->
                <view class="form-item">
                    <text class="label">账号</text>
                    <input class="input" type="text" placeholder="请输入您的账号" v-model="username" />
                </view>

                <!-- 密码输入 -->
                <view class="form-item">
                    <text class="label">密码</text>
                    <view class="input-wrapper">
                        <input class="input" :type="showPassword ? 'text' : 'password'" placeholder="请输入您的密码" v-model="password" />
                        <image class="eye-icon" :src="showPassword ? '/static/images/login/4.png' : '/static/images/login/3.png'" mode="aspectFit" @click="handleTogglePassword"></image>
                    </view>
                </view>

                <!-- 记住密码 -->
                <view class="remember-box">
                    <checkbox :checked="rememberPassword" @click="handleRememberChange" class="checkbox" />
                    <text class="remember-text">记住密码</text>
                </view>

                <!-- 登录按钮 -->
                <button class="login-btn"  @click="handleLogin">
                    <text class="login-btn-text">{{ loading ? "登录中..." : "登录" }}</text>
                </button>
            </view>

            <!-- 底部信息 -->
            <view class="footer">
                <text class="version">v{{ version }}</text>
                <text class="company">宇光同行</text>
            </view>
        </scroll-view>
    </view>
</template>

<script setup lang="uts">
    import { ref, computed, onMounted } from 'vue'
    import { loginByAccount, getUserInfo } from '../../api/auth/login'
    import {
        saveAccessToken,
        saveUserInfo,
        getRememberedAccount,
        saveRememberedAccount,
        clearRememberedAccount
    } from '../../utils/storage'
    import { validatePassword } from '../../utils/validate'
    import { encryptAES } from '../../utils/crypto'
    // @ts-ignore
    import manifest from '@/manifest.json'

    // 表单数据
    const username = ref<string>("")
    const password = ref<string>("")
    const rememberPassword = ref<boolean>(false)
    const showPassword = ref<boolean>(false)
    const loading = ref<boolean>(false)
    
    // 版本号
    const manifestVersion = manifest.versionName as string | null
    const version = ref<string>(manifestVersion != null ? manifestVersion : '1.0.0')

    // 是否可以登录
    const canLogin = computed((): boolean => {
        return username.value.length > 0 && password.value.length > 0 && !loading.value
    })

    // 记住密码切换
    const handleRememberChange = (): void => {
        rememberPassword.value = !rememberPassword.value
    }
    
    // 切换密码显示/隐藏
    const handleTogglePassword = (): void => {
        showPassword.value = !showPassword.value
    }

    // 登录处理
    const handleLogin = async (): Promise<void> => {
        
        // 验证输入
        if (username.value.trim().length == 0) {
            uni.showToast({
                title: '请输入账号',
                icon: 'none',
                duration: 2000
            })
            return
        }
        
        if (password.value.trim().length == 0) {
            uni.showToast({
                title: '请输入密码',
                icon: 'none',
                duration: 2000
            })
            return
        }
        
        // // 验证密码强度
        // if (!validatePassword(password.value)) {
        //     uni.showToast({
        //         title: '密码强度不足：需包含数字、大小写字母、特殊字符，至少6位',
        //         icon: 'none',
        //         duration: 3000
        //     })
        //     return
        // }

        try {
            loading.value = true
            const result = await loginByAccount(username.value, password.value)
            // 提取 data 部分
            const resultObj = result as UTSJSONObject
            // const data = resultObj['data'] as UTSJSONObject

            // 保存登录信息
            saveAccessToken(resultObj['token'] as string)
			
			const userInfoJson = await getUserInfo();
			console.log(userInfoJson);
			
			const userInfoObj = userInfoJson as UTSJSONObject
			const userInfo = userInfoObj['user'] as UTSJSONObject
			const deptInfo = userInfo['dept'] as UTSJSONObject
            saveUserInfo({
                userId: userInfo['userId'],
                userName: userInfo['userName'],
				nickName: userInfo['nickName'],
				phone: userInfo['phonenumber'],
				deptName: deptInfo['deptName'],
				roleNames: userInfoObj['roleNames']
            })

            // 保存或清除记住的账号密码
            if (rememberPassword.value) {
                saveRememberedAccount(username.value, password.value)
            } else {
                clearRememberedAccount()
            }

            uni.showToast({
                title: '登录成功',
                icon: 'success'
            })

            // 跳转到首页
            setTimeout(() => {
                uni.redirectTo({
                    url: '/pages/index/index'
                })
            }, 1000)

        } catch (e: any) {
            uni.showToast({
                title: e.message ?? '登录失败',
                icon: 'none',
                duration: 2000
            })
        } finally {
            loading.value = false
        }
    }

    // 初始化：加载记住的账号密码
    onMounted(() => {
        const remembered = getRememberedAccount()
        if (remembered != null) {
            username.value = remembered['username'] as string
            password.value = remembered['password'] as string
            rememberPassword.value = true
        }
    })
</script>

<style lang="scss">
    .login-page {
        position: relative;
        flex: 1;
        padding-top: env(safe-area-inset-top);
    }

    .bg-image {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 0;
    }

    .login-content {
        position: relative;
        flex: 1;
        padding: 60rpx 40rpx;
        z-index: 1;
    }

    .header {
        align-items: center;
        margin-bottom: 80rpx;
    }

    .logo {
        width: 200rpx;
        height: 200rpx;
        margin-bottom: 40rpx;
    }

    .title {
        font-size: 48rpx;
        color: #ffffff;
        font-weight: bold;
        // #ifndef APP-HARMONY
        text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
        // #endif
        
    }

    .form-card {
        background: rgba(255, 255, 255, 0.95);
        border-radius: 24rpx;
        padding: 50rpx 40rpx;
         // #ifndef APP-HARMONY
        box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
        // #endif
        margin-bottom: 100rpx;
    }

    .form-item {
        margin-bottom: 40rpx;
    }

    .label {
        font-size: 32rpx;
        color: #333333;
        font-weight: bold;
        margin-bottom: 20rpx;
    }
    
    .input-wrapper {
        position: relative;
        width: 100%;
    }

    .input {
        width: 100%;
        height: 90rpx;
        padding: 0 100rpx 0 30rpx;
        background-color: #f5f5f5;
        border-radius: 12rpx;
        font-size: 30rpx;
        color: #333333;
        border: 1rpx solid transparent;
    }

    .input:focus {
        border-color: #007aff;
        background-color: #ffffff;
    }
    
    .eye-icon {
        position: absolute;
        right: 30rpx;
        top: 50%;
        transform: translateY(-50%);
        width: 40rpx;
        height: 40rpx;
    }

    .remember-box {
        flex-direction: row;
        align-items: center;
        margin-bottom: 50rpx;
    }

    .checkbox {
        transform: scale(0.8);
    }

    .remember-text {
        font-size: 28rpx;
        color: #1677ff;
        margin-left: 12rpx;
    }

    .login-btn {
        width: 100%;
        height: 100rpx;
        background-color: #0081ff;
        border-radius: 50rpx;
        color: #ffffff;
        // #ifndef APP-HARMONY
        box-shadow: 0 8rpx 16rpx rgba(0, 122, 255, 0.3);
        // #endif
    }

    .login-btn-text {
        font-size: 36rpx;
        color: #ffffff !important;
        font-weight: bold;
    }

    .footer {
        position: fixed;
        bottom: 60rpx;
        left: 0;
        right: 0;
        align-items: center;
        z-index: 2;
    }

    .version {
        font-size: 28rpx;
        color: #333333;
        margin-bottom: 15rpx;
    }

    .company {
        font-size: 24rpx;
        color: #333333;
    }
</style>
