<template>
    <div class="change-password flex flex-col">
        <div class="flex-1 flex items-center justify-center">
            <div class="change-password-card bg-body rounded-md px-10 py-10 w-[480px]">
                <div class="text-center text-2xl font-medium mb-2">首次登录</div>
                <div class="text-center text-gray-500 text-sm mb-8">为了您的账号安全，请修改初始密码</div>

                <el-form ref="formRef" :model="formData" size="large" :rules="rules">
                    <el-form-item prop="password">
                        <el-input
                            v-model="formData.password"
                            type="password"
                            show-password
                            placeholder="请输入新密码"
                        >
                            <template #prepend>
                                <icon name="el-icon-Lock" size="16" />
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item prop="password_confirm">
                        <el-input
                            v-model="formData.password_confirm"
                            type="password"
                            show-password
                            placeholder="请再次输入新密码"
                            @keyup.enter="handleSubmit"
                        >
                            <template #prepend>
                                <icon name="el-icon-Lock" size="16" />
                            </template>
                        </el-input>
                    </el-form-item>
                </el-form>

                <el-button type="primary" size="large" :loading="isLock" @click="lockSubmit" class="w-full">
                    确认修改
                </el-button>
            </div>
        </div>
        <layout-footer />
    </div>
</template>

<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import { ref, shallowRef, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useLockFn } from '@/hooks/useLockFn'
import LayoutFooter from '@/layout/components/footer.vue'
import { changeFirstPassword } from '@/api/user'
import { PageEnum } from '@/enums/pageEnum'
import useUserStore from '@/stores/modules/user'
import { getToken } from '@/utils/auth'

const formRef = shallowRef<FormInstance>()
const router = useRouter()
const userStore = useUserStore()

// 检查是否已登录
onMounted(() => {
    const token = getToken()
    if (!token) {
        ElMessage.error('请先登录')
        router.push(PageEnum.LOGIN)
    }
})

const formData = reactive({
    password: '',
    password_confirm: ''
})

const validatePasswordConfirm = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请再次输入密码'))
    } else if (value !== formData.password) {
        callback(new Error('两次输入的密码不一致'))
    } else {
        callback()
    }
}

const rules = {
    password: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
    ],
    password_confirm: [
        { required: true, validator: validatePasswordConfirm, trigger: 'blur' }
    ]
}

const handleSubmit = async () => {
    await formRef.value?.validate()
    
    try {
        await changeFirstPassword({
            password: formData.password,
            password_confirm: formData.password_confirm
        })
        
        ElMessage.success('密码修改成功，请重新登录')
        
        // 更新 store 中的状态
        userStore.isPaw = 1
        
        // 清除登录信息并跳转到登录页
        await userStore.logout()
    } catch (error: any) {
        ElMessage.error(error?.msg || error?.message || '密码修改失败')
    }
}

const { isLock, lockFn: lockSubmit } = useLockFn(handleSubmit)
</script>

<style lang="scss" scoped>
.change-password {
    background-image: url('./images/login_bg.png');
    @apply min-h-screen bg-no-repeat bg-center bg-cover;
}
</style>
