<template>
	<el-dialog v-model="currentVisible" :title="currentMode === AddMode.ADD_MODE ? '新增用户' : '编辑用户'" width="610" center align-center
		@close="handleClose" draggable>
		<div v-if="currentMode === AddMode.ADD_MODE">
			<el-form  :rules="firstFormRules" ref="firstRuleFormRef" :model="firstForm">
				<el-form-item label="用户账号:" prop="userAccount">
					<el-input v-model="firstForm.userAccount" />
				</el-form-item>
				<el-form-item label="用户名称:" prop="userName">
					<el-input v-model="firstForm.userName" />
				</el-form-item>
				<el-form-item label="用户状态:">
					<el-select v-model="userStatusValue" placeholder="请选择状态" style="width: 100%;">
						<el-option v-for="item in userStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
					</el-select>
				</el-form-item>
				<el-form-item label="用户密码:" prop="userPassword">
					<el-input v-model="firstForm.userPassword" />
				</el-form-item>
				<el-form-item label="用户角色:">
					<el-select v-model="userRoleValue" placeholder="请选择角色" style="width: 100%;">
						<el-option v-for="item in userRoleOptions" :key="item.value" :label="item.label" :value="item.value" />
					</el-select>
				</el-form-item>
			</el-form>
		</div>
		<div v-if="currentMode === AddMode.UPDATE_MODE">
			<el-form :inline="true" :rules="secondFormRules" ref="secondRuleFormRef" :model="secondForm">
				<el-form-item label="用户名称:" prop="userName">
					<el-input v-model="secondForm.userName" />
				</el-form-item>
				<el-form-item label="用户角色:">
					<el-select v-model="userRoleValue" placeholder="请选择角色" style="width: 180px;">
						<el-option v-for="item in userRoleOptions" :key="item.value" :label="item.label" :value="item.value" />
					</el-select>
				</el-form-item>
			</el-form>
			<div class="m-t-4" />
			<el-form :inline="true" :rules="editPasswordRules" ref="editPasswordFormRef" :model="editPasswordForm">
				<el-form-item label="用户状态:">
					<el-select v-model="userStatusValue" placeholder="请选择状态" style="width: 180px;">
						<el-option v-for="item in userStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
					</el-select>
				</el-form-item>
				<el-form-item label="用户密码:" prop="userPassword">
					<el-input v-model="editPasswordForm.userPassword" placeholder="不修改请留空" />
				</el-form-item>
			</el-form>
		</div>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="handleClose">取消</el-button>
				<el-button type="primary" @click="handleConfirm">
					确定
				</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import { defineProps, defineEmits } from 'vue';
import { addUser, updateUser } from '@/api/user.ts'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus';
import { AddMode } from './enum';

interface addDialogPropType {
	dialogVisible: boolean,
	mode: AddMode,
	nickName: string,
	userName: string,
	id: number,
	userPassword: string,
	userRole: number,
	userStatus: boolean
}
const props = defineProps<addDialogPropType>()

// 定义表单数据结构（与rules对应）
const firstForm = ref({
  userAccount: '', // 用户账号
  userName: '',    // 用户名称
  userPassword: '' // 用户密码
})
const secondForm = ref({
  userName: '' // 编辑模式的用户名称
})
const editPasswordForm = ref({
  userPassword: '' // 编辑模式的密码
})

// 表单引用
const firstRuleFormRef = ref<FormInstance>()
const secondRuleFormRef = ref<FormInstance>()
const editPasswordFormRef = ref<FormInstance>()

// 新增模式验证规则
const firstFormRules = ref<FormRules>({
	userAccount: [
		{ required: true, message: '请输入用户账号', trigger: 'blur' },
		{ type: 'string', min: 1, max: 20, message: '用户账号长度1-20字符', trigger: 'blur' },
		{ pattern: /^[A-Za-z0-9]+$/, message: '只能包含英文字母或数字', trigger: 'blur' }
	],
	userName: [
		{ required: true, message: '请输入用户名称', trigger: 'blur' },
		{ type: 'string', min: 1, max: 20, message: '用户名称长度1-20字符', trigger: 'blur' },
	],
	userPassword: [
		{ required: true, message: '请输入用户密码', trigger: 'blur' },
		{ type: 'string', min: 6, max: 20, message: '密码长度6-20字符', trigger: 'blur' },
	],
})

// 编辑模式验证规则（密码可选）
const secondFormRules = ref<FormRules>({
	userName: [
		{ required: true, message: '请输入用户名称', trigger: 'blur' },
		{ type: 'string', min: 1, max: 20, message: '用户名称长度1-20字符', trigger: 'blur' },
	],
})
const editPasswordRules = ref<FormRules>({
	userPassword: [
		{ type: 'string', min: 6, max: 20, message: '密码长度6-20字符', trigger: 'blur' },
	],
})

// 状态选项（统一值类型，避免类型错误）
const userStatusValue = ref(true)
const userRoleValue = ref(1)
const userStatusOptions = [
	{ value: true, label: '启用' },
	{ value: false, label: '停用' } // 与userStatusValue类型一致（boolean）
]
const userRoleOptions = [
	{ value: false, label: '管理员' },
	{ value: true, label: '普通用户' } // 统一值类型
]


const emit = defineEmits(['update:dialogVisible', 'getUserList'])

// 组件状态
const currentVisible = ref(props.dialogVisible)
const currentMode = ref(props.mode)

// 关闭对话框
const handleClose = () => {
	firstRuleFormRef.value?.resetFields()
	secondRuleFormRef.value?.resetFields()
	editPasswordFormRef.value?.resetFields()
	currentVisible.value = false
}

// 确认操作
const handleConfirm = async () => {
	try {
		if (currentMode.value === AddMode.ADD_MODE) {
			if (!firstRuleFormRef.value) {
				return;
			}
			// 使用Promise形式的validate（不传入回调），确保await生效
			const valid = await firstRuleFormRef.value.validate();
			if (valid) {
				await addUser({
					nickname: firstForm.value.userName, 
					username: firstForm.value.userAccount,
					password: firstForm.value.userPassword,
					role: userRoleValue.value,
					status: userStatusValue.value
				});
				ElMessage.success('新增成功');
				emit('getUserList');
				currentVisible.value = false;
			}
		} else if (currentMode.value === AddMode.UPDATE_MODE) {
			// 编辑模式逻辑（略，可参考新增模式调整）
			if (!secondRuleFormRef.value) return;
			const valid = await secondRuleFormRef.value.validate();
			if (valid) {
				// 密码非空时验证密码
				if (editPasswordForm.value.userPassword) {
					if (!editPasswordFormRef.value) return;
					const pwdValid = await editPasswordFormRef.value.validate();
					if (!pwdValid) return;
				}
				await updateUser({
					id: props.id,
					nickname: secondForm.value.userName,
					role: userRoleValue.value,
					status: userStatusValue.value,
					...(editPasswordForm.value.userPassword && { password: editPasswordForm.value.userPassword })
				});
				ElMessage.success('编辑成功');
				emit('getUserList');
				currentVisible.value = false;
			}
		}
	} catch (error) {
		console.error(error);
	}
};

watch(() => props.dialogVisible, (newVal) => {
	currentVisible.value = newVal
})

watch(() => currentVisible.value, (newVal) => {
	emit('update:dialogVisible', newVal)
})

watch(() => props.mode, (newVal) => {
	currentMode.value = newVal
})

watch(
	[() => props.dialogVisible, () => props.mode, () => props.nickName, () => props.userPassword, () => props.userStatus, () => props.userRole],
	([newVisible, newMode, newNickName, newPwd, newStatus, newRole]) => {
		if (newVisible && newMode === AddMode.UPDATE_MODE) {
			secondForm.value.userName = newNickName;
			editPasswordForm.value.userPassword = newPwd || '';
			userStatusValue.value = newStatus;
			userRoleValue.value = newRole;
		}
		if (!newVisible) {
			// 清空表单
			firstForm.value = { userAccount: '', userName: '', userPassword: '' };
			secondForm.value = { userName: '' };
			editPasswordForm.value = { userPassword: '' };
		}
	},
	{ immediate: true }
);
</script>

<style>
/* 保持原有样式 */
.el-dialog {
	background: transparent;
	background-image: url("@/assets/picture/dialog1.png");
	background-size: 100% 100%;
	background-repeat: no-repeat;
	color: #ffffff;

	.el-dialog__title {
		color: #ffffff;
	}

	.el-input__inner {
		color: #ffffff;
	}

	.el-select__wrapper {
		background-color: #1d5484;
		box-shadow: 0, 0, 0, 0;
		border: none;

		.el-select__placeholder {
			color: #ffffff;
		}
	}
}

.el-form {
	.el-form-item__label {
		color: #ffffff;
	}
}
</style>
    