<script lang="ts" setup>
import type { MenuEntity } from '@vben/types';

import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { ElMessage } from 'element-plus';

import { useVbenForm, z } from '#/adapter/form';
import {
  addMenuApi,
  editMenuApi,
  getMenuDetailApi,
  getMenuListApi,
} from '#/api/menu';

const emit = defineEmits(['finish']);
const data = ref();
const formType = ref<'create' | 'detail' | 'edit'>('create');
const parentMenus = ref<{ label: string; value: number }[]>([]);

const titleMap = {
  create: '新增菜单',
  detail: '菜单详情',
  edit: '编辑菜单',
} as const;

const getTitle = computed(() => titleMap[formType.value]);

// 获取父级菜单列表
async function fetchParentMenus() {
  try {
    const res = await getMenuListApi({
      pageindex: 1,
      rows: 1000,
      menu_type: 1, // 只获取目录类型的菜单作为父级
    });

    if (res && res.Data) {
      parentMenus.value = res.Data.map((item: MenuEntity) => ({
        label: item.menu_name,
        value: item.menu_id,
      }));
      // 添加一个根菜单选项
      parentMenus.value.unshift({ label: '根菜单', value: 0 });
    }
  } catch (error) {
    console.error('获取父级菜单失败', error);
  }
}

const [BaseForm, baseFormApi] = useVbenForm({
  showDefaultActions: false,
  // 所有表单项共用，可单独在表单内覆盖
  commonConfig: {
    labelWidth: 130,
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  wrapperClass: 'grid-cols-1 lg:grid-cols-2',
  schema: [
    {
      component: 'Input',
      fieldName: 'menu_name',
      label: '菜单名称',
      rules: z.string().min(1, '请输入菜单名称'),
      componentProps: {
        placeholder: '请输入菜单名称',
      },
    },
    {
      component: 'Select',
      fieldName: 'menu_type',
      label: '菜单类型',
      rules: z.number().min(1, '请选择菜单类型'),
      componentProps: {
        placeholder: '请选择菜单类型',
        options: [
          { label: '目录', value: 1 },
          { label: '菜单', value: 2 },
          { label: '按钮', value: 3 },
          { label: 'API接口', value: 4 },
        ],
      },
    },
    // {
    //   component: 'Input',
    //   fieldName: 'menu_sort',
    //   label: '菜单分类',
    //   componentProps: {
    //     placeholder: '请输入菜单分类',
    //   },
    // },
    {
      component: 'Input',
      fieldName: 'menu_key',
      label: '菜单标识',
      componentProps: {
        placeholder: '请输入菜单标识',
      },
    },
    {
      component: 'Select',
      fieldName: 'parent_id',
      label: '父级菜单',
      defaultValue: 0,
      componentProps: {
        placeholder: '请选择父级菜单',
        options: parentMenus,
      },
    },
    {
      component: 'InputNumber',
      fieldName: 'order_num',
      label: '显示顺序',
      defaultValue: 0,
      componentProps: {
        placeholder: '请输入显示顺序',
        min: 0,
      },
    },
    {
      component: 'Input',
      fieldName: 'path',
      label: '路径',
      componentProps: {
        placeholder: '请输入路径',
      },
    },
    {
      component: 'Input',
      fieldName: 'component',
      label: '组件',
      componentProps: {
        placeholder: '请输入组件',
      },
    },
    {
      component: 'Input',
      fieldName: 'icon',
      label: '图标',
      componentProps: {
        placeholder: '请输入图标',
      },
    },
    {
      component: 'Input',
      fieldName: 'perms',
      label: '权限标识',
      componentProps: {
        placeholder: '请输入权限标识',
      },
    },
    {
      component: 'Switch',
      fieldName: 'visible',
      label: '菜单状态',
      defaultValue: 0,
      componentProps: {
        activeValue: 0,
        inactiveValue: 1,
        activeText: '显示',
        inactiveText: '隐藏',
      },
    },
    {
      component: 'Switch',
      fieldName: 'no_cache',
      label: '是否缓存',
      defaultValue: 0,
      componentProps: {
        activeValue: 1,
        inactiveValue: 0,
        activeText: '是',
        inactiveText: '否',
      },
    },
    {
      component: 'Input',
      fieldName: 'remark',
      label: '备注',
      componentProps: {
        type: 'textarea',
        placeholder: '请输入备注',
        rows: 3,
      },
      // @ts-ignore wrapperProps属性在运行时有效，但类型定义中缺失
      wrapperProps: {
        class: 'col-span-2',
      },
    },
  ],
});

const [Modal, modalApi] = useVbenModal({
  class: 'w-8/12',
  onCancel() {
    modalApi.close();
  },
  async onConfirm() {
    // 校验输入的数据
    const formValues = await baseFormApi.getValues();
    const validate = await baseFormApi.validate();
    if (!validate.valid) {
      return;
    }

    try {
      const apiMap = {
        create: () => addMenuApi(formValues as unknown as MenuEntity),
        edit: () =>
          editMenuApi({
            ...formValues,
            'menu_id.value': data.value.row.menu_id,
          } as unknown as MenuEntity),
      };

      if (formType.value === 'detail') {
        modalApi.close();
        return;
      }

      await apiMap[formType.value]();
      ElMessage.success('操作成功');
      emit('finish');
      modalApi.close();
    } catch {}
  },
  async onOpenChange(isOpen) {
    if (isOpen) {
      data.value = modalApi.getData();

      formType.value = data.value.formType;

      // 获取父级菜单列表
      await fetchParentMenus();

      baseFormApi.setState({
        commonConfig: { disabled: formType.value === 'detail' },
      });

      if (data.value.formType === 'create') {
        // 新增时设置默认值
        baseFormApi.setFieldValue('visible', 0);
        baseFormApi.setFieldValue('no_cache', 0);
        baseFormApi.setFieldValue('parent_id', 0);
        baseFormApi.setFieldValue('order_num', 0);
        baseFormApi.setFieldValue('menu_type', 1);
        return;
      }

      try {
        modalApi.setState({ loading: true });
        const detailData = await getMenuDetailApi({
          menu_id: data.value.row.menu_id,
        });

        baseFormApi.setValues(detailData);
      } catch {
        // console.log(error);
      }

      modalApi.setState({ loading: false });
    }
  },
});
</script>

<template>
  <Modal :title="getTitle">
    <BaseForm />
  </Modal>
</template>
