import React, { useEffect, useState } from 'react';
import { Modal, Form, Input } from 'antd';

import { dispatch } from '../../../../model';

const UpdatePartitionModal = (props) => {
  const { visible, onCancel, item, action = 'add' } = props;

  const [ form ] = Form.useForm();
  const [ confirmLoading, setConfirmLoading ] = useState(false);

  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 4 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 20 },
    },
  };

  useEffect(() => {

    if (visible) {
      if (action !== 'add') {
        form.setFieldsValue({ name: item?.name||'', cnName: item?.cnName||'', partitionMethod: item?.partitionMethod||'', definition: item?.definition||'', remark: item?.remark||'' });
      }
    }

    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [visible])

  const handleOk = async () => {

    try {
      const values = await form.validateFields();

      let newItem = null;
      if (action === 'add') {
        newItem = {...values};
      } else {
        newItem = {...item, ...values};
      }
      
      setConfirmLoading(true);
      dispatch({
        type: 'datamodel.savePartitionType',
        payload: {
          data: newItem
        },
        callback: data => {
          setConfirmLoading(false);
          reset();
          onCancel && onCancel(true);
        },
        error: () => {
          setConfirmLoading(false);
        }
      })

    } catch (errInfo) {

    }
  }

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

  return (
    <Modal 
      forceRender
      visible={visible}
      title={action==='add'?'新增分区':'编辑分区'}
      width={520}
      confirmLoading={confirmLoading}
      onCancel={() => {
        reset();
        onCancel && onCancel();
      }}
      onOk={handleOk}
    >
    <Form 
      {...formItemLayout}
      form={form}
    >
      <Form.Item 
        label="名称" 
        name="name" 
        rules={[{ required: true, message: '请输入分区名称' }]}
      >
        <Input />
      </Form.Item>
      <Form.Item 
        label="中文名称" 
        name="cnName" 
        rules={[{ required: true, message: '请输入分区中文名称' }]}
      >
        <Input />
      </Form.Item>
      <Form.Item 
        label="分区方式" 
        name="partitionMethod" 
        rules={[{ required: true, message: '请输入分区方式' }]}
      >
        <Input />
      </Form.Item>
      <Form.Item 
        label="定义" 
        name="definition" 
      >
        <Input.TextArea row={4} />
      </Form.Item>
      <Form.Item 
        label="描述" 
        name="remark" 
      >
        <Input.TextArea row={4} />
      </Form.Item>
    </Form>
    </Modal>
  );
}

export default UpdatePartitionModal;