<template>
  <el-drawer v-model="isDrawer" :size="width" :title="title" @close="handleReset" >
    <el-form
      :model="formParams"
      :rules="rules"
      ref="formRef"
      label-placement="left"
      :label-width="80"
    >
      <el-form-item label="部门名称" prop="deptName">
        <el-input placeholder="请输入部门名称" v-model="formParams.deptName" />
      </el-form-item>
      <el-form-item label="上级部门" prop="parentId">
        <el-tree-select
          :data="getTreeList"
          clearable
          check-strictly
          v-model="formParams.parentId"
          placeholder="请选择上级部门"
        />
      </el-form-item>
      <el-form-item label="排序" prop="orderNum">
        <el-input-number placeholder="请输入排序" v-model="formParams.orderNum"  class="orderNum-input"/>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-space>
        <el-button @click="handleReset">重置</el-button>
        <el-button type="primary" :loading="subLoading" @click="formSubmit">提交</el-button>
      </el-space>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
  import { ref, computed, watch, reactive } from 'vue';
  import { ElMessage } from 'element-plus';
  import type { FormInstance, FormRules } from 'element-plus'
  import type { editDeptProps } from '@/types/dept/type';
  import { updateDepartments, saveDept } from '@/api/auth/dept';
  import { replaceParams } from '@/utils/helper/treeHelper';
  import { IS_DISABLED } from '@/types/common/constants';
  import { DeptTreeItem } from '@/types/dept/type';
  
  interface Props {
    title: string;
    width: number;
    deptList: Array<DeptTreeItem>;
    dataSource: DeptTreeItem;
  }
  const emit = defineEmits(['change']);
  const props = withDefaults(defineProps<Props>(), {
    title: '添加部门',
    width: 450,
  });
  const rules = reactive<FormRules>({
    deptName: {
      required: true,
      message: '部门名称不能为空',
      trigger: 'blur',
    },
  });
  const defaultValueRef = () => ({
    id: null,
    parentId: null,
    deptName: '',
    orderNum: undefined,
  });

  const message = ElMessage;
  const formRef = ref<FormInstance>();
  const isDrawer = ref(false);
  const subLoading = ref(false);

  const getTreeList = computed(() => {
    return [
      {
        label: '顶级部门',
        value: -1,
        children: replaceParams(props.deptList || [], 'deptName', 'id'),
      },
    ];
  });

  const formParams = ref<editDeptProps>(defaultValueRef());

  function openDrawer() {
    isDrawer.value = true;
  }

  function closeDrawer() {
    isDrawer.value = false;
  }

  function formSubmit() {
    formRef.value?.validate((valid) => {
      if (!valid) {
        return message.error('请填写完整信息');
      }
      const msg = formParams.value.id ? '编辑成功' : '添加成功';
      const params = { ...formParams.value };
      if (formParams.value.id) {
        updateDepartments(params).then(() => {
          message.success(msg);
          emit('change');
          handleReset();
          closeDrawer();
        });
      } else {
        delete params.id;
        saveDept(params).then(() => {
          message.success(msg);
          emit('change');
          handleReset();
          closeDrawer();
        });
      }
    });
  }

  function handleReset() {
    formRef.value?.resetFields();
    formParams.value = Object.assign(formParams.value, defaultValueRef());
  }

  watch(
    () => props.dataSource,
    (value) => {
      if (value) {
        Object.entries(value).forEach(([key, value]) => {
          if (['id', 'parentId', 'deptName', 'orderNum'].includes(key)) {
            formParams.value[key] = value;
          }
        });
      }
    },
    {
      immediate: true,
    },
  );

  defineExpose({
    openDrawer,
    closeDrawer,
  });
</script>
<style lang="scss" scoped>
  .orderNum-input {
    width: 188px;
  }
</style>
