/**
 * @file PopUp
 * @description
 * @author fex
 */

import React from 'react';
import { themeable, ThemeProps } from '../theme';
import { localeable, LocaleProps } from '../locale';
import Transition, {
  ENTERED,
  EXITING,
  EXITED,
  ENTERING
} from 'react-transition-group/Transition';
import Portal from 'react-overlays/Portal';
import { Icon } from './icons';
import Button from './Button';
import { isMobile } from '../utils/helper';
import { findDOMNode } from 'react-dom';

export interface PopUpPorps extends ThemeProps, LocaleProps {
  title?: string;
  className?: string;
  style?: {
    [styleName: string]: string;
  };
  overlay?: boolean;
  onHide?: <T>(e: T) => void; // Jay
  isShow?: boolean;
  container?: any;
  showConfirm?: boolean;
  onConfirm?: (value: any) => void;
  showClose?: boolean;
  placement?: 'left' | 'center' | 'right';
  header?: JSX.Element;
  // Jay
  closeOnOutside?: boolean;
  round?: boolean;
  tableRotate?: boolean;
  updateChanged?: boolean;
  onActonClick?: (value: any[], optionModified?: boolean | undefined) => void;
  multiple?: boolean
  footer?: JSX.Element;
  popOverHeatClassName?: string;
  isShowHide?: boolean
}

const fadeStyles: {
  [propName: string]: string;
} = {
  [ENTERED]: '',
  [EXITING]: 'out',
  [EXITED]: '',
  [ENTERING]: 'in'
};
interface OperationState {
  more: boolean;
  hide: boolean;
}
export class PopUp extends React.PureComponent<PopUpPorps, OperationState> {
  scrollTop: number = 0;
  dom: HTMLDivElement;
  static defaultProps = {
    className: '',
    overlay: true,
    isShow: false,
    container: document.body,
    // Jay
    // showClose: true,
    showClose: false,

    onConfirm: () => { },
    // Jay
    closeOnOutside: true,
  };
  state = {
    more: false,
    hide: false,
  }
  componentDidMount() {
    const { isShow } = this.props

    if (isShow) {
      this.handleOnTouchMove()
      this.dom.addEventListener("scroll", () => { this.handleOnTouchMove() })
    }
    if (!this.props?.isShowHide) {
      this.setState({ hide: true })
    }
  }
  componentDidUpdate(prevProps: any) {
    const props = this.props
    // 在from表单上因为有下拉刷新的组件导致会点击两次，暂时不知道为啥，目前只有Upload上不可编辑下会这样，就在这种情况下延迟500毫米跳过不知道为啥的第二次点击
    if (props.isShowHide) {
      if (prevProps.isShow !== props.isShow && props.isShow == true) {
        setTimeout(() => {
          this.setState({ hide: true })
        }, 500)
      } else if (prevProps.isShow !== props.isShow && props.isShow == false) {
        if (this.state.hide) {
          this.setState({ hide: false })
        }
      }
    }


    if (props.isShow) {
      this.scrollTop =
        document.body.scrollTop || document.documentElement.scrollTop;
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = 'auto';
      document.body.scrollTop = this.scrollTop;
    }
  }
  componentWillUnmount() {
    const { isShow } = this.props
    document.body.style.overflow = 'auto';
    document.body.scrollTop = this.scrollTop;
    if (isShow) {
      this.dom.removeEventListener("scroll", () => { this.handleOnTouchMove() })
    }
  }

  handleClick(e: React.MouseEvent) {
    e.stopPropagation();
  }
  domRef = (ref: HTMLDivElement) => {
    this.dom = ref;
  };
  handleOnTouchMove() {
    const { classPrefix: ns } = this.props;
    const PopUp = findDOMNode(this) as HTMLElement;
    const PopUpContent = PopUp?.querySelector(
      `.${ns}PopUp-content`
    ) as HTMLElement;
    const scrollHeight = PopUpContent.firstElementChild?.scrollHeight;
    const clientHeight = PopUpContent.clientHeight
    const scrollTop = PopUpContent.scrollTop
    if (scrollHeight && clientHeight + scrollTop < scrollHeight) {
      this.setState({ more: true })
    } else {
      this.setState({ more: false })
    }
  }
  render() {
    const {
      style,
      title,
      children,
      overlay,
      onHide,
      onConfirm,
      onActonClick,
      classPrefix: ns,
      classnames: cx,
      className,
      isShow,
      container,
      showConfirm,
      translate: __,
      showClose,
      header,
      multiple,
      placement = 'center',
      // Jay
      closeOnOutside,
      round,
      tableRotate,
      footer,
      popOverHeatClassName,
      ...rest
    } = this.props;

    const outerStyle: any = {
      ...style
    };
    delete outerStyle.top;

    return (
      <Portal container={container} >
        <Transition mountOnEnter unmountOnExit in={isShow} timeout={500} appear >
          {(status: string) => {
            return (
              <div
                // Jay
                // className={cx(`${ns}PopUp`, className, fadeStyles[status])}
                className={cx(`${ns}PopUp`, this.props.updateChanged && 'updateChanged', className, fadeStyles[status], round && 'round', tableRotate && 'pop-rotate')}
                style={outerStyle}
                {...rest}
                onClick={this.handleClick}

                onTouchMove={() => { this.handleOnTouchMove() }}
              >
                {overlay && (
                  // Jay
                  // <div className={`${ns}PopUp-overlay`} onClick={onHide} />
                  <div className={`${ns}PopUp-overlay`} onClick={(e) => {
                    this.state.hide && (!showClose || closeOnOutside) && onHide?.(e)
                  }} />
                )}
                <div className={cx(`${ns}PopUp-inner`)} >
                  {!showConfirm && showClose ? (
                    <div className={cx(`${ns}PopUp-closeWrap`, popOverHeatClassName)}>
                      {isMobile() && header}
                      {isMobile() && onActonClick && <Button
                        className={cx(`${ns}PopUp-cancel-danger`)}
                        onClick={() => onActonClick && onActonClick([])}
                      >
                        {__('clear')}
                      </Button>}
                      < span className={cx(`${ns}PopUp-closeWrap-icon`)}>
                        <Icon
                          icon="close"
                          className={cx('icon', `${ns}PopUp-close`)}
                          onClick={onHide}
                        />
                      </span>
                    </div>
                  ) : null}
                  {showConfirm && (
                    <div className={cx(`${ns}PopUp-toolbar`)}>
                      <Button
                        className={cx(`${ns}PopUp-cancel`)}
                        level="text"
                        onClick={onHide}
                      >
                        {__('cancel')}
                      </Button>
                      {title && (
                        <span className={cx(`${ns}PopUp-title`)}>{title}</span>
                      )}
                      <Button
                        className={cx(`${ns}PopUp-confirm`)}
                        level="text"
                        onClick={onConfirm}
                      >
                        {__('confirm')}
                      </Button>
                    </div>
                  )}
                  <div
                    ref={this.domRef}
                    className={cx(`${ns}PopUp-content`, `justify-${placement}`, isMobile() && 'PopUp-scroll')}
                  >
                    {isShow ? children : null}
                    {multiple && !footer && isMobile() && this.state.more && <div style={{ width: "100%", height: 20, position: 'absolute', bottom: 0, left: 0, textAlign: 'center', fontSize: 20, lineHeight: '10px' }}>...</div>}
                  </div>
                  {(footer && isMobile()) && <div className={cx(`PopUp-footer`)}>
                    {footer}
                  </div>}
                  {!(multiple && footer && isMobile()) && <div className={cx(`PopUp-safearea`)}></div>}
                </div>
              </div>
            );
          }}
        </Transition>
      </Portal >
    );
  }
}

export default themeable(localeable(PopUp));
