import React, { useEffect, useMemo, useRef, useState } from 'react';
import { Modal, Form, Button } from "antd";

import UpdateBasicInfo from "./UpdateBasicInfo";
import UpdateField from "./UpdateField";
import { showMessage } from '../../../../../util';
import { dispatch } from '../../../../../model';
import './UpdateTemplateModal.less';

export const EditTemplateContext = React.createContext({
  attrIsEditingFunction: null,
});

export const UpdateTemplateModal = (props) => {
  const { visible, onCancel, action = 'add', template, nodeId } = props;
  const [form] = Form.useForm();
  const [fields, setFields] = useState([]);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const attrIsEditingRef = useRef(false);

  useEffect(() => {
    if (visible) {
      form?.setFieldsValue({name: template?.name||'', cnName: template?.cnName||'', comment: template?.comment||''});
      setFields([]);
    }
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [visible])

  const title = useMemo(() => {
    if (action === 'add') {
      return '新建模版';
    }
    if (action === 'detail') {
      return '模版详情';
    }

    if (action === 'update') {
      return '编辑模版';
    }
    return '';
  }, [action])

  const attrIsEditingFunction = (value) => {
    attrIsEditingRef.current = value;
  }

  const onFieldChange = (values) => {
    setFields(values);
  }

  const save = (e) => {
    e.stopPropagation();

    if (attrIsEditingRef.current) {
      showMessage("warn", '还有字段正在编辑，需先保存该字段!');
    } else {
      saveLogic();
    }
  }

  const saveLogic = async () => {
    try {
      const row = await form.validateFields();

      if ((fields||[]).length === 0) {
        showMessage('warn', '请新增字段');
        return;
      }

      setConfirmLoading(true);

      let url = '', newTemplate = {};
      if (action === 'add') {
        url = 'msd.addModel';
        newTemplate = {...row, nodeId: nodeId||''};
      } else {
        url = 'msd.updateModel';
        newTemplate = {...template, ...row}
      }

      dispatch({
        type: url,
        payload: {
          data: newTemplate
        },
        callback: id => {

          (fields||[]).forEach((field, index) => {
            field.parentId = id;
            field.seq = index;
          });

          dispatch({
            type: 'msd.saveColumns',
            payload: {
              params: {
                modelId: id
              },
              data: fields
            },
            callback: () => {
              setConfirmLoading(false);
              onCancel && onCancel(true);  
            },
            error: () => {
              setConfirmLoading(false);
            }
          });
        },
        error: () => {
          setConfirmLoading(false);
        }
      });

    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  }

  return (
    <EditTemplateContext.Provider value={{
      attrIsEditingFunction,
    }}>
      <Modal
        forceRender
        className='update-template-modal'
        width='80%'
        title={title}
        visible={visible}
        onCancel={() => {onCancel && onCancel();}}
        onOk={save}
        footer={[
          <Button key="cancel" onClick={() => {onCancel && onCancel();}}>
            取消
          </Button>,
          action!=='detail' && <Button
            key="ok"
            type="primary"
            loading={confirmLoading}
            onClick={save}
          >
            确定
          </Button>,
        ]}
      >
        <UpdateBasicInfo form={form} editable={action!=='detail'} template={template} />
        <UpdateField editable={action!=='detail'} template={template} onChange={onFieldChange} visible={visible} />
      </Modal>
    </EditTemplateContext.Provider>
  );
}
