<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 {
    sysMenuAdd,
    sysMenuEdit,
    sysMenuDetailId,
    sysMenuQueryTree,
  } from '/@/api/sys/sysMenuApi';
  import { usePermissionStore } from '/@/store/modules/permission';

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

  const permissionStore = usePermissionStore();

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

  const { createMessage } = useMessage();
  const [registerForm, { setFieldsValue, updateSchema, resetFields, validate }] = useForm({
    labelWidth: 100,
    schemas: dataFormSchema,
    showActionButtonGroup: false,
    baseColProps: { lg: 12, md: 24 },
    actionColOptions: {
      span: 23,
    },
  });
  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 sysMenuDetailId(data.record.id);
      await setFieldsValue({
        ...resData,
        // 设置默认值
        visible: resData.visible,
        disable: resData.disable,
        keepalive: resData.keepalive ? 0 : 1,
        linkExternal: resData.linkExternal,
        frame: resData.frame,
      });
    } else {
      await setFieldsValue({
        parentId: data.record.parentId,
      });
    }

    const treeDatas = await sysMenuQueryTree({ 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();
      console.log('🚀 ~ file: FormModal.vue:76 ~ handleSubmit ~ values:', values);
      if (!values.parentId) {
        values.parentId = '0';
      }
      setModalProps({ confirmLoading: true });
      if (!unref(isUpdate)) {
        await sysMenuAdd({ ...values });
        // 重新构建路由
        await permissionStore.buildRoutesAction();
        createMessage.success('新增成功！');
      } else {
        await sysMenuEdit({ ...values, id: rowId.value });
        createMessage.success('编辑成功！');
      }
      closeModal();
      emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
