<template>
    <div class="login-content w-full h-full flex justify-center items-center">
        <div class="box w-1/2 h-1/2 min-w-400px min-h-400px">
            <div class="box-left"></div>
            <div class="box-right flex flex-col px-4 min-w-400px gap-24px justify-center items-center">
                <div class="font-bold text-gray-700 text-3xl">商户询报价系统</div>
                <el-tabs
                    v-model="activeName"
                    type="border-card"
                    stretch
                    @tab-click="handleClick"
                    class="w-3/4 rounded-2xl shadow-lg shadow-gray-500 p-3 mt-4"
                >
                    <el-tab-pane label="" name="first">
                        <template #label>
                            <div class="flex items-center">
                                <i class="fa fa-key"></i>
                                <span class="font-bold ml-2">密码登录</span>
                            </div>
                        </template>
                        <div class="flex flex-col items-center justify-center">
                            <el-input
                                v-model="username"
                                class="w-240px mt-4"
                                size="large"
                                placeholder="请输入用户名"
                            >
                                <template #prefix>
                                    <el-icon><UserFilled /></el-icon>
                                </template>
                            </el-input>
                            <el-input
                                type="password"
                                v-model="password"
                                class="w-240px mt-4"
                                size="large"
                                placeholder="请输入密码..."
                            >
                                <template #prefix>
                                    <i class="fa fa-key"></i>
                                </template>
                            </el-input>
                            <el-button
                                type="primary"
                                class="mt-3 w-240px"
                                size="large"
                                @click="user_login"
                            >
                                <i class="fa fa-sign-in-alt pr-2"></i>登录
                            </el-button>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane label="" name="second">
                        <template #label>
                            <div class="flex items-center">
                                <el-icon><Iphone /></el-icon>
                                <span class="font-bold ml-2">短信验证码</span>
                            </div>
                        </template>
                        <div class="flex flex-col justify-center items-center">
                            <div class="flex items-center w-240px mt-4">
                                <el-input
                                    v-model="mobile"
                                    class="w-160px"
                                    size="large"
                                    placeholder="手机号"
                                    :readonly="sms_input"
                                >
                                    <template #prefix>
                                        <el-icon><Iphone /></el-icon>
                                    </template>
                                </el-input>
                                <el-button
                                    :disabled="sms_btn"
                                    type="primary"
                                    size="large"
                                    class="w-75px ml-4px"
                                    @click="get_code"
                                >
                                    {{ sms_btn_msg }}
                                </el-button>
                            </div>
                            <el-input
                                v-model="code"
                                style="width: 240px"
                                size="large"
                                placeholder="短信验证码"
                                class="mt-4"
                            >
                                <template #prefix>
                                    <el-icon><Grid /></el-icon>
                                </template>
                            </el-input>
                            <el-button
                                type="primary"
                                class="mt-3 w-240px"
                                size="large"
                                @click="mobile_login"
                            >
                                <i class="fa fa-sign-in-alt pr-2"></i>登录
                            </el-button>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane label="" name="third">
                        <template #label>
                            <div class="flex items-center">
                                <i class="fa fa-envelope"></i>
                                <span class="font-bold ml-2">邮箱验证码</span>
                            </div>
                        </template>
                        <div class="flex flex-col justify-center items-center">
                            <div class="flex items-center w-240px mt-4">
                                <el-input
                                    type="email"
                                    v-model="email"
                                    class="w-160px"
                                    size="large"
                                    placeholder="邮箱号"
                                    :readonly="mail_input"
                                >
                                    <template #prefix>
                                        <i class="fa fa-envelope"></i>
                                    </template>
                                </el-input>
                                <el-button
                                    type="primary"
                                    size="large"
                                    class="w-75px ml-4px"
                                    :disabled="mail_btn"
                                    @click="get_mail_code"
                                >
                                    {{ mail_btn_msg }}
                                </el-button>
                            </div>
                            <el-input
                                v-model="ecode"
                                style="width: 240px"
                                size="large"
                                placeholder="邮件验证码"
                                class="mt-4"
                            >
                                <template #prefix>
                                    <el-icon><Grid /></el-icon>
                                </template>
                            </el-input>
                            <el-button
                                type="primary"
                                class="mt-3 w-240px"
                                size="large"
                                @click="email_login"
                            >
                                <i class="fa fa-sign-in-alt pr-2"></i>登录
                            </el-button>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane label="" name="fourth">
                        <template #label>
                            <div class="flex items-center">
                                <i class="fa fa-qrcode"></i>
                                <span class="font-bold ml-2">微信扫码</span>
                            </div>
                        </template>
                        <div class="flex flex-col justify-center items-center">
                            <wxlogin
                                :appid="appId"
                                :scope="scope"
                                :redirect_uri="redirect_uri"
                                :state="state"
                                :self_redirect="self_redirect"
                                :href="style_href"
                                class='w-300px h-300px'
                            >
                            </wxlogin>
                        </div>
                    </el-tab-pane>
                </el-tabs>
                <div class="w-full flex items-center justify-center mt-4">
                    <el-link type="primary">找回密码</el-link>
                </div>
                <el-divider class="mt-6">
                    <span class="text-xs text-gray-400">成都机联云维科技有限公司 ©版权所有</span>
                </el-divider>
            </div>
        </div>
    </div>
</template>

<script setup>
    import { ref,onMounted } from 'vue'
    import wxlogin from 'vue-next-wxlogin'
    import { useRouter } from 'vue-router'
    import { getToken, setToken, removeToken } from '@/utils'
    import { wechatPlatform,addLog } from '@/api'
    import { login, verifyToken,getSMSCode,getEmailCode,verifyEmail } from '@/api/user'
    import { useUserStore } from '@/store'
    import { dayjs, ElMessage } from 'element-plus'

    const router = useRouter()
    const user_store = useUserStore()
    const activeName = ref('first')

    const appId = ref('')
    const impower_style = `
        .impowerBox qrcode {width: 200px;margin-top:10px;border: 0;}
        .impowerBox .title {display: none;}
        .status_icon {display: none;}
        .impowerBox .info {width: 200px;margin: -10px auto;display: none;}
        .impowerBox .status {text-align: center;padding: 0;}
    `
    const style_href = ref(`data:text/css;base64,${window.btoa(unescape(encodeURIComponent(impower_style)))}`)
    const self_redirect = ref('false')
	const scope = ref("snsapi_login")
	const redirect_uri = encodeURIComponent("https://api.jifuyun.cn/store/wechat_login")
	const state = ref(`${parseInt(new Date().getTime() / 1000)}`)

    onMounted(async () => {
        console.log(dayjs().format('YYYY-MM-DD HH:mm:ss'))
        const {data: res} = await wechatPlatform('open')
        if(res.error == 0) {
            appId.value = res.data.AppId
        }
        const token = getToken()
        if(token) {
            const { data: res } = await verifyToken()
            if(res.error == 0) {
                user_store.setInfo(res.data.user)
                // await addLog(0,user_store.userId,'login',dayjs().format('YYYY-MM-DD HH:mm:ss'))
                router.push('/home')
            } else {
                ElMessage.error(res.msg)
                user_store.logout()
                removeToken()
            }
        }
    })

    const handleClick = (tab, event) => {}

    const username = ref('')
    const password = ref('')
    const user_login = async () => {
        if(username.value == '' || password.value == '') {
            ElMessage.error('用户名、密码不能为空！')
            return
        }
        const {data: res} = await login({username: username.value, password: password.value})
        if(res.error == 0) {
            setToken(res.data.token)
            user_store.setInfo(res.data.user)
            ElMessage.success('登录成功')
            router.push('/home')
        } else {
            ElMessage.error(res.msg)
        }
    }

    const mobile = ref('')
    const code = ref('')
    const sms_input = ref(false)
    const sms_btn = ref(false)
    const sms_btn_msg = ref('发验证码')
    const mobile_login = async () => {
        if(mobile.value == '' || code.value == '') {
            ElMessage.error('手机号和验证码不能为空！')
            return
        }
        const {data: res} = await login({mobile: mobile.value, code: code.value,type: 'mobile'})
        if(res.error == 0) {
            setToken(res.data.token)
            user_store.setInfo(res.data.user)
            ElMessage.success('登录成功')
            router.push('/home')
        } else {
            ElMessage.error(res.msg)
        }
    }

    const get_code = async () => {
        const REG_MOBILE = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
        if(!REG_MOBILE.test(mobile.value)) {
            ElMessage.error('无效的手机号！')
            return
        }
        const {data: res} = await getSMSCode(mobile.value)
        if(res.error == 0) {
            sms_btn.value = true
            sms_input.value = true
            let counter = 300
            const td = setInterval(() => {
                sms_btn_msg.value = `${counter}秒重发`
                counter--
                if (counter <= 0) {
                    sms_btn.value = false
                    sms_input.value = false
                    sms_btn_msg.value = '发验证码'
                    clearInterval(td)
                }
            }, 1000);
        } else {
            ElMessage.error(res.msg)
            sms_btn.value = false
            sms_input.value = false
            sms_btn_msg.value = '发验证码'
            clearInterval(td)
        }
    }

    const email = ref('')
    const ecode = ref('')
    const mail_input = ref(false)
    const mail_btn = ref(false)
    const mail_btn_msg = ref('发验证码')
    const email_login = async () => {
        if(email.value == '' || ecode.value == '') {
            ElMessage.error('邮箱号和验证码不能为空！')
            return
        }
        const {data: res} = await login({email: email.value, code: ecode.value,type: 'email'})
        if(res.error == 0) {
            setToken(res.data.token)
            user_store.setInfo(res.data.user)
            ElMessage.success('登录成功')
            router.push('/home')
        } else {
            ElMessage.error(res.msg)
        }
    }

    const get_mail_code = async () => {
        const REG_MAIL = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
        if(!REG_MAIL.test(email.value)) {
            ElMessage.error('无效的邮箱号！')
            return
        }
        const {data: res} = await getEmailCode(email.value)
        if(res.error == 0) {
            mail_btn.value = true
            mail_input.value = true
            let counter = 300
            const td = setInterval(() => {
                mail_btn_msg.value = `${counter}秒重发`
                counter--
                if (counter <= 0) {
                    mail_btn.value = false
                    mail_input.value = false
                    mail_btn_msg.value = '发验证码'
                    clearInterval(td)
                }
            }, 1000);
        } else {
            ElMessage.error(res.msg)
            mail_btn.value = false
            mail_input.value = false
            mail_btn_msg.value = '发验证码'
            clearInterval(td)
        }
    }
</script>

<style lang="scss" scoped>
    @media screen and (max-width: 768px) {
        .box {
            min-width: 400px!important;
            .box-left {
                display: none!important;
            }
        }
    }

    .login-content {
        background: linear-gradient(to bottom, rgba(255, 255, 255, 0.75), rgba(255, 255, 255, 0.0)), url('../assets/back.jpg') no-repeat;
        // width: 100%;
        // height: 100%;
        overflow: hidden;
        background-size: cover;
        // display: flex;
        // justify-content: center;
        // align-items: center;
        .box {
            background-color: #f5f5f5;
            border-radius: 40px;
            box-shadow: 0 12px 12px 8px rgba(0, 0, 0, 0.5);
            display: grid;
            align-items: center;
            grid-template-columns: repeat(2,1fr);
            .box-left {
                border-radius: 40px 0 0 40px;
                background: url('../assets/extractor.jpg') no-repeat;
                width: 100%;
                height: 100%;
                overflow: hidden;
                background-size: cover;
            }
            .box-right {
                    :deep(.el-divider__text) {
                        background-color: #f5f5f5 !important;
                    }
            }
        }
    }
</style>