<script setup lang="ts">
    import { useUserStore } from '@/store/modules/user'
    import { closeSplashscreenAndChechUpgrade } from '@/utils/upgrade'
    import Link from '@/utils/const/link'
    import * as API from '/@/api/model/userInfo'
    import { Message } from '@/common'

    const userStore = useUserStore()

    onShow(async () => {
        // 恢复倒计时：计算实际剩余秒数，重启定时器
        if (model.countdown > 0 && countdownEndTime > 0) {
            const remaining = Math.max(0, Math.ceil((countdownEndTime - Date.now()) / 1000))
            if (remaining > 0) {
                model.countdown = remaining
                startCountdownTimer()
            } else {
                model.countdown = 0
                countdownEndTime = 0
            }
        }

        const token = userStore.getToken
        if (token) {
            model.isLogin = true
            await userStore.refreshUserInfo()
            goHome()
            Message.toast(`欢迎回来~`)
        } else {
            try {
                await closeSplashscreenAndChechUpgrade()
            } catch (error) {
                console.log('error', error)
            }
        }
    })

    const readConfirmShow = ref<boolean>(false)
    const form = ref()
    const slideVerifyRef = ref()
    const showSlideVerify = ref(false)

    const canLogin = computed(() => {
        return !!model.form.data.username && !!model.form.data.code
    })

    const model = reactive({
        isLogin: false,
        loading: false,
        countdown: 0,
        form: {
            phoneRules: [
                {
                    name: 'username',
                    rule: ['required', 'isMobile'],
                    msg: ['请输入手机号', '请输入正确的手机号'],
                },
            ],
            loginRules: [
                {
                    name: 'username',
                    rule: ['required', 'isMobile'],
                    msg: ['请输入手机号', '请输入正确的手机号'],
                },
                {
                    name: 'code',
                    rule: ['required'],
                    msg: ['请输入验证码'],
                },
            ],
            data: {
                username: '',
                code: '',
                read: false,
            },
        },
    })

    let countdownTimer: any = null
    let countdownEndTime = 0

    function login() {
        form?.value.validator(model.form.data, model.form.loginRules).then(async (res: { isPassed: boolean }) => {
            if (res.isPassed) {
                if (!model.form.data.read) {
                    readConfirmShow.value = true
                    return
                }
                doLogin()
            } else {
                Message.toast(res.errorMsg)
            }
        })
    }

    function smsCode() {
        form?.value.validator(model.form.data, model.form.phoneRules).then(async (res: { isPassed: boolean }) => {
            if (res.isPassed) {
                if (model.countdown > 0) return
                showSlideVerify.value = true
                slideVerifyRef.value.reset()
            } else {
                Message.toast(res.errorMsg)
            }
        })
    }

    function onSlideSuccess() {
        showSlideVerify.value = false
        startCountdown()

        const params = {
            mobile: model.form.data.username,
            smsmode: '1',
        }
        API.sysSms(params)
            .then(async () => {
                Message.toast('验证码已发送')
            })
            .catch((err) => {
                console.error('短信发送业务异常:', err)
            })
    }

    function doLogin() {
        model.loading = true
        const params = {
            mobile: model.form.data.username,
            captcha: model.form.data.code,
        }
        API.phoneLogin(params)
            .then(handleLoginSuccess)
            .finally(() => (model.loading = false))
    }

    async function handleLoginSuccess(body: any) {
        if (body && body.token) {
            userStore.setToken(body.token)
            const user = await API.getUserInfo()
            userStore.setUserInfo(user)
            goHome()
            Message.toast(`登录成功, 欢迎回来~`)
        } else {
            Message.toast(body.message || '登录失败')
        }
    }

    function startCountdown() {
        if (countdownTimer) clearInterval(countdownTimer)
        model.countdown = 60
        countdownEndTime = Date.now() + 60 * 1000
        startCountdownTimer()
    }

    function startCountdownTimer() {
        if (countdownTimer) clearInterval(countdownTimer)
        countdownTimer = setInterval(() => {
            const remaining = Math.max(0, Math.ceil((countdownEndTime - Date.now()) / 1000))
            model.countdown = remaining
            if (remaining <= 0) {
                clearInterval(countdownTimer)
                countdownTimer = null
                countdownEndTime = 0
            }
        }, 300)
    }

    function goHome() {
        uni.reLaunch({ url: '/pages/shouye/shouye' })
    }

    function goRegister() {
        uni.navigateTo({ url: '/pages/login/register' })
    }

    onHide(() => {
        if (countdownTimer) {
            clearInterval(countdownTimer)
            countdownTimer = null
        }
    })

    onUnload(() => {
        if (countdownTimer) {
            clearInterval(countdownTimer)
            countdownTimer = null
        }
    })

    function onReadConfirm() {
        model.form.data.read = true
        readConfirmShow.value = false
        login()
    }

    function closeAgreeModal() {
        readConfirmShow.value = false
    }
</script>

<template>
    <view class="login-page">
        <view class="header-visual">
            <image class="header-scene" src="/static/images/login/farm_base_bg.png" mode="aspectFill"></image>
            <view class="header-overlay"></view>

            <image class="float-icon device-1" src="/static/images/nongchang/device1.png" mode="aspectFit"></image>
            <image class="float-icon device-2" src="/static/images/nongchang/device3.png" mode="aspectFit"></image>

            <view class="brand-hero">
                <view class="logo-box">
                    <image class="logo-img" src="/static/logo.png" mode="aspectFit"></image>
                </view>
                <view class="brand-info">
                    <text class="app-title">湘农数智农服</text>
                    <view class="app-slogan">
                        <text>智慧生产 · 农务管家</text>
                    </view>
                </view>
            </view>
        </view>

        <view class="main-card-container">
            <view class="aesthetic-card">
                <fui-form ref="form" top="0" :padding="['0', '0']" background="transparent" :show="false">
                    <view class="card-header">
                        <text class="welcome-text">您好，欢迎登录</text>
                        <view class="green-line"></view>
                    </view>

                    <view class="input-fields">
                        <view class="field-item">
                            <text class="field-label">手机号</text>
                            <fui-input
                                v-model="model.form.data.username"
                                :padding="['24rpx', '0']"
                                placeholder="请输入手机号"
                                backgroundColor="transparent"
                                placeholderStyle="font-size:16px;"
                                borderColor="#F0F0F0"
                                borderBottom
                                height="110rpx"
                                size="34"
                                maxlength="11"
                            ></fui-input>
                        </view>

                        <view class="field-item">
                            <text class="field-label">验证码</text>
                            <view class="code-inner">
                                <fui-input
                                    v-model="model.form.data.code"
                                    :padding="['24rpx', '0']"
                                    placeholder="请输入验证码"
                                    placeholderStyle="font-size:16px;"
                                    backgroundColor="transparent"
                                    borderColor="#F0F0F0"
                                    borderBottom
                                    height="110rpx"
                                    size="34"
                                    maxlength="6"
                                    autocomplete="off"
                                ></fui-input>
                                <view class="sms-trigger" :class="{ inactive: model.countdown > 0 }" @click="smsCode">
                                    {{ model.countdown > 0 ? `${model.countdown}s后重发` : '获取验证码' }}
                                </view>
                            </view>
                        </view>
                    </view>

                    <view class="action-footer">
                        <view :class="['btn-wrapper', { disabled: !canLogin }]">
                            <fui-button
                                text="验证并登录"
                                background="linear-gradient(90deg, #5DB66F 0%, #4CAF50 100%)"
                                radius="100rpx"
                                height="80rpx"
                                @click="login"
                                :loading="model.loading"
                                :disabled="!canLogin || model.loading"
                                color="#ffffff"
                                disabled-color="#888888"
                                disabled-background="#f5f5f5"
                                size="30"
                                shadow
                            ></fui-button>
                        </view>

                        <view class="secondary-links">
                            <view class="reg-btn" @click="goRegister">还没有账号？立即注册</view>
                        </view>
                    </view>

                    <view class="policy-wrapper">
                        <fui-checkbox-group>
                            <fui-label class="policy-label">
                                <view class="checkbox-align">
                                    <fui-checkbox
                                        color="#5DB66F"
                                        :scaleRatio="0.7"
                                        :checked="model.form.data.read"
                                        @change="(e) => (model.form.data.read = e.checked)"
                                    ></fui-checkbox>
                                </view>
                                <view class="policy-text">
                                    已阅读并同意<text class="link" @click.stop="Link.to(Link.services, '服务协议')">《服务协议》</text>与<text class="link" @click.stop="Link.to(Link.privacy, '隐私政策')">《隐私政策》</text>
                                    ，同意运营商对本人提供的手机号码进行验证。
                                </view>
                            </fui-label>
                        </fui-checkbox-group>
                    </view>
                </fui-form>
            </view>
        </view>

        <view class="footer-aesthetic"></view>

        <view class="agree-mask" v-if="readConfirmShow" @click.self="closeAgreeModal">
            <view class="agree-panel">
                <view class="agree-gradient-header"></view>
                <view class="agree-close" @click="closeAgreeModal">
                    <text>✕</text>
                </view>
                <view class="agree-title-wrap">
                    <view class="agree-title">服务协议及隐私保护</view>
                    <view class="agree-title-line"></view>
                </view>
                <view class="agree-content">
                    <view class="agree-text">
                        为了更好的保障您的合法权益，请您阅读并同意
                        <text class="agree-link" @click.stop="Link.to(Link.services, '用户协议')">《用户协议》</text>
                        和
                        <text class="agree-link" @click.stop="Link.to(Link.privacy, '隐私协议')">《隐私协议》</text>
                        。
                    </view>
                    <view class="agree-btn" @click="onReadConfirm">同意并继续</view>
                </view>
            </view>
        </view>

        <view class="slide-mask" v-if="showSlideVerify" @click.self="showSlideVerify = false">
            <view class="slide-panel">
                <view class="slide-gradient-header"></view>
                <view class="slide-close" @click="showSlideVerify = false">
                    <text>✕</text>
                </view>
                <view class="slide-title-wrap">
                    <view class="slide-title">安全验证</view>
                    <view class="slide-title-line"></view>
                </view>
                <view class="slide-content">
                    <view class="slide-desc">按住滑块，拖动到最右侧</view>
                    <fui-slide-verify
                        ref="slideVerifyRef"
                        width="540"
                        height="80"
                        slider-width="80"
                        background="#f5f7f5"
                        active-bg-color="#5DB66F"
                        pass-color="#5DB66F"
                        arrow-color="#5DB66F"
                        line-color="#5DB66F"
                        color="#999"
                        active-color="#fff"
                        @success="onSlideSuccess"
                    ></fui-slide-verify>
                </view>
            </view>
        </view>
    </view>
</template>

<style lang="less" scoped>
    .login-page {
        min-height: 100vh;
        background-color: #f7faf8;
        display: flex;
        flex-direction: column;
        overflow-x: hidden;
    }

    .header-visual {
        height: 550rpx;
        position: relative;
        padding-top: var(--status-bar-height);
        overflow: hidden;

        .header-scene {
            position: absolute;
            width: 100%;
            height: 100%;
            top: 0;
            left: 0;
            filter: brightness(0.9);
        }

        .header-overlay {
            position: absolute;
            width: 100%;
            height: 100%;
            top: 0;
            left: 0;
            background: linear-gradient(180deg, rgba(93, 182, 111, 0.3) 0%, rgba(76, 175, 80, 0.7) 100%);
        }

        .float-icon {
            position: absolute;
            opacity: 0.7;
            filter: drop-shadow(0 4rpx 10rpx rgba(0,0,0,0.15));

            &.device-1 {
                width: 130rpx;
                height: 130rpx;
                right: 20rpx;
                top: 180rpx;
                transform: rotate(10deg);
                animation: float-slow 4s ease-in-out infinite;
            }
            &.device-2 {
                width: 110rpx;
                height: 110rpx;
                left: 30rpx;
                bottom: 100rpx;
                animation: float-slow 3s ease-in-out infinite alternate;
            }
        }

        .brand-hero {
            position: relative;
            z-index: 10;
            display: flex;
            flex-direction: column;
            align-items: center;
            margin-top: 80rpx;

            .logo-box {
                width: 140rpx;
                height: 140rpx;
                background: #fff;
                border-radius: 40rpx;
                display: flex;
                align-items: center;
                justify-content: center;
                box-shadow: 0 12rpx 24rpx rgba(0,0,0,0.1);

                .logo-img {
                    width: 90rpx;
                    height: 90rpx;
                }
            }

            .brand-info {
                margin-top: 24rpx;
                text-align: center;
                color: #fff;

                .app-title {
                    font-size: 44rpx;
                    font-weight: 800;
                    letter-spacing: 2rpx;
                    background: linear-gradient(90deg, #fff 0%, #fff 40%, rgba(255,255,255,0.3) 50%, #fff 60%, #fff 100%);
                    background-size: 300% 100%;
                    -webkit-background-clip: text;
                    background-clip: text;
                    -webkit-text-fill-color: transparent;
                    animation: shine-text 3s ease-in-out infinite;
                }

                .app-slogan {
                    margin-top: 8rpx;
                    font-size: 24rpx;
                    opacity: 0.95;
                    display: flex;
                    align-items: center;
                    justify-content: center;

                    .weather-icon {
                        width: 36rpx;
                        height: 36rpx;
                        margin-right: 10rpx;
                    }
                }

                .app-slogan text {
                    background: linear-gradient(90deg, rgba(255,255,255,0.9) 0%, rgba(255,255,255,0.9) 40%, rgba(255,255,255,0.4) 50%, rgba(255,255,255,0.9) 60%, rgba(255,255,255,0.9) 100%);
                    background-size: 300% 100%;
                    -webkit-background-clip: text;
                    background-clip: text;
                    -webkit-text-fill-color: transparent;
                    animation: shine-text 3s ease-in-out infinite 0.5s;
                }
            }
        }
    }

    .main-card-container {
        padding: 0 40rpx;
        margin-top: -80rpx;
        position: relative;
        z-index: 20;
    }

    .aesthetic-card {
        background: #ffffff;
        border-radius: 50rpx;
        padding: 70rpx 50rpx 60rpx;
        box-shadow: 0 15rpx 50rpx rgba(0, 0, 0, 0.06);

        .card-header {
            margin-bottom: 50rpx;

            .welcome-text {
                font-size: 38rpx;
                font-weight: bold;
                color: #333;
            }
            .green-line {
                width: 50rpx;
                height: 7rpx;
                background: #5DB66F;
                border-radius: 4rpx;
                margin-top: 14rpx;
            }
        }

        .field-item {
            margin-bottom: 40rpx;

            .field-label {
                font-size: 26rpx;
                color: #999;
                margin-left: 4rpx;
            }

            .code-inner {
                display: flex;
                align-items: center;
                justify-content: space-between;

                .sms-trigger {
                    white-space: nowrap;
                    font-size: 27rpx;
                    color: #5DB66F;
                    padding: 14rpx 28rpx;
                    background: #f1f9f2;
                    border-radius: 50rpx;
                    margin-left: 20rpx;
                    font-weight: 500;

                    &.inactive {
                        color: #bbb;
                        background: #f8f8f8;
                    }
                }
            }
        }
    }

    .action-footer {
        margin-top: 60rpx;

        .btn-wrapper {
            transition: opacity 0.3s;
        }

        .secondary-links {
            margin-top: 40rpx;
            text-align: center;

            .reg-btn {
                font-size: 28rpx;
                color: #aaa;
            }
        }
    }

    .policy-wrapper {
        margin-top: 60rpx;

        .policy-label {
            display: flex;
            align-items: flex-start;
            justify-content: center;
        }

        .checkbox-align {
            line-height: 1;
            display: flex;
            align-items: center;
            flex-shrink: 0;
            margin-top: 4rpx;
        }

        .policy-text {
            font-size: 24rpx;
            color: #bbb;
            margin-left: 12rpx;
            flex: 1;
            line-height: 1.6;
            word-break: break-all;
        }

        .link {
            color: #5DB66F;
            font-weight: 500;
        }
    }

    .footer-aesthetic {
        flex: 1;
        background: linear-gradient(180deg, #f7faf8 0%, #edf3ef 100%);
    }

    .agree-mask {
        position: fixed;
        inset: 0;
        background: rgba(0, 0, 0, 0.5);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 9999;
    }

    .agree-panel {
        width: 640rpx;
        background: #ffffff;
        border-radius: 50rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        box-shadow: 0 15rpx 50rpx rgba(0, 0, 0, 0.08);
        position: relative;
        overflow: hidden;
    }

    .agree-gradient-header {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 180rpx;
        background: linear-gradient(180deg, #4CAF50 0%, #5DB66F 40%, rgba(93, 182, 111, 0.15) 85%, transparent 100%);
        border-radius: 50rpx 50rpx 0 0;
    }

    .agree-close {
        position: absolute;
        top: 20rpx;
        right: 24rpx;
        width: 56rpx;
        height: 56rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        background: rgba(255, 255, 255, 0.25);
        z-index: 2;

        text {
            font-size: 32rpx;
            color: #ffffff;
            line-height: 1;
        }
    }

    .agree-title-wrap {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding-top: 48rpx;
        margin-bottom: 20rpx;
        position: relative;
        z-index: 1;
    }

    .agree-title {
        font-size: 36rpx;
        font-weight: 700;
        color: #ffffff;
        margin-bottom: 10rpx;
        text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.12);
    }

    .agree-title-line {
        width: 48rpx;
        height: 6rpx;
        background: rgba(255, 255, 255, 0.7);
        border-radius: 3rpx;
    }

    .agree-content {
        width: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 36rpx 50rpx 48rpx;
        position: relative;
        z-index: 1;
    }

    .agree-text {
        font-size: 28rpx;
        color: #666;
        line-height: 1.8;
        text-align: center;
        margin-bottom: 44rpx;
    }

    .agree-link {
        color: #5DB66F;
        font-weight: 600;
    }

    .agree-btn {
        width: 100%;
        height: 90rpx;
        background: linear-gradient(90deg, #5DB66F 0%, #4CAF50 100%);
        border-radius: 100rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 32rpx;
        color: #ffffff;
        font-weight: 600;
        box-shadow: 0 6rpx 20rpx rgba(93, 182, 111, 0.3);
    }

    .slide-mask {
        position: fixed;
        inset: 0;
        background: rgba(0, 0, 0, 0.5);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 9999;
    }

    .slide-panel {
        width: 640rpx;
        background: #ffffff;
        border-radius: 50rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        box-shadow: 0 15rpx 50rpx rgba(0, 0, 0, 0.08);
        position: relative;
        overflow: hidden;
    }

    .slide-gradient-header {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 180rpx;
        background: linear-gradient(180deg, #4CAF50 0%, #5DB66F 40%, rgba(93, 182, 111, 0.15) 85%, transparent 100%);
        border-radius: 50rpx 50rpx 0 0;
    }

    .slide-close {
        position: absolute;
        top: 20rpx;
        right: 24rpx;
        width: 56rpx;
        height: 56rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        background: rgba(255, 255, 255, 0.25);
        z-index: 2;

        text {
            font-size: 32rpx;
            color: #ffffff;
            line-height: 1;
        }
    }

    .slide-title-wrap {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding-top: 48rpx;
        margin-bottom: 20rpx;
        position: relative;
        z-index: 1;
    }

    .slide-title {
        font-size: 36rpx;
        font-weight: 700;
        color: #ffffff;
        margin-bottom: 10rpx;
        text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.12);
    }

    .slide-title-line {
        width: 48rpx;
        height: 6rpx;
        background: rgba(255, 255, 255, 0.7);
        border-radius: 3rpx;
    }

    .slide-content {
        width: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 36rpx 50rpx 48rpx;
        position: relative;
        z-index: 1;
    }

    .slide-desc {
        font-size: 26rpx;
        color: #999;
        margin-bottom: 36rpx;
        letter-spacing: 0.5rpx;
    }

    @keyframes float-slow {
        0%, 100% { transform: translateY(0) rotate(5deg); }
        50% { transform: translateY(-15rpx) rotate(-5deg); }
    }

    @keyframes shine-text {
        0% { background-position: 0% 0; }
        30% { background-position: 0% 0; }
        60% { background-position: 100% 0; }
        100% { background-position: 100% 0; }
    }
</style>
