<template>
  <basicModal
    @register="modalRegister"
    ref="modalRef"
    class="basicModal basicFormModal"
    @on-ok="handleSubmit"
    @on-close="handleClose"
  >
    <template #default>
      <n-form ref="formRef" :model="formData" label-placement="left" label-width="80px">
        <n-form-item label="部门类型" path="type">
          <n-select
            v-model:value="formData.type"
            class="flex-1"
            clearable
            :options="optionData.deptTypeList"
            label-field="name"
            value-field="id"
            placeholder="请选择部门类型"
          />
        </n-form-item>
        <n-form-item
          label="父级部门"
          path="parentId"
          :rule="{ type: 'number', required: true, message: '请选择父级部门', trigger: 'change' }"
        >
          <n-tree-select
            class="flex-1"
            v-model:value="formData.parentId"
            :options="deptOptions"
            clearable
            default-expand-all
            label-field="name"
            key-field="id"
            placeholder="请选择父级菜单"
          />
        </n-form-item>
        <n-form-item
          label="部门名称"
          path="name"
          :rule="{ required: true, message: '请输入部门名称', trigger: 'blur' }"
        >
          <n-input v-model:value="formData.name" placeholder="请输入部门名称" clearable />
        </n-form-item>
        <n-form-item label="部门排序" path="sort" class="flex-1">
          <div>
            <n-input-number v-model:value="formData.sort" :max="9999" />
            <div class="form-tips">数值越小越排前</div>
          </div>
        </n-form-item>
        <n-form-item label="部门备注" path="note">
          <n-input
            type="textarea"
            class="flex-1"
            v-model:value="formData.note"
            placeholder="请输入部门名称"
            clearable
          />
        </n-form-item>
      </n-form>
    </template>
  </basicModal>
</template>
<script lang="ts" setup>
  import { deptAdd, deptUpdate, getDeptList, getDeptDetail } from '@/api/system/dept';
  import { onMounted, reactive, ref } from 'vue';
  import { buildTree } from '@/utils/auth';
  import { useMessage, useDialog } from 'naive-ui';
  import { useModal } from '@/components/Modal';

  /**
   * 定义接收的参数
   */
  const props = defineProps({
    visible: {
      type: Boolean,
      required: true,
      default: false,
    },
    deptId: {
      type: Number,
      required: true,
      default: 0,
    },
    pid: {
      type: Number,
      default: 0,
    },
  });

  /**
   * 定义选项数据
   */
  const optionData = reactive({
    deptTypeList: [
      {
        id: 1,
        name: '公司',
      },
      {
        id: 2,
        name: '子公司',
      },
      {
        id: 3,
        name: '部门',
      },
      {
        id: 4,
        name: '小组',
      },
    ],
  });

  /**
   * 定义参数变量
   */
  const message = useMessage();
  const expandedKeys = ref([]);
  const emit = defineEmits(['success', 'update:visible']);
  const formRef = ref();

  /**
   * 定义表单参数
   */
  const formData = reactive({
    id: '',
    //父级id
    parentId: 0,
    //类型
    type: 1,
    //名称
    name: '',
    //排序
    sort: 0,
    note: '',
  });

  /**
   * 定义模态
   */
  const [modalRegister, { openModal, setSubLoading }] = useModal({
    title: props.deptId ? '编辑部门' : '添加部门',
    subBtuText: '确定',
    width: 600,
  });

  /**
   * 执行关闭窗体
   */
  const handleClose = () => {
    emit('update:visible', false);
  };

  const deptOptions = ref<any[]>([]);

  /**
   * 获取部门数据
   */
  const getDept = async () => {
    const data: any = await getDeptList();
    data.map((item) => {
      expandedKeys.value.push(item.id);
    });
    const menu: any = [{ id: 0, name: '顶级', children: [] }];
    const lists = buildTree(data);
    menu[0].children.push(...lists);
    deptOptions.value = menu;
  };

  /**
   * 执行提交表单
   */
  const handleSubmit = async () => {
    formRef.value
      .validate()
      .then(async () => {
        props.deptId ? await deptUpdate(formData) : await deptAdd(formData);
        message.success('操作成功');
        setSubLoading(false);
        emit('update:visible', false);
        emit('success');
      })
      .catch((error) => {
        setSubLoading(false);
      });
  };

  /**
   * 设置表单数据
   */
  const setFormData = (data: Record<any, any>) => {
    for (const key in formData) {
      if (data[key] != null && data[key] != undefined) {
        formData[key] = data[key];
      }
    }
  };

  const getDetail = async () => {
    const data = await getDeptDetail(props.deptId);
    setFormData(data);
  };

  /**
   * 钩子函数
   */
  onMounted(() => {
    getDept();
    if (props.deptId) {
      getDetail();
    } else {
      formData.parentId = props.pid;
    }
  });

  /**
   * 定义函数
   */
  defineExpose({
    openModal,
  });
</script>
