<template>
    <section class="mx-auto max-w-xl">
        <div class="flex min-h-full flex-1 flex-col justify-center py-12 sm:px-6 lg:px-8">
            <div class="sm:mx-auto sm:w-full sm:max-w-md">
                <img class="mx-auto w-80 h-24" :src="logo" alt="" />
                <h2 class=" text-center text-2xl font-bold leading-9 tracking-tight text-gray-900">{{ t('signIn.title') }}
                </h2>
            </div>
            <div class="mt-10 sm:mx-auto sm:w-full sm:max-w-[480px]">
                <div class="bg-white px-6 py-12 shadow sm:rounded-lg sm:px-12">
                    <form class="space-y-6" @submit.prevent="onSubmit">
                        <div>
                            <label for="phone-number" class="block text-sm font-medium leading-6 text-gray-900">{{
                                t('signIn.p_n') }}</label>
                            <div class="relative mt-2 rounded-md shadow-sm">
                                <div class="absolute inset-y-0 left-0 flex items-center">
                                    <!-- <label for="country" class="sr-only">{{ t('signIn.country') }}</label> -->
                                    <v-select :options="countries" label="localName" v-model="selectCountry"
                                        :clearable="false" @input="onFocusCountrySelect">
                                        <template v-slot:no-options="{ search, searching }">
                                            <template v-if="searching">
                                                {{ t('common.noResult') }}
                                            </template>
                                            <em v-else style="opacity: 0.5">Search</em>
                                        </template></v-select>
                                </div>
                                <input type="tel" name="phone-number" id="phone-number" v-model="formData.mobile" class="block w-full rounded-md border-0 pl-32 py-1.5 outline-none
                                     text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300
                                      placeholder:text-gray-400 focus:ring-2 focus:ring-inset
                                       focus:ring-[#F96825] sm:text-sm sm:leading-6" />
                            </div>
                        </div>
                        <div>
                            <label for="password" class="block text-sm font-medium leading-6 text-gray-900">{{
                                t('signIn.password') }}</label>
                            <div class="mt-2">
                                <input id="password" name="password" type="password" autocomplete="password"
                                    v-model="formData.password" :required="true" class="block w-full rounded-md border-0 px-1.5 py-1.5 outline-none
                                     text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300
                                      placeholder:text-gray-400 focus:ring-2 focus:ring-inset
                                       focus:ring-[#F96825] sm:text-sm sm:leading-6" />
                            </div>
                        </div>

                        <div class="flex items-center justify-between">
                            <div class="flex items-center">
                                <input id="remember-me" name="remember-me" type="checkbox" v-model="formData.rememberMe"
                                    class="h-4 w-4 rounded border-gray-300 text-[#F96825] focus:ring-[#F96825]" />
                                <label for="remember-me" class="ml-3 block text-sm leading-6 text-gray-900">{{
                                    t('signIn.remember') }}</label>
                            </div>

                            <div class="text-sm leading-6">
                                <a href="#" class="font-semibold text-[#F96825] hover:text-[#F96825]"
                                    @click="openService">{{ t('signIn.forgot') }}</a>
                            </div>
                        </div>

                        <div>
                            <button type="submit"
                                class="flex w-full justify-center rounded-md
                                 bg-[#F96825] px-3 py-1.5 
                                 text-sm font-semibold leading-6 text-white shadow-sm hover:bg-[#F96825] focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600">{{
                                     t('signIn.sign_in') }}</button>
                        </div>
                    </form>
                </div>

                <p class="mt-10 text-center text-sm text-gray-500">
                    {{ t('signIn.n_a_m') }}
                    <a href="/sign-up" class="font-semibold leading-6 text-[#F96825] hover:text-[#F96825]">
                        {{ t('signIn.s_u_n') }}
                    </a>
                </p>
            </div>
        </div>
        <Dialog ref="dialogRef" />
    </section>
</template>


<script lang="ts" setup>
import { onMounted, ref } from "vue";
import { signIn } from '@/api/auth'
import { useRouter } from "vue-router";
import * as AuthUtils from '@/utils/auth'
import Dialog from '@/components/Dialog.vue'
import { useI18n } from 'vue-i18n'
import { listCountry } from '@/api/countries'
import vSelect from 'vue-select'
import 'vue-select/dist/vue-select.css';
import CryptoJS from 'crypto-js';
import * as PageUtils from '@/utils/pageUtils'

const logo  = ref('')

const { t } = useI18n()

const router = useRouter()

const formData = ref({
    mobile: '',
    password: '',
    rememberMe: false
})

const countries = ref([])
const selectCountry = ref('')

const initCountries = async () => {
    const res = await listCountry() as any
    res.forEach((item: any) => {
        countries.value.push(item)
    })

}

// dialog
const dialogRef = ref()


const onFocusCountrySelect = (value) => {
    console.log(value)
}

const onSubmit = async () => {
    formData.value.countryCode = selectCountry.value.phoneCode
    const res = await signIn(formData.value) as any
    const code = res.code
    if (code === 0) {
         localStorage.removeItem("chatOpen")
        AuthUtils.setToken(res.data)
        router.push('/')
    }
    if (code === 1004003000) {
        dialogRef.value.open({
            type: 'warning',
            content: 'The mobile number or password is incorrect. Please try again.',
            showCancelButton: false,
            confirmText: 'Confirm',
        })
        return
    }
}

const base64url = (source: Uint8Array) => {
  // Encode in classical base64
  console.log(source)
  let encodedSource = btoa(String.fromCharCode.apply(null, source as unknown as number[]));
  // Remove padding equal characters
  encodedSource = encodedSource.split('=')[0];
  // Replace characters according to base64url specifications
  encodedSource = encodedSource.replace(/\+/g, '-');
  encodedSource = encodedSource.replace(/\//g, '_');
  return encodedSource;
}

const generateToken = () => {
    const secret = import.meta.env.VITE_AES_SECRET
    const payload = {
        secret: "forgetPassword",
        expireTime: new Date().getTime() + 1000 * 60 * 60 * 24 * 2,
    }
    let key = CryptoJS.enc.Base64.parse(secret);
    let encrypted = CryptoJS.TripleDES.encrypt(JSON.stringify(payload), key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 });
    let decrypt = CryptoJS.TripleDES.decrypt(encrypted.toString(), key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 });
    console.log(encrypted.toString())
    console.log(CryptoJS.enc.Utf8.stringify(decrypt).toString())
    let encoder = new TextEncoder();
    let data = encoder.encode(encrypted.toString());
    return base64url(data);;
}

const  ase_url = import.meta.env.VITE_KF_URL;

const openService = () => {
    const domain = window.location.host
    const key = generateToken()
    if (import.meta.env.MODE === 'dev') {
        window.open(ase_url+'?k=' + encodeURIComponent(key))
        return
    }
    // 忘记密码  使用当前时间戳+ forgetPassword 作为key
    const serviceUrl = `https://service.${domain}` + '?k=' + encodeURIComponent(key)
    window.open(serviceUrl)
}



onMounted(async () => {
    await initCountries()
    const config = PageUtils.getH5PagesConfig()
    logo.value =  config.logo
    selectCountry.value = countries.value[0]
})

</script>

<style scoped>
.top-bg {
    background-image: url('@/assets/imgs/login/login-bg.png');
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center;
}


:deep(.vs__dropdown-toggle) {
    width: 120px;
    height: 35px;
    --vs-border-width: 0px;
}
</style>