import {
  ModalForm,
  ProFormRadio,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { Form } from 'antd';
import React from 'react';
import { OPTIONS } from '../../constants';
import { ConfigController, types } from '../../services';

interface EditFormProps {
  title: string;
  type: 'add' | 'update';
  trigger: JSX.Element;
  value?: ConfigController.ConfigFields;
  onOk: () => void;
  appList: types.SelectOptionFields[];
}

const EditForm: React.FC<EditFormProps> = ({
  trigger,
  title,
  value,
  type,
  onOk,
  appList,
}) => {
  const [form] = Form.useForm<ConfigController.ConfigFields>();

  return (
    <ModalForm<ConfigController.ConfigFields>
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 14 }}
      layout="horizontal"
      title={title}
      trigger={trigger}
      form={form}
      autoFocusFirstInput
      modalProps={{
        destroyOnClose: true,
      }}
      submitTimeout={2000}
      onFinish={async (values) => {
        const { label: appName } =
          appList.find((item) => item.value === values.appId) || {};
        if (type === 'add') {
          await ConfigController.addApi({ ...values, appName });
        } else if (type === 'update') {
          await ConfigController.updateApi({
            ...values,
            appName,
            configId: value?.configId,
          });
        }
        onOk();
        return true;
      }}
    >
      <ProFormSelect
        name="appId"
        label="应用名称"
        initialValue={value?.appId}
        rules={[{ required: true }]}
        options={appList}
      />
      <ProFormText
        name="configName"
        label="参数名称"
        initialValue={value?.configName}
        rules={[{ required: true }]}
      />
      <ProFormText
        name="configKey"
        label="参数键名"
        initialValue={value?.configKey}
        rules={[{ required: true }]}
      />
      <ProFormText
        name="configValue"
        label="参数键值"
        initialValue={value?.configValue}
        rules={[{ required: true }]}
      />
      <ProFormRadio.Group
        label="系统内置"
        name="configType"
        initialValue={value?.configType || 'Y'}
        options={OPTIONS.OPTIONS_CONFIG}
      />
      <ProFormTextArea
        label="备注"
        placeholder="请输入内容"
        name="remark"
        initialValue={value?.remark}
      />
    </ModalForm>
  );
};

export default EditForm;
