<script lang="ts" setup>
import { post, put, get } from "@/common/http/request";
import BaseMultiSelect from "@/components/base/base-multi-select/BaseMultiSelect.vue";

const props = defineProps({
  title: {
    type: String,
    default: "",
  },
});

const visible = defineModel<boolean>("visible", { required: true });
const isEdit = defineModel<boolean>("isEdit", { required: true });
const formData = defineModel<Record<string, any>>("formData", { required: true });
const emit = defineEmits(["success"]);

const roleUrl = "/api/sys/sysrole/getSysRoleSelectList";
const userTypeOptions = [
  { value: 0, label: "普通用户" },
  { value: 5, label: "系统管理员" },
];

const formRef = ref();
const loading = ref(false);
const passwordModified = ref(false);

const rules = {
  loginName: [{ required: true, message: "请输入登录账号", trigger: "blur" }],
  userName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  passWord: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度不能少于6位", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请确认密码", trigger: "blur" },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value !== formData.value.passWord) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  userType: [{ required: true, message: "请选择用户类型", trigger: "change" }],
  roleIds: [{ required: true, message: "请选择角色", trigger: "change", type: "array" }],
};

const handlePasswordChange = () => {
  if (isEdit.value) {
    passwordModified.value = true;
  }
};

const handleSubmit = async () => {
  const valid = await formRef.value?.validate().catch(() => false);
  if (!valid) return;

  loading.value = true;
  try {
    const submitData = { ...formData.value };

    // 编辑模式下，如果密码未修改，则不提交密码字段
    if (isEdit.value && !passwordModified.value) {
      delete submitData.passWord;
      delete submitData.confirmPassword;
    }

    if (isEdit.value) {
      await put(`/api/sys/sysuser/${submitData.id}`, submitData);
    } else {
      await post("/api/sys/sysuser", submitData);
    }

    ElMessage.success(isEdit.value ? "编辑成功" : "新建成功");
    visible.value = false;
    emit("success");
  } finally {
    loading.value = false;
  }
};

const handleClose = () => {
  formRef.value?.resetFields();
  passwordModified.value = false;
};

const handleOpen = () => {
  if (!isEdit.value) {
    // 新建时重置密码相关状态
    passwordModified.value = false;
  }
};
</script>
<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
    @open="handleOpen"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-position="right" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="登录账号" prop="loginName">
            <el-input v-model="formData.loginName" placeholder="请输入登录账号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名" prop="userName">
            <el-input v-model="formData.userName" placeholder="请输入姓名" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="密码" prop="passWord">
            <el-input
              v-model="formData.passWord"
              type="password"
              placeholder="请输入密码"
              show-password
              @input="handlePasswordChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
              v-model="formData.confirmPassword"
              type="password"
              placeholder="请确认密码"
              show-password
              @input="handlePasswordChange"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户类型" prop="userType">
            <el-select v-model="formData.userType" placeholder="请选择用户类型" style="width: 100%">
              <el-option v-for="item in userTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="角色" prop="roleIds">
            <BaseMultiSelect
              v-model="formData.roleIds"
              :url="roleUrl"
              name="roleId"
              label="roleName"
              placeholder="请选择角色"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>
