<template>
	<el-dialog :close-on-click-modal="false" :title="$t('merchantUser.changePwdTitle')" draggable v-model="visible" width="500px">
		<el-form :model="form" :rules="dataRules" label-width="100px" ref="dataFormRef" v-loading="loading">
			<el-form-item :label="$t('merchantUser.newPassword')" prop="newPwd">
				<el-input :placeholder="$t('merchantUser.inputNewPasswordTip')" type="password" v-model="form.newPwd" show-password />
			</el-form-item>

			<el-form-item :label="$t('merchantUser.confirmPassword')" prop="confirmPwd">
				<el-input :placeholder="$t('merchantUser.inputConfirmPasswordTip')" type="password" v-model="form.confirmPwd" show-password />
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="visible = false">{{ $t('common.cancelButtonText') }}</el-button>
				<el-button @click="onSubmit" type="primary" :disabled="loading">{{ $t('common.confirmButtonText') }}</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script lang="ts" name="ChangePwdDialog" setup>
import { useMessage } from '/@/hooks/message';
import { changePwd } from '/@/api/merchant/merchantUser';
import { useI18n } from 'vue-i18n';

const emit = defineEmits(['refresh']);

const { t } = useI18n();
// 定义变量内容
const dataFormRef = ref();
const visible = ref(false);
const loading = ref(false);
const userId = ref('');

// 提交表单数据
const form = reactive({
	newPwd: '',
	confirmPwd: '',
});

// 自定义校验规则
const validateConfirmPwd = (rule: any, value: any, callback: any) => {
	if (value === '') {
		callback(new Error(t('merchantUser.confirmPasswordRequired')));
	} else if (value !== form.newPwd) {
		callback(new Error(t('merchantUser.passwordNotMatch')));
	} else {
		callback();
	}
};

// 定义校验规则
const dataRules = ref({
	newPwd: [
		{ required: true, message: t('merchantUser.newPasswordRequired'), trigger: 'blur' },
		{ min: 6, max: 20, message: t('merchantUser.passwordLengthTip'), trigger: 'blur' },
	],
	confirmPwd: [{ required: true, validator: validateConfirmPwd, trigger: 'blur' }],
});

// 打开弹窗
const openDialog = (id: string) => {
	visible.value = true;
	userId.value = id;

	// 重置表单数据
	nextTick(() => {
		dataFormRef.value?.resetFields();
	});
};

// 提交
const onSubmit = async () => {
	const valid = await dataFormRef.value.validate().catch(() => {});
	if (!valid) return false;

	try {
		loading.value = true;
		await changePwd(userId.value, {
			newPwd: form.newPwd,
		});
		useMessage().success(t('merchantUser.changePwdSuccess'));
		visible.value = false;
		emit('refresh');
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};

// 暴露变量
defineExpose({
	openDialog,
});
</script>
