<script setup lang="ts">
    import { useUserStore } from '@/store/modules/user'
    import { closeSplashscreenAndChechUpgrade } from '@/utils/upgrade'
    import { isDevMode } from '@/utils/env'
    import Link from '@/utils/const/link'
    import SlideVerify from '@/components/slide-verify/SlideVerify.vue'
    import * as API from '/@/api/model/userInfo'

    const userStore = useUserStore()

    onShow(async () => {
        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 defaultText = '湘农数智农服'
    const readConfirmShow = ref<boolean>(false)
    const form = ref()
    const showSlide = ref(false)
    const loginMode = ref(1) // 1: 验证码登录, 2: 密码登录

    const slideType = ref<'sms' | 'login'>('login')

    const model = reactive({
        isLogin: false,
        loading: false,
        text: defaultText,
        countdown: 0,
        form: {
            phoneRules: [
                {
                    name: 'username',
                    rule: ['required', 'isMobile'],
                    msg: ['请输入手机号', '请输入正确的手机号'],
                },
            ],
            codeLoginRules: [
                {
                    name: 'username',
                    rule: ['required', 'isMobile'],
                    msg: ['请输入手机号', '请输入正确的手机号'],
                },
                {
                    name: 'code',
                    rule: ['required'],
                    msg: ['请输入验证码'],
                },
                {
                    name: 'read',
                    validator: [
                        {
                            msg: '请阅读并同意服务协议和隐私政策',
                            method: (value: boolean) => {
                                if (!value) {
                                    readConfirmShow.value = true
                                }
                                return value
                            },
                        },
                    ],
                },
            ],
            pwdLoginRules: [
                {
                    name: 'username',
                    rule: ['required'],
                    msg: ['请输入账号'],
                },
                {
                    name: 'password',
                    rule: ['required'],
                    msg: ['请输入密码'],
                },
                {
                    name: 'read',
                    validator: [
                        {
                            msg: '请阅读并同意服务协议和隐私政策',
                            method: (value: boolean) => {
                                if (!value) {
                                    readConfirmShow.value = true
                                }
                                return value
                            },
                        },
                    ],
                },
            ],
            data: {
                username: '',
                password: '',
                code: '',
                read: false,
            },
        },
    })

    let countdownTimer: any = null

    if (isDevMode()) {
        model.form.data.username = 'admin'
        model.form.data.password = 'Yiring=2026#@!'
        model.form.data.read = true
    }

    function switchMode(mode: number) {
        loginMode.value = mode
    }

    function login() {
        const rules = loginMode.value === 1 ? model.form.codeLoginRules : model.form.pwdLoginRules
        form?.value.validator(model.form.data, rules).then(async (res: { isPassed: boolean }) => {
            if (res.isPassed) {
                // 登录前先做滑动验证 (Requirement 7)
                slideType.value = 'login'
                showSlide.value = true
            }
        })
    }

    function smsCode() {
        form?.value.validator(model.form.data, model.form.phoneRules).then(async (res: { isPassed: boolean }) => {
            if (res.isPassed) {
                if (model.countdown > 0) return
                slideType.value = 'sms'
                showSlide.value = true
            }
        })
    }

    function onSlideSuccess() {
        if (slideType.value === 'sms') {
            // 立即开启倒计时（乐观更新），接口报错也不停止，防止恶意连点
            startCountdown()

            // 发送验证码
            const params = {
                mobile: model.form.data.username,
                smsmode: '1',
            }
            API.sysSms(params)
                .then(async () => {
                    Message.toast('验证码已发送')
                })
                .catch((err) => {
                    // 即使接口返回 code: 130 等错误，也不干扰已启动的倒计时
                    console.error('短信发送业务异常:', err)
                })
        } else {
            // 执行登录
            doLogin()
        }
    }

    function doLogin() {
        model.loading = true
        if (loginMode.value === 1) {
            // 验证码登录
            const params = {
                mobile: model.form.data.username,
                captcha: model.form.data.code,
            }
            API.phoneLogin(params)
                .then(handleLoginSuccess)
                .finally(() => (model.loading = false))
        } else {
            // 密码登录
            const params = {
                username: model.form.data.username,
                password: model.form.data.password,
            }
            API.sysLogin(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
        countdownTimer = setInterval(() => {
            model.countdown--
            if (model.countdown <= 0) {
                clearInterval(countdownTimer)
                countdownTimer = null
            }
        }, 1000)
    }

    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(val: any) {
        if (val.index === 0) {
            model.form.data.read = false
        } else {
            model.form.data.read = true
            login()
        }
        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" />
            <view class="header-overlay"></view>
            
            <!-- 顶部装饰元素：漂浮的气象/农业设备（体现数智感） -->
            <image class="float-icon device-1" src="/static/images/nongchang/device1.png" mode="aspectFit" />
            <image class="float-icon device-2" src="/static/images/nongchang/device2.png" mode="aspectFit" />
            
            <!-- 顶部状态栏占位与操作 -->
            <view class="top-nav-bar">
                <view class="close-btn" @click="goHome">
                    <fui-icon name="close" :size="48" color="#fff" />
                </view>
                <view class="switch-action" @click="switchMode(loginMode === 1 ? 2 : 1)">
                    <text>{{ loginMode === 1 ? '密码登录' : '验证码登录' }}</text>
                    <fui-icon name="arrowright" :size="24" color="#fff" />
                </view>
            </view>

            <!-- 品牌标识与数智概览 -->
            <view class="brand-hero">
                <view class="logo-box">
                    <image class="logo-img" src="/static/logo.png" mode="aspectFit" />
                </view>
                <view class="brand-info">
                    <text class="app-title">湘农数智农服</text>
                    <view class="app-slogan">
                        <image src="/static/images/weather/100.svg" class="weather-icon" />
                        <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">
                    <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">{{ loginMode === 1 ? '手机号' : '账号' }}</text>
                            <fui-input
                                v-model="model.form.data.username"
                                :padding="['24rpx', '0']"
                                :placeholder="loginMode === 1 ? '请输入手机号' : '请输入账号'"
                                backgroundColor="transparent"
                                borderColor="#F0F0F0"
                                borderBottom
                                height="110rpx"
                                size="34"
                            />
                        </view>

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

                        <view class="field-item" v-if="loginMode === 2">
                            <text class="field-label">密码</text>
                            <fui-input
                                v-model="model.form.data.password"
                                type="password"
                                :padding="['24rpx', '0']"
                                placeholder="请输入密码"
                                backgroundColor="transparent"
                                borderColor="#F0F0F0"
                                borderBottom
                                height="110rpx"
                                size="34"
                            />
                        </view>
                    </view>

                    <!-- 登录决策 -->
                    <view class="action-footer">
                        <fui-button
                            text="开启农务数字化"
                            background="linear-gradient(90deg, #5DB66F 0%, #4CAF50 100%)"
                            radius="100rpx"
                            height="110rpx"
                            @click="login"
                            :loading="model.loading"
                            :disabled="model.loading"
                            size="36"
                            shadow
                        />
                        
                        <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">
                                <fui-checkbox
                                    color="#5DB66F"
                                    :scale="0.7"
                                    :checked="model.form.data.read"
                                    @change="(e) => (model.form.data.read = e.checked)"
                                />
                                <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>

        <!-- 功能弹窗 -->
        <fui-modal
            :show="readConfirmShow"
            title="服务协议及隐私保护"
            :buttons="[{ text: '不同意', plain: true }, { text: '同意', plain: false, color: '#fff' }]"
            @click="onReadConfirm"
        >
            <view class="modal-notice">
                点击同意即表示您已阅读并理解
                <text class="link-inline" @click.stop="Link.to(Link.services, '服务协议')">《服务协议》</text>
                与
                <text class="link-inline" @click.stop="Link.to(Link.privacy, '隐私政策')">《隐私政策》</text>
            </view>
        </fui-modal>

        <SlideVerify v-model:show="showSlide" @success="onSlideSuccess" />
    </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: 600rpx;
        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.8);
        }

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

        /* 漂浮装饰：增强数智感 */
        .float-icon {
            position: absolute;
            opacity: 0.6;
            filter: drop-shadow(0 4rpx 10rpx rgba(0,0,0,0.2));
            
            &.device-1 {
                width: 120rpx;
                height: 120rpx;
                right: -20rpx;
                top: 150rpx;
                transform: rotate(15deg);
                animation: float-slow 4s ease-in-out infinite;
            }
            &.device-2 {
                width: 100rpx;
                height: 100rpx;
                left: 40rpx;
                bottom: 120rpx;
                transform: rotate(-10deg);
                animation: float-slow 3s ease-in-out infinite alternate;
            }
        }

        .top-nav-bar {
            position: relative;
            z-index: 10;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20rpx 40rpx;

            .switch-action {
                color: #fff;
                font-size: 28rpx;
                display: flex;
                align-items: center;
                background: rgba(255, 255, 255, 0.2);
                padding: 10rpx 24rpx;
                border-radius: 40rpx;
                backdrop-filter: blur(4px);
            }
        }

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

            .logo-box {
                width: 160rpx;
                height: 160rpx;
                background: #fff;
                border-radius: 44rpx;
                display: flex;
                align-items: center;
                justify-content: center;
                box-shadow: 0 16rpx 32rpx rgba(0,0,0,0.15);
                
                .logo-img {
                    width: 100rpx;
                    height: 100rpx;
                }
            }

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

                .app-title {
                    font-size: 48rpx;
                    font-weight: 800;
                    letter-spacing: 4rpx;
                    text-shadow: 0 4rpx 8rpx rgba(0,0,0,0.2);
                }

                .app-slogan {
                    margin-top: 12rpx;
                    font-size: 26rpx;
                    opacity: 0.9;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    
                    .weather-icon {
                        width: 40rpx;
                        height: 40rpx;
                        margin-right: 12rpx;
                    }
                }
            }
        }
    }

    /* 登录卡片层 */
    .main-card-container {
        padding: 0 40rpx;
        margin-top: -100rpx;
        position: relative;
        z-index: 20;
    }

    .aesthetic-card {
        background: #ffffff;
        border-radius: 56rpx;
        padding: 80rpx 50rpx 60rpx;
        box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.08);

        .card-header {
            margin-bottom: 60rpx;
            
            .welcome-text {
                font-size: 40rpx;
                font-weight: bold;
                color: #333;
            }
            .green-line {
                width: 60rpx;
                height: 8rpx;
                background: #5DB66F;
                border-radius: 4rpx;
                margin-top: 16rpx;
            }
        }

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

            .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: 28rpx;
                    color: #5DB66F;
                    padding: 16rpx 32rpx;
                    background: #f1f9f2;
                    border-radius: 50rpx;
                    margin-left: 20rpx;
                    font-weight: 500;

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

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

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

            .auto-hint {
                font-size: 24rpx;
                color: #ccc;
                margin-bottom: 24rpx;
            }

            .reg-btn {
                font-size: 30rpx;
                color: #666;
                font-weight: 500;
                display: inline-block;
                padding: 10rpx 40rpx;
                border: 1rpx solid #eee;
                border-radius: 40rpx;
            }
        }
    }

    .policy-wrapper {
        margin-top: 80rpx;
        
        .policy-label {
            display: flex;
            align-items: flex-start;
        }

        .policy-text {
            font-size: 24rpx;
            color: #bbb;
            margin-left: 12rpx;
            line-height: 1.4;
        }

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

    .modal-notice {
        font-size: 28rpx;
        color: #666;
        line-height: 1.8;
        
        .link-inline {
            color: #5DB66F;
            font-weight: bold;
        }
    }

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

    @keyframes float-slow {
        0%, 100% { transform: translateY(0) rotate(15deg); }
        50% { transform: translateY(-20rpx) rotate(10deg); }
    }
</style>
