<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    showFooter
    destroyOnClose
    :title="getTitle"
    width="50%"
    @ok="handleSubmit"
    @visible-change="
      () => {
        activeKey = '1';
      }
    "
  >
    <div class="custom-modal-padding-box">
      <a-tabs v-model:activeKey="activeKey">
        <a-tab-pane key="1" :tab="t('菜单信息')">
          <BasicForm @register="registerForm" />
        </a-tab-pane>
        <a-tab-pane key="2" :tab="t('按钮信息')">
          <ButtonTable
            :menuId="rowId"
            :hasMetaFormId="hasMetaFormId"
            ref="buttonTable"
            v-if="activeKey"
          />
        </a-tab-pane>
        <a-tab-pane key="3" :tab="t('表格信息')">
          <ColumnTable :menuId="rowId" ref="columnTable" v-if="activeKey" />
        </a-tab-pane>
        <a-tab-pane key="4" :tab="t('表单信息')">
          <FormTable :menuId="rowId" ref="formTable" v-if="activeKey" />
        </a-tab-pane>
      </a-tabs>
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed } from 'vue';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { BasicColumn } from '/@/components/Table';
  import { BasicModal, useModalInner } from '/@/components/Modal';

  import ButtonTable from './ButtonTable.vue';
  import ColumnTable from './ColumnTable.vue';
  import FormTable from './FormTable.vue';
  import {
    addAppMenu,
    updateAppMenu,
    getAppMenuButtonById,
    getAppMenuColumnById,
    getAppMenuFormById,
  } from '/@/api/system/menu';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { MenuButtonModel } from '/@/api/system/menuButton/model';

  import { usePermissionStore } from '/@/store/modules/permission';
  import { getDicDetailList } from '/@/api/system/dic';
  const { t } = useI18n();

  const isUpdate = ref<boolean>(false);
  const componentType = ref<number>(0);
  const hasMetaFormId = ref(false);
  export const formSchema: FormSchema[] = [
    {
      field: 'name',
      label: t('菜单名称'),
      component: 'Input',
      required: true,
    },
    {
      field: 'code',
      label: t('编码'),
      component: 'Input',
      required: true,
    },
    {
      field: 'sortCode',
      label: t('排序'),
      component: 'InputNumber',
      required: true,
    },
    {
      field: 'categoryId',
      label: t('菜单分类'),
      component: 'Select',
      componentProps: {
        fieldNames: {
          label: 'name',
          value: 'id',
        },
        getPopupContainer: () => document.body,
        allowClear: false,
      },
    },
    {
      field: 'url',
      label: t('路由地址'),
      component: 'Input',
      required: false,
    },
    {
      field: 'enabledMark',
      label: t('状态'),
      component: 'RadioButtonGroup',
      componentProps: {
        options: [
          { label: t('启用'), value: 1 },
          { label: t('禁用'), value: 0 },
        ],
      },
    },
    {
      field: 'component',
      label: t('组件路径'),
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      required: true,
      ifShow: ({ values }) => {
        return values.outLink === 0 && values.componentType === 0;
      },
    },
    {
      field: 'remark',
      label: t('备注'),
      component: 'InputTextArea',
      colProps: { lg: 24, md: 24 },
    },
  ];

  export const columns: BasicColumn[] = [
    {
      title: t('按钮名称'),
      dataIndex: 'name',
      width: 100,
      align: 'left',
    },
    {
      title: t('编码'),
      dataIndex: 'code',
      width: 100,
    },
    {
      title: t('地址'),
      dataIndex: 'url',
      width: 200,
    },
    {
      title: t('请求方式'),
      dataIndex: 'method',
      width: 180,
      format: (text: string | number) => {
        if (text === 0) return 'GET';
        else if (text === 1) return 'POST';
        else if (text === 2) return 'PUT';
        else return 'DELETE';
      },
    },
  ];

  export default defineComponent({
    name: 'MenuDrawer',
    components: {
      BasicModal,
      BasicForm,
      FormTable,
      ButtonTable,
      ColumnTable,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const permissionStore = usePermissionStore();
      const { notification } = useMessage();
      const rowId = ref('');
      const activeKey = ref('1');
      const buttonTable = ref();
      const columnTable = ref();
      const formTable = ref();
      const buttonDatas = ref<MenuButtonModel[]>([]);
      const columnDatas = ref<MenuButtonModel[]>([]);
      const formDatas = ref<MenuButtonModel[]>([]);
      const childIds = ref([]);
      const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: { lg: 12, md: 24 },
        layout: 'vertical',
        rowProps: {
          gutter: 32,
        },
      });

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        setModalProps({ confirmLoading: false, fixedHeight: true });
        isUpdate.value = !!data?.isUpdate;

        if (isUpdate.value) {
          rowId.value = data.record.id;
          childIds.value = data.childIds;
          if (data.record && data.record.meta && data.record.meta.formId) {
            hasMetaFormId.value = true;
          }
          componentType.value = data.record.componentType;
          if (data.record.outLink == 1) {
            data.record.url = data.record.component;
          }
          if (data.record.parentId) {
            data.record.systemId = null;
          }
          setFieldsValue({
            ...data.record,
          });
          getAppMenuButtonById({ menuId: data.record.id }).then((res) => {
            buttonDatas.value = res;
          });
          getAppMenuColumnById({ menuId: data.record.id }).then((res) => {
            columnDatas.value = res;
          });
          getAppMenuFormById({ menuId: data.record.id }).then((res) => {
            formDatas.value = res;
          });
        } else {
          rowId.value = '';
          componentType.value = 0;
          setFieldsValue({
            menuType: 1,
            enabledMark: 1,
            outLink: 0,
            display: 1,
            componentType: 0,
            systemId: import.meta.env.VITE_GLOB_PRODUCTION === 'true' ? '' : '1',
          });
        }

        const system = await getDicDetailList({
          itemId: '1673142942973763585',
        });
        updateSchema([
          {
            field: 'categoryId',
            componentProps: {
              options: system,
            },
          },
        ]);
      });

      const getTitle = computed(() => (!isUpdate.value ? t('新增菜单') : t('编辑菜单')));

      async function handleSubmit() {
        try {
          const values = await validate();
          if (values.outLink == 1) {
            values.component = values.url;
          }
          values.buttonList = buttonTable.value
            ? buttonTable.value.getDataSource()
            : buttonDatas.value;
          values.columnList = columnTable.value
            ? columnTable.value.getDataSource()
            : columnDatas.value;
          values.formList = formTable.value ? formTable.value.getDataSource() : formDatas.value;
          setModalProps({ confirmLoading: true });
          // TODO custom api
          if (!isUpdate.value) {
            //false 新增
            await addAppMenu(values);
            notification.success({
              message: t('提示'),
              description: t('新增菜单成功'),
            }); //提示消息
          } else {
            values.id = rowId.value;
            values.childIds = childIds.value;
            await updateAppMenu(values);
            notification.success({
              message: t('提示'),
              description: t('修改菜单成功'),
            }); //提示消息
          }
          await permissionStore.buildRoutesAction(true);
          closeModal();
          emit('success');
        } catch (error) {
          setModalProps({ confirmLoading: false });
        }
      }
      return {
        registerModal,
        registerForm,
        getTitle,
        hasMetaFormId,
        handleSubmit,
        buttonTable,
        rowId,
        columnTable,
        formTable,
        activeKey,
        t,
      };
    },
  });
</script>
<style lang="less" scoped>
  .custom-modal-padding-box {
    height: 100%;
    padding: 0 16px;
  }

  :deep(.vben-basic-table) {
    margin-top: -15px;
  }

  :deep(.vben-basic-table-header__toolbar) {
    margin-bottom: 0;
    height: auto;
  }
</style>
