import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { deepCopy } from 'amos-tool';
import ModalDialog from './../modal';
import { trimFormData } from './FormUtils';
import Tip from './../tip';

class Container extends Component {
  static propTypes = {
    onStart: PropTypes.func,
    children: PropTypes.node
  };

  componentDidMount() {
    this.props.onStart && this.props.onStart();
  }

  render() {
    return (
      <div className="eb-form-modal-content">
        { this.props.children }
      </div>
    );
  }
}
/**
 * 弹出框表单修饰器
 * @class widthFormModal
 * @extends {Component}
 */
const widthFormModal = function({ width, name, title, modalClass, noOverflow = false }){
  return function(Target) {


    // eslint-disable-next-line react/no-multi-comp
    class FormMoal extends Component {

      constructor(props) {
        super(props);
        this.state = {
          visible: false,
          type: 'add',
          data: null,
          loading: false
        };
      }

      componentDidMount() {
        const props = {
          ...this.props
        };
        const { formRef } = props;
        // 使用修饰器后组件ref不能用了替换成formRef
        formRef && formRef(this.instance);
      }

      onOpen = (data, type) => {
        if (data) {
          this.setState({ visible: true, type: type || 'edit', data });
        } else {
          this.setState({ visible: true, type: type || 'add' });
        }
      }

      onInit = () => {
        const { data } = this.state;
        this.targetInstance && this.targetInstance.onInit && this.targetInstance.onInit(data, this.state.type);
      }
      /**
       * 获取表单form对象（目前只用于提交验证）
       *
       * @memberof Wrapper
       */
      onFormInstance = (component) => {
        // 解决form表单中只有一个input项时，回车页面刷新问题
        // 在form节点上添加 onsubmit = 'return false;' 属性
        if (component && component._reactInternalFiber && component._reactInternalFiber.child && component._reactInternalFiber.child.stateNode) {
          component._reactInternalFiber.child.stateNode.setAttribute('onsubmit','return false;');
        }
        this.form = component;
      }

      onTargetInstance = (node) => {
        if (node) {
          this.targetInstance = node;
          this.targetInstance.form = this.form;
        }
      }
      /**
       * 保存按钮事件
       */
      onSave = (e) => {
        this.targetInstance.onSubmit && this.targetInstance.onSubmit(this.onCancel);
      }
      /**
       * 表单提交
       *
       * @memberof Wrapper
       */
      onSubmit = ({ action, changeValues, form, onSuccess, onError, tip = '保存', showTip = true, showError = true, isClose = true }) => {
        if (!form && !this.form) {
          throw new Error('formSubmit方法form不能为空');
        }
        if (this.state.loading) {
          return;
        }
        this.setState({ loading: true });
        (form || this.form).validate((valid,dataValues) => {
          let values = deepCopy(dataValues);
          if (valid) {
            let obj = null;
            if (changeValues) {
              obj = changeValues(values);
            }
            if (obj) {
              values = obj;
            }
            if (action) {
              action(trimFormData(values)).then(d => {
                showTip && Tip.success(`${tip}成功`);
                onSuccess && onSuccess(d, values);
                this.props.reload && this.props.reload();
                isClose && this.onCancel();
              }).catch(msg => {
                (showTip || showError) && Tip.error(msg || `${tip}失败`);
                onError && onError(msg, values);
              }).finally(() => {
                this.setState({ loading: false });
              });
            } else {
              onSuccess && onSuccess(values);
              isClose && this.onCancel();
              this.setState({ loading: false });
            }
          } else {
            this.setState({ loading: false });
            return false;
          }
        });
      }
      /**
       * 关闭对话框
       */
      onCancel = () => {
        this.targetInstance.onDestroy && this.setState({
          visible: false,
          type: 'add',
          data: null,
          loading: false
        }, this.targetInstance.onDestroy());
      }

      render() {
        const { visible, type, data } = this.state;
        const props = { ...this.props };
        delete props.formRef;
        if ('formInstance' in props) {
          throw new Error('widthFormModal修饰器下的组件不能传入formInstance属性');
        }
        if ('formSubmit' in props) {
          throw new Error('widthFormModal修饰器下的组件不能传入formSubmit属性');
        }
        if (this.props.title) {
          title = this.props.title;
        }
        if (this.props.name) {
          name = this.props.name;
        }
        return (
          <ModalDialog
            visible={visible}
            width={width}
            onCancel={this.onCancel}
            noOverflow={noOverflow}
            modalClass={`yeebt-form-modal ${modalClass || ''}`}
            onOk={this.onSave}
            title={title ? title : `${type === 'add' ? '添加' : '编辑'}${name}`}
            floorNode={this.props.floorNode}
            okText={this.props.okText}
            cancelText={this.props.cancelText}
          >
            <Container onStart={this.onInit}>
              <Target
                {...this.props}
                onCancel={this.onCancel}
                ref={this.onTargetInstance}
                editData={data}
                pageType={type}
                formInstance={this.onFormInstance}
                formSubmit={this.onSubmit}
              />
            </Container>
          </ModalDialog>
        );
      }
    }

    FormMoal.propTypes = {
      reload: PropTypes.func,
      floorNode: PropTypes.any,
      okText: PropTypes.string,
      title: PropTypes.string,
      name: PropTypes.string,
      cancelText: PropTypes.string
    };

    return FormMoal;
  };
};

export default widthFormModal;
