<script setup lang="ts">
import { reactive, ref } from "vue";
import { addDepartment, modifyDepartment, getDepartmentDetail } from "@/api/department";
import { ElMessage } from "element-plus";

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

const formRef = ref();
const dialogVisible = ref(false);
const dialogType = ref<"add" | "edit">("add");
const loading = ref(false);

const state = reactive({
  ruleForm: {
    id: null as number | null,
    parentId: null as number | null,
    parentName: "",
    name: "",
    fullName: "",
    weight: 0,
    status: 1,
    level: 1,
    leaderIdList: [] as number[],
    disLeaderIdList: [] as number[],
    remark: ""
  },
  rules: {
    name: [{ required: true, message: "请输入部门名称", trigger: "blur" }]
  }
});

const resetForm = () => {
  state.ruleForm = {
    id: null,
    parentId: null,
    parentName: "",
    name: "",
    fullName: "",
    weight: 0,
    status: 1,
    level: 1,
    leaderIdList: [],
    disLeaderIdList: [],
    remark: ""
  };
  formRef.value?.resetFields();
};

const getTitle = () => {
  return dialogType.value === "add" ? "新增部门" : "编辑部门";
};

const open = async (type: "add" | "edit", row?: any) => {
  dialogType.value = type;
  resetForm();
  if (type === "edit" && row) {
    loading.value = true;
    try {
      const res = await getDepartmentDetail(row.id);
      Object.assign(state.ruleForm, res);
    } catch (e) {
      ElMessage.error("获取详情失败");
    } finally {
      loading.value = false;
    }
  }
  dialogVisible.value = true;
};

const handleClose = () => {
  dialogVisible.value = false;
  resetForm();
};

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

  loading.value = true;
  try {
    if (dialogType.value === "add") {
      await addDepartment(state.ruleForm);
    } else {
      await modifyDepartment(state.ruleForm);
    }
    ElMessage.success("操作成功");
    handleClose();
    emit("refresh");
  } catch (e) {
    ElMessage.error("操作失败");
  } finally {
    loading.value = false;
  }
};

defineExpose({ open });
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="getTitle()"
    width="650px"
    destroy-on-close
    :close-on-click-modal="false"
  >
    <el-form ref="formRef" :model="state.ruleForm" :rules="state.rules" label-width="120px" :disabled="loading">
      <el-form-item label="上级部门" prop="parentId" v-if="state.ruleForm.level !== 1">
        <el-input v-model="state.ruleForm.parentName" placeholder="上级部门" readonly />
      </el-form-item>
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="state.ruleForm.name" placeholder="请输入部门名称" clearable />
      </el-form-item>
      <el-form-item label="部门全称" prop="fullName">
        <el-input v-model="state.ruleForm.fullName" placeholder="请输入部门全称" clearable />
      </el-form-item>
      <el-form-item label="排序" prop="weight">
        <el-input-number v-model="state.ruleForm.weight" :min="0" :max="999" />
      </el-form-item>
      <el-form-item label="描述" prop="remark">
        <el-input
          v-model="state.ruleForm.remark"
          placeholder="请输入部门描述"
          maxlength="150"
          show-word-limit
          type="textarea"
          :rows="3"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button :loading="loading" type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>
