<template>
    <div>
        <div class="absolute inset-0">
            <img src="/assets/images/auth/bg-gradient.png" alt="image" class="h-full w-full object-cover" />
        </div>

        <div
            class="relative flex items-center justify-center bg-[url(/assets/images/auth/map.png)] bg-cover bg-center bg-no-repeat dark:bg-[#060818] sm:px-16">


            <img src="/assets/images/auth/coming-soon-object3.png" alt="image"
                class="absolute right-0 top-0 h-[300px]" />

            <div
                class="relative w-full max-w-[870px] rounded-md bg-[linear-gradient(45deg,#fff9f9_0%,rgba(255,255,255,0)_25%,rgba(255,255,255,0)_75%,_#fff9f9_100%)] p-2 dark:bg-[linear-gradient(52.22deg,#0E1726_0%,rgba(14,23,38,0)_18.66%,rgba(14,23,38,0)_51.04%,rgba(14,23,38,0)_80.07%,#0E1726_100%)]">
                <div
                    class="relative flex flex-col justify-center rounded-md bg-white/60 backdrop-blur-lg dark:bg-black/50 px-6 lg:min-h-[758px] py-20">
                    <div class="absolute top-6 end-6">
                        <div class="dropdown">

                        </div>
                    </div>
                    <div class="mx-auto w-full max-w-[440px]">
                        <div class="mb-10">
                            <h1 class="text-3xl font-extrabold uppercase !leading-snug text-primary md:text-4xl">Sign in
                            </h1>
                            <p class="text-base font-bold leading-normal text-white-dark">欢迎登录V3StudioApp</p>
                        </div>
                        <form class="space-y-5 dark:text-white" @submit.prevent="handleSubmit">
                            <div>
                                <label for="Email">请输入账号</label>
                                <div class="relative text-white-dark">
                                    <input id="Email" type="text" placeholder="请输入账号"
                                        class="form-input ps-10 placeholder:text-white-dark"
                                        v-model="inputValue.username" />
                                    <span class="absolute start-4 top-1/2 -translate-y-1/2">
                                        <icon-mail :fill="true" />
                                    </span>
                                </div>
                            </div>
                            <div>
                                <label for="Password">请输入密码</label>
                                <div class="relative text-white-dark">
                                    <input id="Password" type="password" placeholder="请输入密码"
                                        class="form-input ps-10 placeholder:text-white-dark"
                                        v-model="inputValue.password" />
                                    <span class="absolute start-4 top-1/2 -translate-y-1/2">
                                        <icon-lock-dots :fill="true" />
                                    </span>
                                </div>
                            </div>
                            <div>
                                <label for="Captcha">验证码</label>
                                <div class="relative text-white-dark" style="display: flex;align-items: center;">
                                    <input id="Captcha" type="text" placeholder="请输入验证码"
                                        class="form-input ps-10 placeholder:text-white-dark"
                                        v-model="inputValue.captcha" />
                                    <img :src="validcodeImg" alt="" @click="changeValidcode()" style="height: 38px">
                                </div>
                            </div>
                            <div>
                                <label class="flex cursor-pointer items-center">
                                    <input v-model="inputValue.checked" type="checkbox"
                                        class="form-checkbox bg-white dark:bg-black" />
                                    <span class="text-white-dark">记住密码</span>
                                </label>
                            </div>
                            <button type="submit"
                                class="btn btn-gradient !mt-6 w-full border-0 uppercase shadow-[0_10px_20px_-10px_rgba(67,97,238,0.44)]">
                                登录
                            </button>
                        </form>
                        <!-- 新用户注册账号--暂不开放 -->
                        <!-- <div class="relative my-7 text-center md:mb-9">
                            <span class="absolute inset-x-0 top-1/2 h-px w-full -translate-y-1/2 bg-white-light dark:bg-white-dark"></span>
                            <span class="relative bg-white px-2 font-bold uppercase text-white-dark dark:bg-dark dark:text-white-light">or</span>
                        </div> -->



                        <!-- <div class="text-center dark:text-white">
                           新用户请注册 ?
                            <router-link to="/auth/boxed-signup" class="uppercase text-primary underline transition hover:text-black dark:hover:text-white">
                                注册
                            </router-link>
                        </div> -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, computed, reactive, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import appSetting from '@/app-setting';
import { useAppStore } from '@/stores/index';
import { useRouter } from 'vue-router';
import { useMeta } from '@/composables/use-meta';

import IconCaretDown from '@/components/icon/icon-caret-down.vue';
import IconMail from '@/components/icon/icon-mail.vue';
import IconLockDots from '@/components/icon/icon-lock-dots.vue';
import IconInstagram from '@/components/icon/icon-instagram.vue';
import IconFacebookCircle from '@/components/icon/icon-facebook-circle.vue';
import IconTwitter from '@/components/icon/icon-twitter.vue';
import IconGoogle from '@/components/icon/icon-google.vue';

//封装接口
import { UserService } from '@/api/api'
import { v4 as uuidv4 } from "uuid";
useMeta({ title: 'Login Boxed' });
let uuid: string = ''
let validcodeImg = ref('');

/* 定义表单且提交表单 */
const inputValue = reactive({
    username: '',
    password: '',
    uuid: '',
    scene: 'LOGIN',
    captcha: '',
    checked: false
});
const loginForm = ref({
    username: '',
    password: "",
})
interface LoginResponse {
    data: any;
    response: {
        data: {
            refresh_token: string
        };
    }
}
const MixinClone = (obj) => {
    return JSON.parse(JSON.stringify(obj))
}
const handleSubmit = async () => {
    try {
        inputValue.uuid = uuid;
        const params = MixinClone(inputValue)
        const response = await UserService.login(params) as LoginResponse
        store.setUser({
            ...response.data,
            token: response.data.refresh_token
        });
        // 判断是否记住密码
        if (inputValue.checked) {
            loginForm.value.username = inputValue.username
            loginForm.value.password = inputValue.password
            localStorage.setItem("loginForm", JSON.stringify(loginForm));
        } else {
            localStorage.setItem("loginForm", JSON.stringify({}));
        }
        // 路由跳转到首页
        router.replace({
            name: 'home'
        });
    } catch (error) {
        changeValidcode()
        console.error('Login failed:', error);
    }
    /* try {
        
        const res:Object = await reactive(UserService.login(inputValue))
        store.setUser({
            ...res.data,
            token: res.data.refresh_token
        })
        router.replace({
            name: 'home'
        })
    } catch (error) {
        console.error('Login failed:', error);
    } */
};
onMounted(() => {
    const _uuid = uuidv4()
    uuid = _uuid
    changeValidcode()
    //在setup中，用来加载页面时，查看账户密码是否存在
    if (localStorage.getItem("loginForm") != null && Object.keys(localStorage.getItem("loginForm") ?? 'null').length > 2) {

        inputValue.checked = true;
        var userPwdInfo = JSON.parse(localStorage.getItem("loginForm") ?? 'null');
        console.log(userPwdInfo._value);
        inputValue.username = userPwdInfo._value.username;
        inputValue.password = userPwdInfo._value.password;

    } else {
        inputValue.checked = false;
    }


});
const router = useRouter();

const store = useAppStore();
// multi language
const i18n = reactive(useI18n());
const changeLanguage = (item: any) => {
    i18n.locale = item.code;
    appSetting.toggleLanguage(item);
};

const currentFlag = computed(() => {
    return `/assets/images/flags/${i18n.locale.toUpperCase()}.svg`;
});

//获取验证码
const changeValidcode = async () => {
    try {
        validcodeImg.value = await UserService.login1(uuid);
    } catch (error) {
        console.error('Failed to load image:', error);
    }
}

</script>
