import * as React from 'react';
import { Props, State } from './type';
import * as Styled from './index.style';
import Carousel from './carousel';
import { handleScheme } from '../utils/snailTargetHandler';
import { formatImage } from '../utils/imgResize'
import { BaseComponent } from '../base-component'

const isSnailOnline = location.host === 'du.163.com'

export class Slider extends React.Component<Props, State> {
  public static defaultProps = new Props();
  public state = new State();
  //轮播组件根目录
  public sliderContainer = null;

  public componentDidMount() {
    const {isEdit, duration, interval} = this.props
    if(!isEdit){
      new Carousel({
        rootNode: this.sliderContainer,
        speed: duration,
        interval: interval,
        onSwitch: index => {
          this.setState({
            index
          })
        }
      })
    }
  }

  public clickHandler(event: React.MouseEvent<HTMLUListElement>){
    /**
     * 当图片为2张的时候
     * carousel 会通过cloneNode复制节点，来获得比较好的切换效果
     * 同时会导致新复制出来的节点的事件丢失，所以这里使用事件代理来规避这个情况
     * 暂时因为只有一个div所以没有递归查找
     */
    let target = (event.target as any)?.dataset?.href;

    if (!target) return;
    if(location.href.indexOf('lofter.com') > 0){
      const newWebview = (event.target as any).dataset.newWebview;
      // 有newWebview属性的，需要在webview中打开，可以带来更好的打开体验
      if (newWebview === 'true') {
        target = `lofter://webview?url=${encodeURIComponent(target)}&inside=true`;
      }
      location.href = target
      //lofter不需要打点
      return
    }
    let {isEdit, logPointId, pos} = this.props;
    let logQuery;
    //蜗牛频道页默认打点id
    if(isSnailOnline){
      logPointId = logPointId || 'acttemplate1-1';
      logQuery = {
        category: 'acttemplate',
        url: target,
        pos
      }
    }
    handleScheme({
      target,
      logPointId,
      logQuery,
      isEdit
    })
  }

  public render() {
    const {
      slider,
      style,
      marginTop,
      space,
      radius
    } = this.props
    let containerWidth = parseFloat(style.width);
    let contentWidth = containerWidth - (space * 2);
    let {width = 3, height = 1} = slider && slider[0] && slider[0].imageObj || {}

    return (
      <Styled.Container style={style}>
        <BaseComponent {...this.props}>
          <div className={marginTop && 'f-before'}>
            <div
              ref={(ref) => this.sliderContainer = ref}
              id="slider-container"
              className="slider-container"
              style={{
                marginTop: `${marginTop}rem`
              }}
            >
              <ul
                className="slider"
                style={{height: `${contentWidth*height/width}rem`}}
                onClick={this.clickHandler.bind(this)}
              >
                {
                  this.props.slider.length > 0 && this.props.slider.map((sliderItem, index) => {
                    const {imageObj, target, newWebview = false} = sliderItem
                    if(imageObj){
                      let { url } = imageObj
                      return url &&
                        <li
                          key={index}
                        >
                          <div
                            data-href={target}
                            className="slider-image"
                            data-new-webview={newWebview}
                            style={{
                              width: `calc(100% - ${space * 2}rem)`,
                              backgroundImage: `url(${formatImage(url)})`,
                              marginLeft: `${space}rem`,
                              marginRight: `${space}rem`,
                              borderRadius: `${radius}rem`
                            }}
                          ></div>
                        </li>
                    }
                  })
                }
                {
                  this.props.slider.length == 0 && this.props.isEdit && <li>轮播图组件</li>
                }
              </ul>
              {
                this.props.slider.length && this.props.slider.length > 1 &&
                  <ul className="index">
                    {
                      this.props.slider.map((item, index) => <li key={index} className={`item ${index === this.state.index && 'current'}`}></li>)
                    }
                  </ul>
              }
            </div>
          </div>
        </BaseComponent>
      </Styled.Container>
    )
  }
}
