<template>
    <el-dialog draggable class="cn-operate-dialog" width="500px" v-model="dialogVisible" :title="title">
        <el-scrollbar>
            <el-form :inline="false" :model="form" label-width="120px" :rules="rules" ref="formRef">
                <el-form-item label="新密码:" prop="newPwd" style="margin-top: 20px">
                    <el-input v-model="form.newPwd" type="password" placeholder="请输入新密码" show-password />
                </el-form-item>
                <el-form-item label="确认密码:" prop="confirmPwd" style="margin-top: 20px">
                    <el-input v-model="form.confirmPwd" type="password" placeholder="请输入确认密码" show-password />
                </el-form-item>
            </el-form>
        </el-scrollbar>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submit">确认</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script lang="ts" setup>
import { ref, inject } from 'vue'
import { reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { updateFirstPassword } from '@/api/user-boot/user'
import { validatePwd } from '@/utils/common'
import { useAdminInfo } from '@/stores/adminInfo'
import { useRouter } from 'vue-router'

const dialogVisible = ref(false)
const title = ref('修改默认密码')
const formRef = ref()
// 注意不要和表单ref的命名冲突
const form = reactive({
    newPwd: '',
    confirmPwd: '',
    loginName: ''
})
const rules = {
    newPwd: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        {
            min: 6,
            max: 12,
            message: '长度在 6 到 12 个字符',
            trigger: 'blur'
        },
        { validator: validatePwd, trigger: 'blur' }
    ],
    confirmPwd: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        {
            min: 6,
            max: 12,
            message: '长度在 6 到 12 个字符',
            trigger: 'blur'
        },
        {
            validator: (rule: any, value: string, callback: any) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'))
                } else if (value !== form.newPwd) {
                    callback(new Error('两次输入密码不一致!'))
                } else {
                    callback()
                }
            },
            trigger: 'blur',
            required: true
        }
    ]
}

const open = (loginName: string) => {
    form.loginName = loginName
    dialogVisible.value = true
}
const submit = () => {
    formRef.value.validate(async (valid: boolean) => {
        if (valid) {
            updateFirstPassword({
                name: form.loginName,
                password: form.confirmPwd
            }).then((res: any) => {
                dialogVisible.value = false
                ElMessage.success('密码修改成功, 请重新登录')
            })
        }
    })
}

defineExpose({ open })
</script>

