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

    const userStore = useUserStore()

    onShow(async () => {
        // 检查是否有 token
        const token = userStore.getToken
        if (token) {
            model.isLogin = true
        }

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

            // 跳转到登录页
            goHome()
            Message.toast(`欢迎回来~`)
        } else {
            // 关闭启动页并检查更新
            try {
                await checkUpgrade()
            } 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: defaultText,
        countdown: 0, // 倒计时秒数
        countdownTimer: null, // 倒计时定时器
        form: {
            phoneRules: [
                {
                    name: 'username',
                    rule: ['required'],
                    msg: ['请输入手机号'],
                },
            ],
            rules: [
                {
                    name: 'username',
                    rule: ['required'],
                    msg: ['请输入手机号'],
                },
                {
                    name: 'code',
                    rule: ['required'],
                    msg: ['请输入验证码'],
                },
                {
                    name: 'read',
                    validator: [
                        {
                            msg: '请阅读并同意服务协议和隐私政策',
                            method: (value: boolean) => {
                                readConfirmShow.value = !value
                                return value
                            },
                        },
                    ],
                },
            ],
            data: {
                username: '',
                code: '',
                read: false,
                deviceId: '',
            },
        },
    })

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

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

                // 短信登录
                model.loading = true
                API.phoneLogin(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 smsCode() {
        form?.value.validator(model.form.data, model.form.phoneRules).then(async (res: { isPassed: boolean }) => {
            if (res.isPassed) {
                // 如果已经在倒计时中，不重复发送
                if (model.countdown > 0) {
                    return
                }

                const params = {
                    /* mobile: model.form.data.username,
					smsmode: '0', */
					
					mobile: model.form.data.username,
					smsmode: 1,
                }
                API.sysSms(params)
                    .then(async (body) => {
                        Message.toast('验证码已发送')
                        console.log('body', body)
                        // 开始倒计时
                        startCountdown()
                    })
                    .catch(() => {
                        // 即使请求失败也显示倒计时，防止重复点击
                        startCountdown()
                    })
            }
        })
    }

    /**
     * 开始倒计时
     */
    function startCountdown() {
        model.countdown = 60

        model.countdownTimer = setInterval(() => {
            model.countdown--

            if (model.countdown <= 0) {
                clearInterval(model.countdownTimer)
                model.countdownTimer = null
            }
        }, 1000)
    }

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

    onHide(() => {
        model.show = false
    })

    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="login_warp">
		<image class="login_top_bg" src="/static/images/login/login_top_bg.png" />
		<view class="login_top_warp">
			<view class="login_hello">
				<text class="text_hello">您好，欢迎使用</text>
				<view class="login_server_name"><text class="text_server_name">湘农数智服务平台</text></view>
			</view>
		</view>
		
		<fui-form class="form" ref="form" top="0" :padding="['0rpx', '0rpx']" background="#e46962">
			<view class="login_content">
				<view class="login-input-area">
					<view class="user_phone">
						<image class="user_phone_img" src="/static/images/register/user.png" />
						<view class="user_text_view"><text class="view_text">手机号</text></view>
					</view>
					<view class="input-bottom-border">
						<fui-input
							height="94rpx"
							:padding="['0rpx', '0rpx', '0rpx', '12rpx']"
							class="input"
							autocomplete="off"
							:required="false"
							clearable
							trim
							type="number"
							placeholder="请输入手机号"
							v-model="model.form.data.username"
							name="mobile"
							backgroundColor="transparent"
							borderColor="transparent"
							maxlength="11"
						>
						</fui-input>
					</view>
					<view class="user_phone mt50">
						<image class="user_phone_img" src="/static/images/register/sms.png" />
						<view class="user_text_view"><text class="view_text">验证码</text></view>
					</view>
					<view class="input-bottom-border">
						<fui-input
							height="94rpx"
							:padding="['0rpx', '0rpx', '0rpx', '12rpx']"
							class="input"
							type="number"
							placeholder="请输入验证码"
							v-model="model.form.data.code"
							backgroundColor="transparent"
							borderColor="transparent"
						><fui-button
							width="200rpx"
							height="64rpx"
							:background="model.countdown > 0 ? '#CCCCCC' : '#67c17a'"
							:color="model.countdown > 0 ? '#67c17a' : '#fff'"
							@click="smsCode"
							:size="28"
							:disabled="model.countdown > 0"
							:text="model.countdown > 0 ? `${model.countdown}秒后重试` : '获取验证码'"
						/>
						</fui-input>
					</view>
				</view>
				
				<view class="submit_btn_view">
				    <fui-button
				        height="72rpx"
				        background="#5DB66F"
				        size="28rpx"
				        radius="36rpx"
				        text="立即登录"
				        @click="login"
				        :disabled="model.loading"
				        :loading="model.loading"
				    />
				</view>
				
			</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"
		                    />
		                    <text style="color: #999;;font-size:28rpx;">已阅读并同意</text>
		                </fui-label>
		                <fui-text
		                    @tap="Link.to(Link.services, '服务协议')"
		                    size="28rpx"
		                    text="《服务协议》"
		                    color="#4da25b"
		                /><text style="color: #999;;font-size:28rpx;">与</text>
		                <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>
    @keyframes blink-caret {
        0%,
        100% {
            border-right-color: #333;
        }

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

    .login_warp {
        position: relative;
        font-size: 24rpx;
        height: calc(100vh);
        block-size: 100% 100%;
        background-color: #fafefc;

		.login_top_bg{
			width:750rpx;
			height:1324rpx;
			position:absolute;
			left:0rpx;
			top:0rpx;
		}

		.login_top_warp{
			width:750rpx;
			height:482rpx;
			position: relative;

			.login_hello{
				position: absolute;
				left: 50rpx;
				top: 226rpx;
				color: rgb(51 51 51 / 100%);

				.text_hello{
					font-size: 32rpx;
					font-weight: 400;
					letter-spacing: 0rpx;
					line-height: 40rpx;
				}

				.login_server_name{
					margin-top:32rpx;

					.text_server_name{
						font-size: 40rpx;
						font-weight: 500;
						letter-spacing: 0rpx;
						line-height: 40rpx;
					}
				}
			}
		}
		
		.login_content{
			display:flex;
			justify-content: center;
			flex-wrap:wrap;
			position: relative;

			.login-input-area{
				width: 650rpx;
				// border:1rpx red solid;
				.user_phone{
					display:flex;
					align-items: center;

					.user_phone_img{
						width: 40rpx;
						height: 40rpx;
					}
				}

				.user_text_view{
					margin-left:12rpx;
					height: 40rpx;
					line-height: 40rpx;

					.view_text{
						font-size: 30rpx;
						font-weight: 500;
						letter-spacing: 0rpx;
						color: rgb(51 51 51 / 100%);
					}
				}

				.input-bottom-border{
					border-bottom: 2rpx #eee solid;
				}

				.mt50{
					margin-top:50rpx;
				}
			}
		}

		.submit_btn_view{
			margin-top:120rpx;
			width:650rpx;
		}
		
		.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;
		    }
		}
		
		.form {
		    position: absolute;
		    top: 480rpx;
		    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 {
		    width: 100%;
		    margin-top: 40rpx;
		}
		
		:deep(.fui-input__border-bottom) {
		    right: 32rpx !important;
		}
		
		.btn-register {
		    color: cadetblue;
		}
    }
</style>
