<template>
  <BasicModal
    v-bind="$attrs"
    destroyOnClose
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
    width="900px"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { dataFormSchema } from './data';

  import { sysOrgAdd, sysOrgEdit, sysOrgDetailOrgId, sysOrgQueryTree } from '/@/api/sys/sysOrgApi';

  const emit = defineEmits(['success', 'register']);

  const getTitle = computed(() => (!unref(isUpdate) ? '新增部门' : '编辑部门'));
  const isUpdate = ref(false);
  const rowId = ref();

  const { createMessage } = useMessage();
  const [registerForm, { setFieldsValue, resetFields, validate, updateSchema }] = useForm({
    labelWidth: 100,
    schemas: dataFormSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
    baseColProps: { lg: 12, md: 24 },
  });
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async data => {
    await resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      rowId.value = data.record.id;
      const resData = await sysOrgDetailOrgId(data.record.id);
      resData.disable = resData.disable ? '1' : '0';

      await setFieldsValue({
        ...resData,
      });
    } else {
      await setFieldsValue({
        parentId: data.record.parentId,
      });
    }
    const treeDatas = await sysOrgQueryTree({ excludeNodeIds: [data.record.id] });
    treeDatas.forEach(async item => {
      findItem(item, data.record.id);
    });
    const treeData = [
      {
        id: '0',
        name: '根目录',
        children: treeDatas,
      },
    ];
    await updateSchema([
      {
        field: 'parentId',
        componentProps: { treeData },
      },
    ]);
  });

  // 设置自身及自身下级不可选择
  async function setDisable(item) {
    item.disabled = true;
    if (item.children?.length) {
      item.children.map(async ele => {
        await setDisable(ele);
      });
    }
  }
  // 寻找自身菜单
  async function findItem(item, recordId) {
    if (item.id == recordId) {
      await setDisable(item);
    } else {
      if (item.children?.length) {
        item.children.map(async ele => {
          await findItem(ele, recordId);
        });
      }
    }
  }
  // 提交按钮事件
  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      values.parentId = values.parentId || '0';
      !unref(isUpdate)
        ? await sysOrgAdd({ ...values })
        : await sysOrgEdit({ ...values, id: rowId.value });
      !unref(isUpdate) ? createMessage.success('新增成功！') : createMessage.success('编辑成功！');
      closeModal();
      emit('success', { isUpdate: unref(isUpdate), values: { ...values, orgId: rowId.value } });
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
