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

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

const UpdateDefineTreeNodeModal = (props) => {
  const {visible, onCancel, type, node} = props;

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

  useEffect(() => {
    if (visible) {
      if (type === 'add') {
        form.setFieldsValue({action: node ? 'sub' : 'root', name: '', comment: ''});
      } else {
        form.setFieldsValue({action: '', name: node?.name||'', comment: node?.comment||''});
      }
    }
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [visible, node, type])

  const handleCancel = () => {
    setConfirmLoading(false);
    form.setFields([{ name: 'name', errors: [] }, { name: 'comment', errors: [] }]);
    onCancel && onCancel();
  }

  const handleOk = async () => {
    setConfirmLoading(true);

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

      let payload = null;
      if (type === 'add') {
        payload = {
          name: values.name||'',
          comment: values.comment||'', 
          parentId: (values.action==='root')?'root':node?._id
        };
      } else {
        payload = {
          ...node,
          name: values.name||'',
          comment: values.comment||'', 
        }
      }

      let url = (type === 'add')?'msd.addTreeNode':'msd.updateTreeNode';

      dispatch({
        type: url,
        payload: {
          data: payload
        },
        callback: id => {
          setConfirmLoading(false);
          onCancel && onCancel(true, id);
        },
        error: () => {
          setConfirmLoading(false);
        }
      });
    } catch (errInfo) {
      setConfirmLoading(false);
    }
  }

  return (
    <Modal 
      confirmLoading={confirmLoading}
      visible={visible}
      title={type==='add'?"新增目录":"编辑目录"}
      onOk={handleOk}
      onCancel={handleCancel}
    >
      <UpdateNodeForm type={type} node={node} form={form} />
    </Modal>
  );
}

export default UpdateDefineTreeNodeModal;