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

export default function Create(props: MyBetaModalFormProps) {
  const [form] = Form.useForm();

  return (
    <BetaSchemaForm<ApiTypes.Company.Organizations.Store>
      {...MyModalFormProps.props}
      title={`添加${props.title}`}
      wrapperCol={{ span: 24 }}
      width="500px"
      trigger={<MyButtons.Create title={`添加${props.title}`} />}
      key={new Date().getTime()}
      form={form}
      onOpenChange={(open: any) => {
        if (open) {
          form.resetFields(); // 清空表单数据
        }
      }}
      onFinish={async (values: any) =>
        Apis.Company.Organizations.Store({
          ...values,
          companies_id: values?.companies_id || props?.item?.id,
          parent_id: values?.parent_id?.[values.parent_id.length - 1],
        })
          .then(() => {
            props.reload?.();
            message.success(props.title + '成功');
            return true;
          })
          .catch(() => false)
      }
      columns={[
        ...(props?.item?.id
          ? []
          : [
              Selects?.Companies({
                key: 'companies_id',
                title: '公司',
                colProps: { span: 24 },
                required: true,
              }),
            ]),
        MyFormItems.EnumRadio({
          key: 'type',
          title: '类型',
          colProps: { span: 24 },
          valueEnum: OrganizationsTypeEnum,
          required: true,
        }),
        {
          key: 'name',
          title: '组织名称',
          colProps: { span: 24 },
          formItemProps: { ...rulesHelper.text },
        },
        {
          name: ['type'],
          valueType: 'dependency',
          columns: ({ type }: any) => {
            return type !== OrganizationsTypeEnum.Group.value
              ? [
                  Selects?.OrganizationsTree({
                    title: '设置上级组织(可选)',
                    key: 'parent_id',
                    params: { companies_id: props?.item?.id },
                    colProps: { span: 24 },
                    fieldProps: {
                      placeholder: '可搜索或手动选择上级组织',
                    },
                  }),
                ]
              : [];
          },
        },
      ]}
    />
  );
}
