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

    const userStore = useUserStore()

    onLoad(async () => {
        // 获取推送标识并设置 PushClientId 缓存
        // uni.getPushClientId({
        //     success: (res) => {
        //         uni.setStorageSync(PUSH_CLIENT_KEY, res.cid)
        //     },
        // })

        // 检查是否有 token
        const token = userStore.getToken
        if (token) {
            // // 检查登录状态
            // try {
            //     const valid = await Auth.valid.request()
            //     if (valid && userStore.getUserInfo) {
            //         model.isLogin = true
            //     }
            // } catch (error) {
            //     console.log('error', error)
            // }
            model.isLogin = true
        }

        if (model.isLogin) {
            // 刷新用户信息
            await userStore.refreshUserInfo()

            // 跳转到登录页
            goHome()
        } else {
            // 关闭启动页并检查更新
            try {
                await closeSplashscreenAndChechUpgrade()
            } catch (error) {
                console.log('error', error)
            } finally {
                nextTick(() => {
                    model.show = true
                })
            }
        }
    })

    // 页面数据
    const defaultText = '湖南省农业服务平台'
    const readConfirmShow = ref<boolean>(false)
    const form = ref()
    const model = reactive({
        show: false,
        isLogin: false,
        loading: false,
        text: '',
        form: {
            rules: [
                {
                    name: 'username',
                    rule: ['required'],
                    msg: ['请输入手机号/账号'],
                },
                {
                    name: 'password',
                    rule: ['required'],
                    msg: ['请输入密码'],
                },
                {
                    name: 'read',
                    validator: [
                        {
                            msg: '请阅读并同意服务协议和隐私政策',
                            method: (value: boolean) => {
                                readConfirmShow.value = !value
                                return value
                            },
                        },
                    ],
                },
            ],
            data: {
                username: '',
                password: '',
                read: false,
                deviceId: '',
            },
        },
    })

    // TODO: 开发环境快速填入账户密码，并默认勾选已读隐私政策和服务协议
    if (isDevMode()) {
        model.form.data.username = 'admin'
        model.form.data.password = 'ZzqEUxdqARrd!aeH'
        model.form.data.read = true
    }

    /**
     * 登录
     */
    function login() {
        form?.value.validator(model.form.data, model.form.rules).then(async (res: { isPassed: boolean }) => {
            if (res.isPassed) {
                // 登录参数
                const params = {
                    username: model.form.data.username,
                    password: model.form.data.password,
                }

                // 短信登录
                model.loading = true
                API.sysLogin(params)
                    .then(async (body) => {
                        console.log('body', body)
                        if (body) {
                            // 设置登录缓存信息
                            userStore.setToken(body.token)

                            // 登录成功后查询用户信息
                            const user = await API.getUserInfo()
                            userStore.setUserInfo(user)

                            // 打开登录页
                            goHome()
                            Message.toast(`登录成功, 欢迎回来!`)
                        } else {
                            Message.toast(body.message)
                            return false
                        }
                    })
                    .finally(() => {
                        model.loading = false
                    })
            }
        })
    }

    /**
     * 跳转到门户页
     */
    function goHome() {
        uni.reLaunch({
            url: '/pages/shouye/shouye',
        })
    }

    // 添加欢迎登录的文字打字动态效果
    let loop = null
    let direction = 'right'
    const count = ref(0)
    watch(
        () => model.show,
        (show) => {
            if (show) {
                loop && clearInterval(loop)
                loop = setInterval(() => {
                    if (direction === 'right') {
                        count.value++
                        if (count.value > defaultText.length + 20) {
                            direction = 'left'
                            count.value = defaultText.length
                        }
                    } else {
                        count.value--
                        if (count.value < 0) {
                            direction = 'right'
                        }
                    }

                    if (count.value > defaultText.length) {
                        model.text = defaultText
                    } else if (count.value < 0) {
                        model.text = ''
                    } else {
                        model.text = defaultText.slice(0, count.value)
                    }
                }, 200)
            }
        },
    )

    onUnload(() => {
        model.show = false
        loop && clearInterval(loop)
    })

    function onReadConfirm(val) {
        if (val.index === 0) {
            model.form.data.read = false
        } else {
            model.form.data.read = true
            login()
        }
        readConfirmShow.value = false
    }
</script>

<template>
    <view class="warp">
        <!-- <image class="login-warp" src="/static/login/login_bg.png" /> -->
        <view class="login-bg-wrap">
            <image class="login-bg" src="/static/logo.png" />
            <view class="logo-content-wrap">
                <!-- <view class="">{{ '欢迎登录' }}</view> -->
                <view class="logo-text mb-3">{{ model.text }}</view>
                <!-- <text class="text-#999 text-24">{{ '*小程序仅供内部员工使用' }}</text> -->
            </view>
        </view>
        <fui-form class="form" ref="form" top="50" :padding="['0rpx', '32rpx']">
            <fui-input
                height="100rpx"
                class="input"
                autocomplete="off"
                :required="false"
                clearable
                trim
                placeholder="请输入手机号/账号"
                v-model="model.form.data.username"
                name="mobile"
                backgroundColor="transparent"
                borderColor="#DDDDDD"
                maxlength="11"
            >
                <template #left>
                    <view class="fui-left__icon mr-2">
                        <fui-icon name="my" color="#333" :size="48" />
                    </view>
                </template>
            </fui-input>

            <fui-input
                height="100rpx"
                class="input"
                password
                autocomplete="new-password"
                code
                :required="false"
                clearable
                trim
                placeholder="请输入密码"
                v-model="model.form.data.password"
                name="code"
                marginTop="50"
                backgroundColor="transparent"
                borderColor="#DDDDDD"
            >
                <template #left>
                    <view class="fui-left__icon mr-2">
                        <fui-icon name="lock" color="#333" :size="48" />
                    </view>
                </template>
            </fui-input>
            <view class="btn__box flex-center p-32rpx box-border">
                <fui-button
                    height="88rpx"
                    background="#67c17a"
                    size="32rpx"
                    radius="8rpx"
                    text="立即登录"
                    @click="login"
                    :disabled="model.loading"
                    :loading="model.loading"
                />
            </view>
        </fui-form>
        <!-- </view> -->
        <fui-checkbox-group class="checkbox" name="checkbox">
            <view class="fui-list__item fiexdText">
                <view class="fui-align__center" style="justify-content: center">
                    <view
                        class="fui-text privacy-wrap"
                        style="font-size: 28rpx; text-align: center; align-items: center"
                    >
                        <fui-label style="display: inline-flex; align-items: center">
                            <fui-checkbox
                                value="true"
                                color="#4da25b"
                                :checked="model.form.data.read"
                                @change="(e) => (model.form.data.read = e.checked)"
                                style="margin-right: 10rpx; width: 32rpx; height: 32rpx; margin-top: 2rpx"
                            />
                            已阅读并同意
                        </fui-label>
                        <fui-text
                            @tap="Link.to(Link.services, '服务协议')"
                            size="28rpx"
                            text="《服务协议》"
                            color="#4da25b"
                        />和
                        <fui-text
                            @tap="Link.to(Link.privacy, '隐私政策')"
                            size="28rpx"
                            text="《隐私政策》"
                            color="#4da25b"
                        />
                    </view>
                </view>

                <!-- 安全区 -->
                <fui-safe-area />
            </view>
        </fui-checkbox-group>

        <fui-modal
            :show="readConfirmShow"
            title="服务协议及隐私保护"
            :buttons="[
                { text: '不同意', plain: true },
                { text: '同意', plain: false, color: '#fff' },
            ]"
            @click="onReadConfirm"
        >
            <text class="fui-descr">
                <text> 为了更好地保障您的合法权益，请您阅读并同意以下协议 </text>
                <fui-text
                    @tap="Link.to(Link.services, '服务协议')"
                    size="28rpx"
                    text="《服务协议》"
                    color="#1890FF"
                />和
                <fui-text @tap="Link.to(Link.privacy, '隐私政策')" size="28rpx" text="《隐私政策》" color="#1890FF" />
            </text>
        </fui-modal>
    </view>
</template>

<style lang="less" scoped>
    // .login-warp {
    //     width: 100%;
    //     height: calc(100vh);
    //     position: absolute;
    //     // border: 1px solid #000;
    //     z-index: 0;
    // }

    @keyframes blink-caret {
        0%,
        100% {
            border-right-color: #333;
        }

        50% {
            border-right-color: transparent;
        }
    }

    .warp {
        position: relative;
        font-size: 24rpx;
        height: calc(100vh);
        block-size: 100% 100%;
        // background-size: 100% 100%;
        // border: 1px solid #000;
        background-color: #fff;
    }

    .fui-descr {
        letter-spacing: 1rpx;
        padding: 50rpx;
        font-size: 24rpx;
        color: #b2b2b2;
        padding-top: 12rpx;
        padding-bottom: 48rpx;

        ::v-deep(.fui-text__content) {
            text-indent: 0 !important;
        }
    }

    .login-bg-wrap {
        position: absolute;
        top: 260rpx;
        width: 100%;
        // border: 1px solid #000;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        .login-bg {
            width: 124rpx;
            height: 124rpx;
        }

        .logo-content-wrap {
            // position: absolute;
            // left: 40rpx;
            // bottom: 40rpx;
            font-size: 40rpx;
            color: #474747;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;

            .logo-text {
                margin-top: 20rpx;
                font-weight: bold;
                display: flex;
                width: fit-content;
                height: 40rpx;
                line-height: 40rpx;
                letter-spacing: 0.15em;
                border-right: 0.2em solid transparent;
                padding-right: 0.15em;
                animation: blink-caret 1s infinite;
            }
        }
    }

    .form {
        position: absolute;
        top: 500rpx;
        width: 100%;
        z-index: 10;
    }

    .checkbox {
        position: fixed;
        left: 0rpx;
        bottom: 32rpx;
        width: 100%;
        z-index: 10;
    }

    .privacy-wrap {
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .input,
    .btn__box {
        width: 100%;
        height: 100rpx;
        margin-top: 60rpx;
    }

    .fiexdText {
        // position: absolute;
        width: 100%;
        margin-top: 40rpx;
    }

    :deep(.fui-input__border-bottom) {
        right: 32rpx !important;
    }
</style>
