<template>
    <div class="login-box" v-if="isVisible">
        <el-form :model="formData" :rules="rules" ref="formRef" label-width="120px" :hide-required-asterisk="true">
            <div class="login-container">
                <div class="login-close" @click="closeLoginForm">
                    ×
                </div>
                <h4>登录</h4>
                <div class="passwordLogin">
                    <div class="login-phone">
                        <el-form-item label="账号" prop="phoneNumber">
                            <el-input v-model="formData.phoneNumber" placeholder="请输入账号" />
                        </el-form-item>
                    </div>
                    <div class="login_password">
                        <el-form-item label="密码" prop="password">
                            <el-input type="password" v-model="formData.password" placeholder="请输入密码" />
                        </el-form-item>
                    </div>
                    <div class="pic_verifyCode">
                        <el-form-item label="验证码" prop="captchaCode">
                            <el-input type="text" v-model="formData.captchaCode" placeholder="请输入验证码" maxlength="4"/>
                            <img :src="captchaUrl" alt="验证码" @click="refreshCaptcha">
                        </el-form-item>
                    </div>
                    <el-button type="primary" @click="handleLogin">登录</el-button>
                    <p>注：未入驻的账号请开店入驻成功后再继续</p>
                </div>
            </div>
        </el-form>
    </div>
</template>

<script lang="ts" setup>
import { ref, defineProps, defineEmits, watch, onMounted, onUnmounted } from 'vue';
import { useUserStore } from '@/stores/userStore';
import { useRouter } from 'vue-router';
import { GetLogin, GetSmsCode, GetVerifyCode, GetAccountLogin } from '../../api/login';
import { ElMessage } from 'element-plus/es';

const props = defineProps({
    isVisible: {
        type: Boolean,
        default: false
    }
});
const emits = defineEmits(['close-login-form']);

const formData = ref({
    phoneNumber: '',
    password: '',
    captchaCode: ''
});

const router = useRouter();
const userStore = useUserStore();
const verify_token = ref();
const captchaUrl = ref('');
const formRef = ref<InstanceType<typeof import('element-plus/es')['ElForm']>>();

const closeLoginForm = () => {
    emits('close-login-form');
};

const refreshCaptcha = async () => {
    verify_token.value = new Date().getTime();
    const res = await GetVerifyCode({ verify_token: verify_token.value });
    if (res && res.status === 200) {
        captchaUrl.value = `https://mall.gpxscs.cn/api/admin/shop/shop-base-config/image?verify_token=${verify_token.value}`;
    } else {
        console.log("获取图形验证码失败", res);
    }
};

const initCaptcha = async () => {
    await refreshCaptcha();
};

initCaptcha();

watch(() => props.isVisible, (newValue) => {
    if (newValue) {
        refreshCaptcha();
    }
});

const rules = ref({
    phoneNumber: [
        { required: true, message: '请输入账号', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' }
    ],
    captchaCode: [
        { required: true, message: '请输入验证码', trigger: 'blur' }
    ]
});

const handleLogin = async () => {
    formRef.value?.validate(async (valid) => {
        if (valid) {
            const params = {
                user_account: formData.value.phoneNumber,
                user_password: formData.value.password,
                verify_code: formData.value.captchaCode,
                verify_token: verify_token.value
            };
            const res = await GetAccountLogin(params);
            if (res && res.data.status === 200) {
                console.log("登录成功", res);
                userStore.setToken(res.data.data.token);
                userStore.setMobilePhone(formData.value.phoneNumber);
                window.open(`https://mall.gpxscs.cn/admin/#/login?loginInfo=${JSON.parse(JSON.stringify(res.data.data))}`,'_self');
                formData.value.phoneNumber = '';
                formData.value.password = '';
                formData.value.captchaCode = '';
                console.log(res.data.data);
                closeLoginForm();
            } else if(res&&res.data.status===250&&res.data.msg=='用户名或密码错误!'){
                ElMessage.error('用户名或密码错误!');
                console.log("操作失败", res.msg);
            }else if(res&&res.data.status===250&&res.data.msg=='验证码错误'){
                ElMessage.error('验证码错误');
            }
        } else {
            ElMessage.error('请正确填写登录信息');
        }
    });
};

onMounted(() => {
    // 可以在这里添加一些初始化的逻辑
});

onUnmounted(() => {
    // 可以在这里添加一些清理的逻辑
});
</script>

<style lang="scss">
$primary-color: #007BFF;
$secondary-color: #6C757D;
$border-radius: 8px;
$box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);

.login-box {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.4);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000101;
}
.el-message {
  z-index: 1000102 !important; 
}
.login-container {
    padding: 35px;
    border-radius: $border-radius;
    box-shadow: $box-shadow;
    background-color: #fff;
    width: 400px;
    transition: box-shadow 0.3s ease;
    position: relative;

    &:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
    }

    h4 {
        color: $primary-color;
        text-align: center;
        margin-bottom: 30px;
        font-size: 24px;
    }

   .el-form-item {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    label{
        width: 100px !important;
    }
    }



   .el-input {
        width: 100%;
    }

    button {
        width: 100%;
        padding: 2px;
        background-color: #007BFF;
        color: #fff;
        border: none;
        border-radius: $border-radius;
        font-size: 20px;
        cursor: pointer;
        transition: background-color 0.3s ease;

        &:hover {
            background-color: #0056b3;
        }
    }

   .login-close {
        position: absolute;
        top: 10px;
        right: 10px;
        font-size: 20px;
        cursor: pointer;
        color: $secondary-color;

        &:hover {
            color: $primary-color;
        }
    }

   .passwordLogin {
        p {
            margin: 10px;
            color: red;
        }
    }

   .pic_verifyCode img {
        cursor: pointer;
        width: 100px;
        height: 50px;
        margin-left: 5px;
    }
    .el-input{
        flex: 1;
    }
    }
</style>