<!-- 会员中心-会员信息-修改密码 -->
<template>
    <app-drawer :title="passwordType === 1 ? '登录密码' : '资金密码'" :width="460" v-model:show="show" :loading="loading">
        <el-form ref="formRef" label-width="80px" :model="formData" :rules="formRules">
            <el-form-item label="登录代码">
                <span>{{ LoginCode }}</span>
            </el-form-item>
            <el-form-item label="原密码" prop="OldPwd">
                <el-input type="password" placeholder="请输入" v-model="formData.OldPwd" />
            </el-form-item>
            <el-form-item label="新密码" prop="NewPwd">
                <el-input type="password" placeholder="请输入" v-model="formData.NewPwd" />
            </el-form-item>
            <el-form-item label="确认密码" prop="checkPassword">
                <el-input type="password" placeholder="请输入" v-model="checkPassword" />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="onCancel" plain>取消</el-button>
            <el-button type="primary" @click="onSubmit">确认</el-button>
        </template>
    </app-drawer>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { usePassword } from '@/business/account'
import AppDrawer from '@pc/components/base/drawer/index.vue'
import eventBus from '@/services/bus'

const props = defineProps({
    code: String,
})

// 修改密码类型
const passwordType = (() => {
    switch (props.code) {
        case 'mine_profile_loginpassword': {
            return 1
        }
        case 'mine_profile_accountpassword': {
            return 2
        }
    }
    return 0
})()

const { loading, LoginCode, checkPassword, formData, formSubmit } = usePassword(passwordType)
const show = ref(true)
const formRef = ref<FormInstance>()

const formRules: FormRules = {
    OldPwd: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
    NewPwd: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
    checkPassword: [{
        required: true,
        trigger: 'blur',
        validator: (rule, value, callback) => {
            if (formData.NewPwd === checkPassword.value) {
                callback()
            } else {
                callback(new Error('新密码和确认密码不一致'))
            }
        }
    }],
}

const onCancel = () => {
    show.value = false
}

const onSubmit = () => {
    formRef.value?.validate((valid) => {
        if (valid) {
            formSubmit().then(() => {
                if (passwordType === 1) {
                    eventBus.$emit('LogoutNotify', '密码已重置，请重新登录。')
                } else {
                    ElMessage.success('修改成功')
                }
            }).catch((err) => {
                ElMessage.error('修改失败：' + err)
            })
        }
    })
}
</script>