<template>
  <a-modal
    v-model:visible="props.visible"
    :title="props.deptId ? '编辑' : '新增'"
    width="600px"
    @cancel="dialogClose"
  >
    <a-form ref="formRef" :model="formData" :label-col="{ style: { width: '80px' } }">
      <a-form-item label="部门类型" name="type">
        <a-select
          v-model:value="formData.type"
          class="flex-1"
          allow-clear
          placeholder="请选择部门类型"
        >
          <a-select-option
            v-for="(item, index) in optionData.deptTypeList"
            :key="index"
            :value="item.id"
            >{{ item.name }}</a-select-option
          >
        </a-select>
      </a-form-item>
      <a-form-item
        label="父级部门"
        name="parentId"
        :rules="{ required: true, message: '请选择父级部门', trigger: 'change' }"
      >
        <a-tree-select
          class="flex-1"
          v-model:value="formData.parentId"
          :tree-data="deptOptions"
          allow-clear
          treeDefaultExpandAll
          :fieldNames="{ children: 'children', label: 'name', value: 'id' }"
          placeholder="请选择父级菜单"
        />
      </a-form-item>
      <a-form-item
        label="部门名称"
        name="name"
        :rules="{ required: true, message: '请输入部门名称', trigger: 'blur' }"
      >
        <a-input v-model:value="formData.name" placeholder="请输入部门名称" allow-clear />
      </a-form-item>
      <a-form-item label="部门排序" name="sort" class="flex-1">
        <div>
          <a-input-number v-model:value="formData.sort" :max="9999" />
          <div class="form-tips">数值越小越排前</div>
        </div>
      </a-form-item>
      <a-form-item label="部门备注" name="note">
        <a-textarea
          class="flex-1"
          v-model:value="formData.note"
          placeholder="请输入部门名称"
          allow-clear
        />
      </a-form-item>
    </a-form>
    <template #footer>
      <span class="dialog-footer">
        <a-button @click="dialogClose">取消</a-button>
        <a-button :loading="subLoading" type="primary" @click="submit"> 确定 </a-button>
      </span>
    </template>
  </a-modal>
</template>
<script lang="ts" setup>
  import type { FormInstance } from 'ant-design-vue';
  import { deptAdd, deptUpdate, getDeptList, getDeptDetail } from '@/api/system/dept';
  import { onMounted, reactive, ref, shallowRef } from 'vue';
  import { buildTree } from '@/utils/auth';
  import { message } from 'ant-design-vue';
  import { useLockFn } from '@/utils/useLockFn';

  /**
   * 定义接收的参数
   */
  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 expandedKeys = ref([]);
  const emit = defineEmits(['success', 'update:visible']);
  const formRef = shallowRef<FormInstance>();

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

  /**
   * 关闭窗体
   */
  const dialogClose = () => {
    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 () => {
    await formRef.value?.validate();
    props.deptId ? await deptUpdate(formData) : await deptAdd(formData);
    message.success('操作成功');
    emit('update:visible', false);
    emit('success');
  };

  const { isLock: subLoading, lockFn: submit } = useLockFn(handleSubmit);

  /**
   * 设置表单数据
   */
  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;
    }
  });
</script>
