<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" />
      </el-form-item>
      <el-form-item label="状态" prop="isDisabled">
        <el-switch v-model="formParams.isDisabled" :active-value="1" :inactive-value="0" />
      </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 } from 'vue';
  import { ElMessage } from 'element-plus';
  import type { editDeptProps } from '@/types/dept/type';
  import { deptInfo, 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 = {
    deptName: {
      required: true,
      message: '部门名称不能为空',
      trigger: 'blur',
    },
  };
  const defaultValueRef = () => ({
    id: null,
    parentId: null,
    isDisabled: 1,
    deptName: '',
    orderNum: undefined,
  });

  const message = ElMessage;
  const formRef: any = ref(null);
  const isDrawer = ref(false);
  const subLoading = ref(false);

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

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

  function openDrawer(id?) {
    if (id) {
      formParams.value.id = id;
      getInfo();
      return;
    }
    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 };
      params.isDisabled = formParams.value.isDisabled ? IS_DISABLED.YES : IS_DISABLED.NO;
      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());
  }

  function getInfo() {
    deptInfo({ id: formParams.value.id }).then((res) => {
      const params = {
        id: res.id,
        parentId: res.parentId,
        isDisabled: res.isDisabled,
        deptName: res.deptName,
        orderNum: res.orderNum,
      };
      formParams.value = Object.assign(formParams.value, params);
      isDrawer.value = true;
    });
  }

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

  defineExpose({
    openDrawer,
    closeDrawer,
  });
</script>
