import {
  MyBetaModalFormProps,
  MyButtons,
  MyFormItems,
  MyModalFormProps,
  rulesHelper,
} from '@/common';
import { SysSelects } from '@/components/SysSelects';
import { Apis } from '@/gen/Apis';
import { SysPermissionsTypeEnum } from '@/gen/Enums';
import { BetaSchemaForm } from '@ant-design/pro-components';
import { ButtonProps, Form, message } from 'antd';

export default function Create(
  props: {
    buttonProps?: ButtonProps;
    guardName: string;
  } & MyBetaModalFormProps,
) {
  const [form] = Form.useForm();
  return (
    <BetaSchemaForm<ApiTypes.Permission.SysPermissions.Store>
      {...MyModalFormProps.props}
      title={`添加${props.title}`}
      form={form}
      wrapperCol={{ span: 24 }}
      width="600px"
      trigger={
        <MyButtons.Create title={`添加${props.title}`} {...props.buttonProps} />
      }
      onFinish={async (values) => {
        return Apis.Permission.SysPermissions.Store({
          ...values,
          guard_name: props.guardName,
        })
          .then(() => {
            props.reload?.();
            message.success(props.title + '成功');
            return true;
          })
          .catch(() => false);
      }}
      onOpenChange={(open: boolean) => {
        if (open && props.item) {
          form.setFieldsValue({
            parent_id: props.item.id || undefined,
            icon: undefined,
          });
        }
      }}
      columns={[
        SysSelects.SysPermissionsTree({ guard_name: props.guardName }),
        {
          key: 'name',
          title: '标题',
          required: true,
          formItemProps: { ...rulesHelper.text },
        },
        {
          key: 'key',
          title: '标识(en)',
        },
        MyFormItems.IconSelect(),
        MyFormItems.EnumRadio({
          key: 'type',
          title: '类型',
          valueEnum: SysPermissionsTypeEnum,
          required: true,
        }),
        { key: 'path', title: '路由' },
        SysSelects.Api(),
      ]}
    />
  );
}
