<template>
  <BasicModal v-bind="$attrs" @register="registerModal" @ok="handleSubmit">
    <div class="pt-4 h-100">
      <BasicForm @register="registerForm" />
    </div>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { FormSchema } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { addPageDesignMenu } from '/@/api/system/pagedesign';
  import { getSubSystemList } from '/@/api/system/subSystem';
  import { getMenuTree } from '/@/api/system/menu';
  const { t } = useI18n();
  const accountFormSchema: FormSchema[] = [
    {
      field: 'code',
      label: t('菜单编码'),
      component: 'Input',
      required: true,
    },
    {
      field: 'title',
      label: t('菜单名称'),
      component: 'Input',
      required: true,
    },
    {
      field: 'parentId',
      label: t('上级菜单'),
      component: 'MenuSelect',
    },
    {
      field: 'systemId',
      label: t('所属系统'),
      component: 'Select',
      componentProps: {
        fieldNames: {
          label: 'name',
          value: 'id',
        },
        getPopupContainer: () => document.body,
        allowClear: false,
      },
      dynamicDisabled: ({ values }) => {
        return values.parentId ? true : false;
      },
    },
    {
      field: 'icon',
      label: t('菜单图标'),
      component: 'IconPicker',
    },
    {
      field: 'sortCode',
      label: t('排序'),
      component: 'InputNumber',
      required: true,
    },
    {
      field: 'remark',
      label: t('备注'),
      component: 'InputTextArea',
      colProps: { lg: 24, md: 24 },
      componentProps: {
        placeholder: t('请填写备注'),
        autoSize: { minRows: 4, maxRows: 15 },
      },
    },
  ];

  const emit = defineEmits(['success', 'register']);
  const formId = ref();
  const { notification } = useMessage();
  const systemId = ref('1');
  const [registerForm, { resetFields, validate, updateSchema }] = useForm({
    schemas: accountFormSchema,
    showActionButtonGroup: false,
    layout: 'vertical',
    rowProps: { gutter: 32 },
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    formId.value = data.id;
    const treeData = await getMenuTree();
    const system = await getSubSystemList();
    const onlineSystem = system.filter((x) => x.id !== '1'); //线上环境使用
    updateSchema([
      {
        field: 'parentId',
        componentProps: ({ formModel }) => {
          return {
            getPopupContainer: () => document.body,
            onChange: (v) => {
              findParentSystem(treeData, treeData, v);
              formModel.systemId = systemId.value;
            },
          };
        },
      },
      {
        field: 'systemId',
        componentProps: {
          options: import.meta.env.VITE_GLOB_PRODUCTION === 'true' ? onlineSystem : system,
        },
      },
    ]);
    setModalProps({
      confirmLoading: false,
      draggable: false,
      title: data.title,
      destroyOnClose: true,
      width: 800,
    });
  });

  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      values.id = formId.value;
      await addPageDesignMenu(values);
      notification.success({
        message: t('发布菜单'),
        description: t('成功'),
      }); //提示消息

      closeModal();
      emit('success');
    } catch (error) {
      setModalProps({ confirmLoading: false });
    }
  }
  function findParentSystem(treeData, tempTree, id) {
    for (let i = 0; i < treeData.length; i++) {
      let o = treeData[i];

      if (o.id == id) {
        systemId.value = o.systemId;
        if (o.parentId) {
          findParentSystem(tempTree, tempTree, o.parentId);
        } else {
          break;
        }
      } else if (o.children?.length > 0) {
        findParentSystem(o.children, tempTree, id);
      }
    }
  }
</script>
