import React, { useEffect, useState } from 'react';
import { Modal, Button, Form, Input } from 'antd';
import { dispatch } from '../../../../model';

const FC = (props) => {
  const {visible, service, onCancel} = props;
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [form] = Form.useForm();

  useEffect(() => {
    if (visible) {
      form?.setFieldsValue({name: service?.odata});
    }
  }, [visible])

  const onOk = async() => {
    try {
      const row = await form.validateFields();
      setConfirmLoading(true);
      dispatch({
        type: 'pds.enableOData',
        payload: { 
          params: {
            pdsDataServiceId: service?.id,
            name: row.name,
          }
        },
        callback: data => {
          setConfirmLoading(false);
          cancel(true);
        },
        error: () => {
          setConfirmLoading(false);
        }
      });
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  }

  const reset = () => {
    form.resetFields();
    setConfirmLoading(false);
  }

  const cancel = (refresh = false) => {
    reset();
    onCancel?.(refresh);
  }

  const footer = [ 
    <Button
      key="0" 
      onClick={() => {cancel()}}
    >
    取消
    </Button>,
    <Button
      key="1" 
      type="primary"
      loading={confirmLoading}
      onClick={onOk}
    >
    确定
    </Button>,
  ];

  return (
    <Modal 
      forceRender
      visible={visible}
      title={`启用${service?.name}的OData`}
      width={540}
      onCancel={() => {cancel()}}
      footer={footer}
    >
      <Form form={form}>
        <Form.Item 
          name='name'
          label='URI'
          rules={[
            {
              required: true,
              message: '请输入URI',
            },
          ]}
        >
          <Input placeholder='请输入URI' />
        </Form.Item>
      </Form>
    </Modal>
  )
}

export default FC;