/* eslint-disable no-plusplus */
/* eslint-disable no-unused-vars */
import React, { useEffect, useRef, useState } from 'react';
import Swiper from 'swiper/js/swiper';
import 'swiper/css/swiper.min.css';
import { mergeObject, guid, initTrack } from '../utils';
import { getNodeStyle } from '../utils/style';
import JsCss, { plugin } from './jscss';
import { PREFIX_CLS } from '../config';
import './style/index';
import { SysModel } from '../utils/system';

const prefixCls = `${PREFIX_CLS}-swiper`;
export default ({ model, data, dispatch = () => {}, children, state = {} }) => {
  const { style, props, track = {} } = mergeObject(plugin, data);
  const { carSeriesId } = state;
  const componentName = `${prefixCls}__${
    model === SysModel.DEV ? guid() : data.id
  }`;
  const { navigation = {}, pagination = {} } = style;
  const {
    sliders,
    loop,
    canAutoPlay,
    paginationIsClick,
    effect,
    hasPagination,
    hasNavigation,
    delay,
    coverflowEffect,
    slidesPerView,
    centeredSlides,
    initialSlide,
  } = props;
  const [swiperRealIndex, setSwiperRealIndex] = useState(initialSlide);
  const { rotate, stretch, depth } = coverflowEffect;
  const onLoad = () => {
    const values = sliders.map(() => {
      const id = guid();
      return {
        type: 'VerLayout',
        id,
        style: {
          width: '100%',
          height: 'auto',
        },
        props: {},
        pid: data.id,
        children: [
          {
            type: 'Image',
            pid: id,
            id: guid(),
            style: {
              width: '100%',
            },
            children: [],
          },
        ],
      };
    });
    if (data.children.length === 0) {
      dispatch({
        type: 'tree/updateByKey',
        payload: {
          key: 'children',
          value: values,
          id: data.id,
          createHistory: false,
        },
      });
      dispatch({
        type: 'tree/select',
        payload: {
          data: { ...data, children: values },
        },
      });
    }
  };
  const swiper = useRef(null);
  const SwiperInit = () => {
    if (swiper.current) {
      if (swiper.current.destroy) {
        swiper.current.destroy();
        swiper.current = null;
      }
    }
    swiper.current = new Swiper(`#${componentName}`, {
      loop,
      watchSlidesProgress: true,
      centeredSlides,
      touchRatio: effect === 'coverflow' ? 2 : 1,
      observeParents: true,
      observer: true,
      simulateTouch: model !== SysModel.DEV,
      observeSlideChildren: true,
      initialSlide: swiperRealIndex,
      slidesPerView,
      roundLengths: true,
      updateOnImagesReady: true,
      reloadImages: true,
      effect: effect !== 'coverflow' ? effect : false,
      pagination: {
        el: '.swiper-pagination',
        type: 'bullets',
        dynamicBullets: false,
        hideOnClick: false,
        clickable: paginationIsClick,
        renderBullet(index, className) {
          return `<span data-dndc-track=${initTrack({
            basicUrl: track.track,
            carSeriesId,
            id: `${data.id}pag${index + 1}`,
            target: `轮播点${index + 1}`,
          })} class="${className}"></span>`;
        },
      },
      autoplay: canAutoPlay ? { delay, disableOnInteraction: false } : false,
      navigation: {
        nextEl: `#${componentName} .swiper-button-next`,
        prevEl: `#${componentName} .swiper-button-prev`,
      },
      on: {
        slideChangeTransitionEnd: () => {
          // swiper开启循环的时候，会自动复制slide首尾的dom结构，但是不会复制相应的slide的js事件处理。
          if (swiper.current && loop) {
            const { realIndex, activeIndex } = swiper.current;
            const itemSlideDom = swiper.current.slides[activeIndex];
            if (itemSlideDom.className.indexOf('swiper-slide-duplicate ') > 0) {
              // setSwiperRealIndex(realIndex);
              swiper.current.slideToLoop(realIndex, 0, true);
            }
          }
        },
        progress() {
          if (effect && effect === 'coverflow') {
            const THIS = this;
            const width = THIS.slides.eq(0)[0].offsetWidth / rotate;
            for (let i = 0; i < THIS.slides.length; i++) {
              const slide = THIS.slides.eq(i);
              const slideProgress = THIS.slides[i].progress;
              let modify = 1;
              if (Math.abs(slideProgress) > 1) {
                modify = (Math.abs(slideProgress) - 1) * stretch + 1;
              }
              const translate = `${slideProgress * modify * width}px`;
              const scale = 1 - Math.abs(slideProgress) / depth;
              const zIndex = 999 - Math.abs(Math.round(10 * slideProgress));
              slide.transform(`translateX(${translate})  scale(${scale})`);
              slide.css('zIndex', zIndex);
              slide.css('opacity', 1);
              if (Math.abs(slideProgress) > 3) {
                slide.css('opacity', 0);
              }
            }
          }
        },
        setTransition(transition) {
          if (effect && effect === 'coverflow') {
            const THIS = this;
            for (let i = 0; i < THIS.slides.length; i++) {
              const slide = THIS.slides.eq(i);
              slide.transition(transition);
            }
          }
        },
        resize() {
          const THIS = this;
          THIS.update();
        },
      },
    });
  };
  useEffect(() => {
    if (model === SysModel.DEV) {
      onLoad();
    }
    SwiperInit();
  }, []);
  useEffect(() => {
    SwiperInit();
  }, [
    effect,
    loop,
    paginationIsClick,
    slidesPerView,
    centeredSlides,
    swiperRealIndex,
    initialSlide,
    pagination.type,
    track.track,
  ]);
  useEffect(() => {
    if (effect && effect === 'coverflow') {
      SwiperInit();
    }
  }, [rotate, depth, stretch]);
  useEffect(() => {
    if (swiper.current) {
      if (canAutoPlay) {
        swiper.current.autoplay.start();
      } else {
        swiper.current.autoplay.stop();
      }
    }
  }, [canAutoPlay]);
  useEffect(() => {
    if (swiper.current) {
      swiper.current.params.autoplay.delay = delay;
    }
  }, [delay]);
  useEffect(() => {
    if (swiper.current) {
      swiper.current.appendSlide('');
    }
  }, [children]);

  return (
    <JsCss styles={style} className={prefixCls} id={componentName}>
      <div className="swiper-wrapper">
        {children &&
          children.map((item, index) => (
            <div key={index.toString()} className="swiper-slide">
              {item}
            </div>
          ))}
      </div>

      <div
        style={{ display: hasPagination ? false : 'none' }}
        className={`swiper-pagination  ${prefixCls}-pagination--${pagination.type}`}
      />
      <div
        data-dndc-track={initTrack({
          basicUrl: track.track,
          carSeriesId,
          id: `${data.id}left`,
          target: '左切换按钮',
        })}
        className={`swiper-button-prev ${prefixCls}-navigation--${navigation.type}`}
        style={{ display: hasNavigation ? false : 'none' }}
      />
      <div
        data-dndc-track={initTrack({
          basicUrl: track.track,
          carSeriesId,
          id: `${data.id}right`,
          target: '右切换按钮',
        })}
        className={`swiper-button-next  ${prefixCls}-navigation--${navigation.type}`}
        style={{ display: hasNavigation ? false : 'none' }}
      />
    </JsCss>
  );
};
