<script setup>
import { ref, computed, onUnmounted, nextTick } from 'vue'
import { showToast } from 'vant'
import ClickCaptcha from '@/components/ClickCaptcha.vue'

const router = useRouter()
const phoneNumber = ref('')
const verificationCode = ref('')
const password = ref('')
const isPasswordLogin = ref(false)
const isAgreed = ref(false)
const isCountingDown = ref(false)
const countdown = ref(60)
let timer = null

// 验证组件状态
const showCaptcha = ref(false)
const captchaVerified = ref(false)

// 聚焦状态变量
const phoneFocused = ref(false)
const codeFocused = ref(false)
const passwordFocused = ref(false)

const isPhoneNumberValid = computed(() => {
    return /^1[3-9]\d{9}$/.test(phoneNumber.value)
})

const canLogin = computed(() => {
    if (!isPhoneNumberValid.value) return false
    if (isPasswordLogin.value) {
        return password.value.length >= 6
    } else {
        return verificationCode.value.length === 6
    }
})

async function sendVerificationCode() {
    if (isCountingDown.value || !isPhoneNumberValid.value) return
    if (!isPhoneNumberValid.value) {
        showToast({ message: "请输入有效的手机号" });
        return
    }
    const { data, error } = await useApiFetch('auth/sendSms')
        .post({ mobile: phoneNumber.value, actionType: 'login' })
        .json()

    if (data.value && !error.value) {
        if (data.value.code === 200) {
            showToast({ message: "获取成功" });
            startCountdown()
            // 聚焦到验证码输入框
            nextTick(() => {
                const verificationCodeInput = document.getElementById('verificationCode');
                if (verificationCodeInput) {
                    verificationCodeInput.focus();
                }
            });
        } else {
            showToast(data.value.msg)
        }
    }
}

function startCountdown() {
    isCountingDown.value = true
    countdown.value = 60
    timer = setInterval(() => {
        if (countdown.value > 0) {
            countdown.value--
        } else {
            clearInterval(timer)
            isCountingDown.value = false
        }
    }, 1000)
}

async function handleLogin() {
    if (!isPhoneNumberValid.value) {
        showToast({ message: "请输入有效的手机号" });
        return
    }
    if (isPasswordLogin.value) {
        if (password.value.length < 6) {
            showToast({ message: "密码长度不能小于6位" });
            return
        }
    } else {
        if (verificationCode.value.length !== 6) {
            showToast({ message: "请输入有效的验证码" });
            return
        }
    }
    if (!isAgreed.value) {
        showToast({ message: "请先同意用户协议" });
        return
    }
    // 显示验证组件
    showCaptcha.value = true
}

// 验证成功回调
function handleCaptchaSuccess() {
    captchaVerified.value = true
    showCaptcha.value = false
    // 执行实际的登录逻辑
    performLogin()
}

// 验证关闭回调
function handleCaptchaClose() {
    showCaptcha.value = false
}

// 执行实际的登录逻辑
async function performLogin() {
    const { data, error } = await useApiFetch('/user/mobileCodeLogin')
        .post({ mobile: phoneNumber.value, code: verificationCode.value })
        .json()

    if (data.value && !error.value) {
        if (data.value.code === 200) {
            localStorage.setItem('token', data.value.data.accessToken)
            localStorage.setItem('refreshAfter', data.value.data.refreshAfter)
            localStorage.setItem('accessExpire', data.value.data.accessExpire)
            window.location.href = '/'
        }
    }
}
function toUserAgreement() {
    router.push(`/userAgreement`)
}

function toPrivacyPolicy() {
    router.push(`/privacyPolicy`)
}

onUnmounted(() => {
    if (timer) {
        clearInterval(timer)
    }
})
const onClickLeft = () => {
    router.replace('/')
}
</script>

<template>
    <div class="login-layout ">
        <van-nav-bar fixed placeholder title="用户登录" left-text="" left-arrow @click-left="onClickLeft" />
        <div class="login px-8 relative z-10">
            <div class="mb-8 pt-8 text-left">
                <div class="flex flex-col items-center">
                    <img class="h-16 w-16 rounded-full shadow" src="/logo.jpg" alt="Logo" />
                    <div class="text-3xl mt-4 text-slate-700 font-bold">天远数据</div>
                </div>
            </div>

            <div class="space-y-5">
                <!-- 手机号输入 -->
                <div :class="['input-container', phoneFocused ? 'focused' : '']">
                    <input v-model="phoneNumber" class="input-field" type="tel" placeholder="请输入手机号" maxlength="11"
                        @focus="phoneFocused = true" @blur="phoneFocused = false" />
                </div>

                <!-- 验证码输入 -->
                <div v-if="!isPasswordLogin">
                    <div class="flex items-center justify-between">
                        <div :class="['input-container', codeFocused ? 'focused' : '']">
                            <input v-model="verificationCode" id="verificationCode" class="input-field"
                                placeholder="请输入验证码" maxlength="6" @focus="codeFocused = true"
                                @blur="codeFocused = false" />
                        </div>
                        <button
                            class="ml-2 px-4 py-2 text-sm font-bold flex-shrink-0 rounded-lg transition duration-300"
                            :class="isCountingDown || !isPhoneNumberValid ? 'cursor-not-allowed bg-gray-300 text-gray-500' : 'text-white hover:opacity-90'"
                            :style="isCountingDown || !isPhoneNumberValid ? '' : 'background-color: #a22525'"
                            @click="sendVerificationCode">
                            {{ isCountingDown ? `${countdown}s重新获取` : '获取验证码' }}
                        </button>
                    </div>
                </div>

                <!-- 密码输入 -->
                <div v-if="isPasswordLogin" :class="['input-container', passwordFocused ? 'focused' : '']">
                    <input v-model="password" class="input-field" type="password" placeholder="请输入密码"
                        @focus="passwordFocused = true" @blur="passwordFocused = false" />
                </div>

                <!-- 协议同意框 -->
                <div class="flex items-start space-x-2">
                    <input type="checkbox" v-model="isAgreed" class="mt-1" />
                    <span class="text-xs text-gray-400 leading-tight">
                        未注册手机号登录后将自动生成账号，并且代表您已阅读并同意
                        <a class="cursor-pointer" style="color: #a22525" @click="toUserAgreement">
                            《用户协议》
                        </a>
                        和
                        <a class="cursor-pointer" style="color: #a22525" @click="toPrivacyPolicy">
                            《隐私政策》
                        </a>
                    </span>
                </div>
            </div>

            <button
                class="mt-20 w-full py-3 text-lg font-bold text-white rounded-full transition duration-300 hover:opacity-90"
                style="background-color: #a22525"
                @click="handleLogin">
                登录
            </button>
        </div>

        <!-- 点击验证组件 -->
        <ClickCaptcha :visible="showCaptcha" @success="handleCaptchaSuccess" @close="handleCaptchaClose" />

    </div>
</template>

<style scoped>
.login-layout {
    background: linear-gradient(135deg, #f0d6d6 0%, #e8c8c8 50%, #e0b8b8 100%);
    background-position: center;
    background-size: cover;
    height: 100vh;
    position: relative;
    overflow: hidden;
}

.login-layout::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: 
        radial-gradient(circle at 20% 80%, rgba(162, 37, 37, 0.20) 0%, transparent 50%),
        radial-gradient(circle at 80% 20%, rgba(162, 37, 37, 0.16) 0%, transparent 50%),
        radial-gradient(circle at 40% 40%, rgba(162, 37, 37, 0.12) 0%, transparent 50%);
    pointer-events: none;
}

.login-layout::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-image: 
        linear-gradient(45deg, transparent 40%, rgba(162, 37, 37, 0.04) 50%, transparent 60%),
        linear-gradient(-45deg, transparent 40%, rgba(162, 37, 37, 0.03) 50%, transparent 60%);
    background-size: 80px 80px;
    pointer-events: none;
}

.login {
    background: rgba(255, 255, 255, 0.9);
    border-radius: 2rem;
    margin: 2rem 1rem;
    padding: 2rem 1rem;
    box-shadow: 
        0 20px 40px rgba(162, 37, 37, 0.15),
        0 8px 16px rgba(162, 37, 37, 0.08),
        inset 0 1px 0 rgba(255, 255, 255, 0.9);
}

.input-container {
    border: 2px solid rgba(162, 37, 37, 0.1);
    border-radius: 1rem;
    transition: all 0.3s ease;
    background: rgba(255, 255, 255, 0.9);
}

.input-container.focused {
    border: 2px solid #a22525;
}

.input-field {
    width: 100%;
    padding: 1rem;
    background: transparent;
    border: none;
    outline: none;
    transition: border-color 0.3s ease;
}
</style>
