<template>
    <el-container class="full-page">
        <div class="content">
            <el-main>
                <el-form
                    class="pwdForm"
                    ref="pwdFormRef"
                    :model="pwdForm"
                    :rules="pwdRules"
                    label-width="200px"
                    label-position="top"
                >
                    <el-form-item label="旧密码" prop="old">
                        <el-input
                            type="password"
                            show-password
                            placeholder="请输入旧密码"
                            v-model="pwdForm.old"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="新密码" prop="new">
                        <el-input
                            type="password"
                            show-password
                            placeholder="请输入新密码"
                            v-model="pwdForm.new"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="重复新密码" prop="newRepeat" label-width="120">
                        <el-input
                            type="password"
                            show-password
                            placeholder="请再次输入新密码"
                            v-model="pwdForm.newRepeat"
                        ></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="submitForm()" :disabled="confirm">
                            保 存
                        </el-button>
                        <el-button @click="back()">取 消</el-button>
                    </el-form-item>
                </el-form>
            </el-main>
        </div>
    </el-container>
</template>

<script lang="ts" setup name="ResetPwd">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { updatePassword, getDefaultPwdStrategy } from '@/api/system/user'
import type { FormInstance, FormRules } from 'element-plus'

interface PwdStrategy {
    enable: boolean | number
    pwdRule?: number
    pwdLength?: number
}

const pwdStrategy = ref<PwdStrategy>({
    enable: false
})

onMounted(() => {
    getDefaultPwdStrategy().then((res) => {
        if (res) {
            let { enable, ...rest } = res

            pwdStrategy.value = {
                enable: enable === 1,
                ...rest
            }
        }
    })
})

const pwdForm = reactive({
    // 表单数据
    old: '',
    new: '',
    newRepeat: ''
})
const validateold = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入旧密码'))
    } else {
        callback()
    }
}

const validateNew = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入新密码'))
    }
    let re
    let config = pwdStrategy.value
    if (config.enable) {
        let pwdRule = config.pwdRule
        let pwdLength = config.pwdLength
        if (pwdRule) {
            if (value.length < pwdLength) {
                callback(new Error('新密码长度至少为' + pwdLength))
            }
            if (pwdRule === 1) {
                callback()
            } else if (pwdRule === 2) {
                re = new RegExp('(?=.*[0-9])(?=.*[a-zA-Z])')
                if (!re.test(value)) {
                    callback(new Error('新密码必须包含数字、字母'))
                } else {
                    callback()
                }
            } else if (pwdRule === 3) {
                re = new RegExp('(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9])')
                if (!re.test(value)) {
                    callback(new Error('新密码必须包含数字、字母、特殊字符'))
                } else {
                    callback()
                }
            } else if (pwdRule === 4) {
                re = new RegExp('(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[^a-zA-Z0-9])')
                if (!re.test(value)) {
                    callback(new Error('新密码必须包含数字、大小写字母、特殊字符'))
                } else {
                    callback()
                }
            } else {
                callback()
            }
        }
    } else {
        if (value.length < 6) {
            callback(new Error('密码长度至少6位'))
        } else {
            callback()
        }
    }
}

const validateNewReapeat = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入新密码'))
    } else if (value !== pwdForm.new) {
        callback(new Error('两次输入的密码不一致'))
    } else {
        callback()
    }
}
const pwdRules: FormRules = {
    old: [{ validator: validateold, trigger: 'blur' }],
    new: [{ validator: validateNew, trigger: 'blur' }],
    newRepeat: [{ validator: validateNewReapeat, trigger: 'blur' }]
}

const pwdFormRef = ref<FormInstance>()
const confirm = ref(false)
const router = useRouter()

const submitForm = () => {
    if (!pwdFormRef.value) return
    pwdFormRef.value.validate(async (valid, fields) => {
        if (!valid) {
            ElMessage.warning(
                `有${Object.keys(fields || {}).length}个字段未通过校验，请正确填写表单内容。`
            )
        } else {
            try {
                confirm.value = true
                const result = await updatePassword(pwdForm)
                if (result) {
                    ElMessage.success('密码修改成功')
                    router.push('/login')
                }
            } catch (error) {
                ElMessage.error('密码修改失败')
            } finally {
                confirm.value = false
            }
        }
    })
}

const back = () => {
    router.back()
}
</script>

<style lang="scss" scoped>
.full-page {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
}

.content {
    width: 100%;
    height: 100%;
    background-color: var(--theme-system-module-1);
    border-radius: 12px;
}

.pwdForm {
    width: 600px;
    margin: auto;
}

.el-main .el-form {
    padding: 20px;
}
</style>
