import * as React from 'react';
import { Props, State } from './type';

import * as Styled from './index.style'

export class FoldContainer extends React.Component<Props, State> {
  public static defaultProps = new Props();
  public state = new State();

  componentDidMount() {
    if (this.props.foldImg) {
      this.preloadImg(this.props.foldImg.url)
    }
  }

  handleFold = () => {
    const { fold } = this.state
    this.setState({ 
      fold: !fold
    })
  }

  preloadImg = (url: string) => {
    const img = new Image();
    img.src = url
  }

  public render() {
    const { 
      children, 
      isEdit, 
      foldHeight,
      expandImg,
      foldImg
    } = this.props
    const { fold } = this.state

    return (
      <div
        style={this.props.style}
      >
        {
          children && ( Array.isArray(children) && children.length)
            ? (
              <>
                <Styled.FoldContainer 
                  foldHeight={foldHeight} 
                  fold={fold}
                >
                  {children}
                </Styled.FoldContainer>
                {
                  !!foldHeight && (
                    <>
                      {
                        fold && expandImg || !fold && foldImg 
                          ? (
                            <Styled.FoldImg onClick={this.handleFold} src={fold && expandImg.url || !fold && foldImg.url} />
                          )
                          : (
                            <Styled.FoldBtn onClick={this.handleFold}>
                              { fold ? '展开' : '收起' }
                              <Styled.FoldBtnIcon src="https://lofter.lf127.net/1631705008363/right-arrow.png" alt="fold-icon" />
                            </Styled.FoldBtn>
                          )
                      }
                    </>
                  )
                }
              </>
            )
            : (
              <Styled.EmptyContainer>
                {
                  isEdit && (
                    <div>
                      请添加需要折叠的元素到该容器下
                    </div>
                  )
                }
              </Styled.EmptyContainer>
            )
        }
      </div>
    )
  }
}
