import { rulesHelper } from '@/common';
import { Apis } from '@/gen/Apis';
import { ProColumns, ProFormColumnsType } from '@ant-design/pro-components';

type ReturnType = ProColumns<any, 'text'> & ProFormColumnsType<any, 'text'>;
type PropsType = { required?: boolean } & ReturnType;

export const SysSelects = {
  Api(props?: PropsType): ReturnType {
    const { required = false, ...rest } = props ?? {};

    return {
      title: '后端API',
      dataIndex: 'backend_apis',
      valueType: 'treeSelect',
      hideInTable: true,
      formItemProps: { ...(required ? rulesHelper.number : {}) },
      fieldProps: {
        showSearch: true,
        allowClear: true,
        treeDefaultExpandAll: true,
        dropdownStyle: { maxHeight: 400, overflow: 'auto' },
        multiple: true,
        fieldNames: {
          label: 'value',
          value: 'value',
          children: 'children',
        },
      },
      request: async () =>
        (await Apis.Permission.SysPermissions.SelectApi()).data?.children,
      ...rest,
    };
  },
  SysPermissionsTree(props?: { guard_name: string } & PropsType): ReturnType {
    const { guard_name = 'Admin', ...rest } = props ?? {};

    return {
      key: 'parent_id',
      title: '上级菜单',
      valueType: 'treeSelect',
      request: async () => {
        return Apis.Permission.SysPermissions.Tree({
          guard_name: guard_name,
        }).then((res) => res.data);
      },
      fieldProps: {
        allowClear: true,
        autoClearSearchValue: true,
        bordered: true,
        fieldNames: {
          label: 'name',
          value: 'id',
        },
        filterTreeNode: true,
        showSearch: true,
        treeNodeFilterProp: 'title',
        treeDefaultExpandAll: true,
      },
      ...rest,
    };
  },
  SysRoles(props?: PropsType): ReturnType {
    const {
      title = '角色',
      key = 'roles_id',
      required = false,
      hideInTable = true,
      ...rest
    } = props ?? {};

    return {
      title: title,
      key: key,
      valueType: 'select',
      hideInTable: hideInTable,
      formItemProps: { ...(required ? rulesHelper.number : {}) },
      fieldProps: {
        mode: 'multiple',
        showSearch: false,
        fieldNames: {
          label: 'name',
          value: 'id',
        },
      },
      request: async () => (await Apis.Permission.SysRoles.Select()).data,
      ...rest,
    };
  },
};
