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

    const userStore = useUserStore()
    const form = ref()
    const slideVerifyRef = ref()
    const showSlide = ref(false)
    const slideAction = ref<'sms' | 'submit'>('sms')

    const isForgotPwd = ref(false)

    onLoad((options) => {
        if (options?.type === 'forgot') {
            isForgotPwd.value = true
        }
    })

    const model = reactive({
        loading: false,
        countdown: 0,
        form: {
            rules: [
                {
                    name: 'phone',
                    rule: ['required', 'isMobile'],
                    msg: ['请输入手机号', '请输入正确的手机号'],
                },
                {
                    name: 'code',
                    rule: ['required', 'minLength:6', 'maxLength:6'],
                    msg: ['请输入验证码', '验证码为6位数字', '验证码为6位数字'],
                },
                {
                    name: 'password',
                    rule: ['required', 'minLength:6'],
                    msg: ['请输入密码', '密码长度不能少于6位'],
                },
                {
                    name: 'confirmPassword',
                    rule: ['required', 'minLength:6'],
                    msg: ['请确认密码', '密码长度不能少于6位'],
                    validator: [
                        {
                            msg: '两次输入的密码不一致',
                            method: (value: string) => value === model.form.data.password,
                        },
                    ],
                },
            ],
            rulesPhone: [
                {
                    name: 'phone',
                    rule: ['required', 'isMobile'],
                    msg: ['请输入手机号', '请输入正确的手机号'],
                },
            ],
            data: {
                phone: '',
                password: '',
                confirmPassword: '',
                code: '',
                read: false,
            },
        },
    })

    let countdownTimer: any = null

    function submit() {
        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) {
                slideAction.value = 'submit'
                showSlide.value = true
                slideVerifyRef.value.reset()
            } else {
                Message.toast(res.errorMsg)
            }
        })
    }

    function doSubmit() {
        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?.token) {
                    userStore.setToken(body.token)
                    const user = await API.getUserInfo()
                    userStore.setUserInfo(user)
                    Message.toast(isForgotPwd.value ? '密码重置成功' : '注册成功，欢迎加入~')
                    goHome()
                } else {
                    Message.toast(body?.message || (isForgotPwd.value ? '密码重置失败' : '注册失败'))
                }
            })
            .catch((err) => {
                Message.toast(err?.message || (isForgotPwd.value ? '密码重置失败，请稍后重试' : '注册失败，请稍后重试'))
            })
            .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
                slideAction.value = 'sms'
                showSlide.value = true
                slideVerifyRef.value.reset()
            } else {
                Message.toast(res.errorMsg)
            }
        })
    }

    function onSlideSuccess() {
        showSlide.value = false
        if (slideAction.value === 'submit') {
            doSubmit()
        } else {
            startCountdown()

            const params = {
                mobile: model.form.data.phone,
                smsmode: isForgotPwd.value ? 3 : 2,
            }
            API.sysSms(params)
                .then(async () => {
                    Message.toast('验证码已发送')
                })
                .catch((err) => {
                    console.error('短信发送失败:', err)
                })
        }
    }

    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"></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="top-nav-bar">
                <view class="back-btn" @click="goLogin">
                    <fui-icon name="arrowleft" :size="48" color="#fff"></fui-icon>
                </view>
            </view>

            <!-- 品牌标识 -->
            <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">{{ isForgotPwd ? '重置密码' : '加入数智农服' }}</text>
                    <view class="app-slogan">
                        <image src="/static/images/weather/100.svg" class="weather-icon" mode="aspectFit"></image>
                        <text>{{ isForgotPwd ? '设置新密码，安全便捷' : '开启您的智慧农业之旅' }}</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">{{ isForgotPwd ? '重置密码' : '创建新账号' }}</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="['16rpx', '0']"
                                placeholder="请输入手机号"
                                backgroundColor="transparent"
                                placeholderStyle="font-size:16px;"
                                borderColor="#F0F0F0"
                                borderBottom
                                height="80rpx"
                                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="['16rpx', '0']"
                                    placeholder="请输入验证码"
                                    backgroundColor="transparent"
                                    placeholderStyle="font-size:16px;"
                                    borderColor="#F0F0F0"
                                    borderBottom
                                    height="80rpx"
                                    size="30"
                                    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 class="field-item">
                            <text class="field-label">设置密码</text>
                            <fui-input
                                v-model="model.form.data.password"
                                type="password"
                                :padding="['16rpx', '0']"
                                placeholder="请设置6位以上密码（建议字母+数字）"
                                backgroundColor="transparent"
                                placeholderStyle="font-size:16px;"
                                borderColor="#F0F0F0"
                                borderBottom
                                height="80rpx"
                                size="34"
                                autocomplete="new-password"
                            ></fui-input>
                        </view>

                        <view class="field-item">
                            <text class="field-label">确认密码</text>
                            <fui-input
                                v-model="model.form.data.confirmPassword"
                                type="password"
                                :padding="['16rpx', '0']"
                                placeholder="请再次输入密码"
                                backgroundColor="transparent"
                                placeholderStyle="font-size:16px;"
                                borderColor="#F0F0F0"
                                borderBottom
                                height="80rpx"
                                size="34"
                                autocomplete="new-password"
                            ></fui-input>
                        </view>
                    </view>

                    <view class="action-footer">
                        <view class="btn-wrapper">
                            <fui-button
                                :text="isForgotPwd ? '确认重置' : '立即注册'"
                                background="linear-gradient(90deg, #5DB66F 0%, #4CAF50 100%)"
                                radius="100rpx"
                                height="80rpx"
                                @click="submit"
                                :loading="model.loading"
                                :disabled="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="goLogin">{{ isForgotPwd ? '返回登录' : '已有账号？去登录' }}</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="slide-mask" v-if="showSlide" @click.self="showSlide = false">
            <view class="slide-panel">
                <view class="slide-gradient-header"></view>
                <view class="slide-close" @click="showSlide = 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: 460rpx;
        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: 100rpx;
                height: 100rpx;
                right: 20rpx;
                top: 140rpx;
                transform: rotate(10deg);
                animation: float-slow 4s ease-in-out infinite;
            }
            &.device-2 {
                width: 90rpx;
                height: 90rpx;
                left: 30rpx;
                bottom: 80rpx;
                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: 0rpx;

            .logo-box {
                width: 120rpx;
                height: 120rpx;
                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: 76rpx;
                    height: 76rpx;
                }
            }

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

                .app-title {
                    font-size: 38rpx;
                    font-weight: 800;
                    letter-spacing: 2rpx;
                    text-shadow: 0 2rpx 4rpx rgba(0,0,0,0.1);
                }

                .app-slogan {
                    margin-top: 4rpx;
                    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: 36rpx 50rpx 30rpx;
        box-shadow: 0 15rpx 50rpx rgba(0, 0, 0, 0.06);

        .card-header {
            margin-bottom: 24rpx;
            
            .welcome-text {
                font-size: 34rpx;
                font-weight: bold;
                color: #333;
            }
            .green-line {
                width: 44rpx;
                height: 6rpx;
                background: #5DB66F;
                border-radius: 3rpx;
                margin-top: 10rpx;
            }
        }

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

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

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

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

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

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

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

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

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

    .policy-wrapper {
        margin-top: 62rpx;
        
        .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: 22rpx;
            color: #bbb;
            margin-left: 10rpx;
            display: flex;
            align-items: center;
        }

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

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

    .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); }
    }
</style>
