import Taro, { Component } from '@tarojs/taro';
import { View } from '@tarojs/components';

import './index.less';

export default class Skeleton extends Component {
  static defaultProps = {
    selector: 'skeleton',
    backgroundColor: 'transparent'
  };
  state = {
    rects: [],
    circs: []
  };

  componentDidMount() {
    const { selector } = this.props;

    Promise.all([
      this.selectAll(`.${selector} >>> .${selector}-rect`),
      this.selectAll(`.${selector} >>> .${selector}-circ`)
    ]).then(([rects, circs]) =>
      this.setState({
        rects,
        circs
      })
    );
  }

  selectAll = selector =>
    new Promise(resolve =>
      Taro.createSelectorQuery()
        .selectAll(selector)
        .boundingClientRect()
        .exec(res => resolve(res[0]))
    );

  createStyle = ({ width, height, top, left }) => ({
    width: `${width}px`,
    height: `${height}px`,
    top: `${top}px`,
    left: `${left}px`
  });

  createcircStyle = rect => ({
    ...this.createStyle(rect),
    'border-radius': `${rect.height / 2}px`
  });

  render() {
    const { backgroundColor } = this.props;
    const { rects = [], circs = [] } = this.state;

    const skeletonStyle = { backgroundColor };

    return (
      <View
        className='container'
        style={skeletonStyle}
        onTouchMove
        onClick
      >
        {rects.map(rect => (
          <View
            key={`${rect.top}-${rect.left}`}
            className='item'
            style={this.createStyle(rect)}
          />
        ))}
        {circs.map(circ => (
          <View
            key={`${circ.top}-${circ.left}`}
            className='item'
            style={this.createcircStyle(circ)}
          />
        ))}
      </View>
    );
  }
}
