import './style/dialog.less';
import CenterModal from './CenterModal';
import { showModal, closeModal, closeModalAll } from './helper';
import { Component } from 'inferno';
import { uuidWrapper } from './helper/uuidWrapper';

export class Dialog extends Component<any, any> {

  constructor(props, context) {
    super(props, context);
  }

  public static defaultProps = {
    type: 'alert',
    leftText: '取消',
    rightText: '确定',
    onLeft: () => { console.log(); },
    onRight: () => { console.log(); },
    onMask: () => { console.log(); },
    closeByMask: false,
    // 适用于showModal 模式
    parentElement: '',
  };

  public render() {
    const { type = 'alert', title, leftText, rightText, onLeft, onRight, children, textAlign = 'left', ...restProps } = this.props;
    const cls = ['mp-dialog'];
    if (type === 'alert') {
      cls.push('dialog-alert');
    }
    if (type === 'confirm') {
      cls.push('dialog-confirm');
    }
    if (type === 'nobtn') {
      cls.push('dialog-nobtn');
    }
    const bodyStyle = {
      textAlign,
    };
    return (
      <CenterModal
        {...restProps}
        className={cls.join(' ')}
      >
        <div className="dialog-content">
          {title ? <div className="dc-title">{title}</div> : ''}
          <div className="dc-body" style={bodyStyle}>{children}</div>
          <div className="dc-footer">
            <div className="left-btn" onClick={onLeft}>{leftText}</div>
            <div className="right-btn" onClick={onRight}>{rightText}</div>
          </div>
        </div>
      </CenterModal>
    );
  }

  public static withUUIDWrapper = uuidWrapper(Dialog);

  public static open(props, instanceFlag?) {
    const Instance = instanceFlag ? uuidWrapper(Dialog) : Dialog.withUUIDWrapper;
    const defaultProps: any = {
      onLeft: () => {
        closeModal(Instance);
      },
      onRight: () => {
        closeModal(Instance);
      },
    };
    if (props.closeByMask) {
      defaultProps.onMask = () => {
        closeModal(Instance);
      };
    }
    return showModal(Instance, { ...defaultProps, ...props });
  }

  public static close(wrapper?) {
    if (wrapper && wrapper.instance) {
      return closeModal(wrapper.instance);
    }
    return closeModalAll();
  }

  public static alert(props, instanceFlag) {
    return this.open({ type: 'alert', ...props }, instanceFlag);
  }

  public static confirm(props, instanceFlag) {
    return this.open({ type: 'confirm', ...props }, instanceFlag);
  }
}
