<template>
  <el-dialog
    v-model="currentVisible"
    :title="currentMode === AddMode.ADD_MODE ? '新增用户' : '编辑用户'"
    width="480"
    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" label-width="100px">
          <el-input v-model="firstForm.userAccount" style="width: 300px" />
        </el-form-item>
        <el-form-item label="用户名称:" prop="userName" label-width="100px">
          <el-input v-model="firstForm.userName" style="width: 300px" />
        </el-form-item>
        <el-form-item label="用户状态:" label-width="100px">
          <el-select v-model="userStatusValue" placeholder="请选择状态" style="width: 300px">
            <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" label-width="100px">
          <el-input v-model="firstForm.userPassword" style="width: 300px" />
        </el-form-item>
        <el-form-item label="用户角色:" label-width="100px">
          <el-select v-model="userRoleValue" placeholder="请选择角色" style="width: 300px">
            <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" label-width="100px">
          <el-input v-model="secondForm.userName" style="width: 300px" />
        </el-form-item>
        <el-form-item label="用户角色:" label-width="100px">
          <el-select v-model="userRoleValue" placeholder="请选择角色" style="width: 300px">
            <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="用户状态:" label-width="100px">
          <el-select v-model="userStatusValue" placeholder="请选择状态" style="width: 300px">
            <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" label-width="100px">
          <el-input v-model="editPasswordForm.userPassword" placeholder=" " style="width: 300px" />
        </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 { 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: 3, max: 20, message: "用户账号长度3-20字符", trigger: "blur" },
    { pattern: /^[A-Za-z0-9]+$/, message: "用户账号只能包含英文字母或数字", trigger: "blur" },
  ],
  userName: [
    { required: true, message: "请输入用户名称", trigger: "blur" },
    { type: "string", min: 2, max: 20, message: "用户名称长度2-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: "停用" },
];
const userRoleOptions = [
  { value: 1, label: "管理员" },
  { value: 0, 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;
      }
      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-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>
