<script setup lang="ts">
    import * as API from '/@/api/model/userInfo'
    import SlideVerify from '@/components/slide-verify/SlideVerify.vue'

    const defaultText = '湘农数智农服'
    const form = ref()
    const showSlide = ref(false)
    const slideType = ref<'sms' | 'register'>('register')
    const model = reactive({
        loading: false,
        countdown: 0, 
        form: {
            rules: [
                {
                    name: 'phone',
                    rule: ['required', 'isMobile'],
                    msg: ['请输入手机号', '请输入正确的手机号'],
                },
                {
                    name: 'code',
                    rule: ['required'],
                    msg: ['请输入验证码'],
                },
                {
                    name: 'password',
                    rule: ['required', 'minLength:6'],
                    msg: ['请输入密码', '密码长度不能少于6位'],
                },
            ],
            rulesPhone: [
                {
                    name: 'phone',
                    rule: ['required', 'isMobile'],
                    msg: ['请输入手机号', '请输入正确的手机号'],
                },
            ],
            data: {
                phone: '',
                password: '',
                code: '',
                read: false,
            },
        },
    })

    let countdownTimer: any = null

    function register() {
        if (!model.form.data.read) {
            Message.toast('请阅读并同意服务协议及隐私政策')
            return
        }

        form?.value.validator(model.form.data, model.form.rules).then(async (res: { isPassed: boolean }) => {
            if (res.isPassed) {
                slideType.value = 'register'
                showSlide.value = true
            }
        })
    }

    function doRegister() {
        const params = {
            phone: model.form.data.phone,
            password: model.form.data.password,
            code: model.form.data.code,
        }

        model.loading = true
        API.sysRegister(params)
            .then(async (body) => {
                if (body) {
                    Message.toast(`注册成功, 请登录~`)
                    setTimeout(() => {
                        goLogin()
                    }, 1500)
                }
            })
            .finally(() => {
                model.loading = false
            })
    }

    function smsCode() {
        form?.value.validator(model.form.data, model.form.rulesPhone).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') {
            // 开启乐观倒计时，不论接口成败，60s内不准重发
            startCountdown()

            const params = {
                mobile: model.form.data.phone,
                smsmode: 2, // 2-注册
            }
            API.sysSms(params)
                .then(async () => {
                    Message.toast('验证码已发送')
                })
                .catch((err) => {
                    console.error('注册短信发送失败:', err)
                })
        } else {
            doRegister()
        }
    }

    function startCountdown() {
        if (countdownTimer) clearInterval(countdownTimer)
        model.countdown = 60
        countdownTimer = setInterval(() => {
            model.countdown--
            if (model.countdown <= 0) {
                clearInterval(countdownTimer)
                countdownTimer = null
            }
        }, 1000)
    }

    function goLogin() {
        uni.navigateTo({
            url: '/pages/login/login',
        })
    }

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

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

    onUnload(() => {
        if (countdownTimer) {
            clearInterval(countdownTimer)
            countdownTimer = null
        }
    })
</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/device3.png" mode="aspectFit" />
            
            <!-- 顶部导航 -->
            <view class="top-nav-bar">
                <view class="back-btn" @click="goLogin">
                    <fui-icon name="arrowleft" :size="48" 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">手机号</text>
                            <fui-input
                                v-model="model.form.data.phone"
                                :padding="['24rpx', '0']"
                                placeholder="请输入手机号"
                                backgroundColor="transparent"
                                borderColor="#F0F0F0"
                                borderBottom
                                height="110rpx"
                                size="34"
                                maxlength="11"
                            />
                        </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="请输入验证码"
                                    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">
                            <text class="field-label">设置密码</text>
                            <fui-input
                                v-model="model.form.data.password"
                                type="password"
                                :padding="['24rpx', '0']"
                                placeholder="请设置6位以上登录密码"
                                backgroundColor="transparent"
                                borderColor="#F0F0F0"
                                borderBottom
                                height="110rpx"
                                size="34"
                                autocomplete="new-password"
                            />
                        </view>
                    </view>

                    <view class="action-footer">
                        <fui-button
                            text="立即注册"
                            background="linear-gradient(90deg, #5DB66F 0%, #4CAF50 100%)"
                            radius="100rpx"
                            height="110rpx"
                            @click="register"
                            :loading="model.loading"
                            :disabled="model.loading"
                            size="36"
                            shadow
                        />
                        
                        <view class="secondary-links">
                            <view class="reg-btn" @click="goLogin">已有账号？去登录</view>
                        </view>
                    </view>

                    <!-- 隐私合规：对齐优化 -->
                    <view class="policy-wrapper">
                        <fui-checkbox-group>
                            <fui-label class="policy-label">
                                <view class="checkbox-align">
                                    <fui-checkbox
                                        color="#5DB66F"
                                        :scale="0.7"
                                        :checked="model.form.data.read"
                                        @change="(e) => (model.form.data.read = e.checked)"
                                    />
                                </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>

        <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: 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;
            }
        }

        .top-nav-bar {
            position: relative;
            z-index: 10;
            padding: 20rpx 40rpx;
        }

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

            .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;
                    text-shadow: 0 2rpx 4rpx rgba(0,0,0,0.1);
                }

                .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;
                    }
                }
            }
        }
    }

    .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: 70rpx;

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

            .reg-btn {
                font-size: 28rpx;
                color: #888;
                padding: 10rpx 40rpx;
                border: 1rpx solid #f0f0f0;
                border-radius: 40rpx;
            }
        }
    }

    .policy-wrapper {
        margin-top: 60rpx;
        
        .policy-label {
            display: flex;
            align-items: center; /* 垂直居中 */
            justify-content: center;
        }

        .checkbox-align {
            line-height: 1;
            display: flex;
            align-items: center;
        }

        .policy-text {
            font-size: 24rpx;
            color: #bbb;
            margin-left: 12rpx;
            display: flex;
            align-items: center;
        }

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

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

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