import { AddButton, MyColorPicker } from '@/common';
import { Apis } from '@/gen/Apis';
import { GuardNameEnum, SysPermissionsTypeEnum } from '@/gen/Enums';
import { BetaSchemaForm } from '@ant-design/pro-components';
import { useMemoizedFn } from 'ahooks';
import { message } from 'antd';
import { useState } from 'react';

type FormType = ApiReqTypes.SysRoles.Store;

export default function Create(props: { title: string; onFinish: () => void }) {
  const [loading, setLoading] = useState(false);

  const handleFinish = useMemoizedFn(async (values: FormType) => {
    setLoading(true);
    return Apis.SysRoles.Store(values)
      .then(() => {
        message.success('添加成功');
        props.onFinish();
        return true;
      })
      .finally(() => {
        setLoading(false);
      });
  });

  return (
    <BetaSchemaForm<FormType>
      title={`添加${props.title}`}
      layoutType="ModalForm"
      trigger={<AddButton title={props.title} />}
      modalProps={{
        maskClosable: false,
        destroyOnClose: true,
      }}
      initialValues={{
        type: SysPermissionsTypeEnum.PAGE.value,
      }}
      onFinish={handleFinish}
      disabled={loading}
      loading={loading}
      columns={[
        {
          key: 'name',
          title: '名称',
        },
        {
          key: 'guard_name',
          title: '权限组',
          valueType: 'radioButton',
          fieldProps: {
            buttonStyle: 'solid',
          },
          valueEnum: GuardNameEnum,
        },
        {
          key: 'color',
          title: '颜色',
          renderFormItem: () => <MyColorPicker />,
        },
      ]}
    />
  );
}
