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;
    item?: any;
  } & MyBetaModalFormProps,
) {
  const [form] = Form.useForm();
  return (
    <BetaSchemaForm<ApiTypes.Permission.SysPermissions.Store>
      {...MyModalFormProps.props}
      title={`添加${props.title}`}
      layout="horizontal"
      labelCol={{ span: 4 }}
      wrapperCol={{ span: 20 }}
      labelAlign="left"
      width="600px"
      trigger={
        <MyButtons.Create title={`添加${props.title}`} {...props.buttonProps} />
      }
      // 确保正确弹窗，使用动态的时间参数
      key={new Date().getTime()}
      form={form}
      onOpenChange={(open: any) => {
        if (open) {
          form.resetFields(); // 清空表单数据
          // 如果有传入的item，设置为上级菜单
          if (props.item?.id) {
            form.setFieldsValue({
              parent_id: props.item.id,
            });
          }
        }
      }}
      onFinish={async (values) => {
        return Apis.Permission.SysPermissions.Store({
          ...values,
          guard_name: props.guardName,
        })
          .then(() => {
            props.reload?.();
            message.success(props.title + '成功');
            return true;
          })
          .catch(() => false);
      }}
      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(),
      ]}
    />
  );
}
