<template>
  <BasicModal width="720px"
              v-bind="$attrs"
              @ok="handleSubmit"
              @register="registerModal"
  >
    <BasicForm @register="registerForm"/>
  </BasicModal>
</template>
<script lang="ts" setup>
  /**
   * Copyright © 2020-2022 <a href="http://www.entfrm.com/">entfrm</a> All rights reserved.
   * author entfrm开发团队-王翔
   */
  import { ref, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './menu.data';
  import { BasicModal, ModalProps, useModalInner } from '/@/components/Modal';
  import { listMenu, addMenu, editMenu, getMenu } from '/@/api/system/menu';
  import { listToTree } from '/@/utils/helper/treeHelper';

  /** https://v3.cn.vuejs.org/api/options-data.html#emits */
  const emit = defineEmits(['success', 'register']);

  const tag = ref('');

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate, clearValidate }] = useForm({
    labelWidth: 100,
    schemas: formSchema,
    showActionButtonGroup: false,
    baseColProps: { span: 24 }
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data: ModalInnerData = {}) => {
    await resetFields();
    await clearValidate();
    listMenu().then(data => {
      updateSchema({
        field: 'parentId',
        componentProps: {
          treeData: listToTree(data)
        }
      });
    });
    tag.value = data._tag;
    const menuId = data.record?.id;
    const props: ModalProps = { confirmLoading: false };
    switch (unref(tag)) {
      case 'add':
        props.title = '新增菜单';
        menuId && await setFieldsValue({ parentId: menuId });
        break;
      case 'edit':
        props.title = '编辑菜单';
        await setFieldsValue(await getMenu({ id: menuId }) || {});
        break;
    }
    setModalProps(props);
  });

  async function handleSubmit() {
    try {
      const formData = await validate();
      setModalProps({ confirmLoading: true });
      switch (unref(tag)) {
        case 'add':
          await addMenu(formData);
          break;
        case 'edit':
          await editMenu(formData);
          break;
      }
      closeModal();
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
