import { customCarousel, CATEGORIES } from '../../configuration/constants';
import { throttle } from '../../utils'

export default {

  // 组件名称
  name: customCarousel,

  // 前面板html模板
  viewTemplate() {
    return `
      <div data-gjs-type="${customCarousel}" class="${customCarousel}">
      </div>
    `
  },
  // 前面板html样式
  viewStyle() {
    return `
      <style>
        .${customCarousel} {
          width: 700px;
          height: 500px;
          position: absolute;
          overflow: hidden;
          margin: 50px auto;
        }
        .${customCarousel} .bannerBox{
          width: 2100px;
          height: 100% !important;
          position: relative;
          margin: 0;
          padding: 0;
        }
        .${customCarousel} .bannerBox li{
          float: left;
          position: relative;
          width: 700px;
          height: 100% !important;
          list-style: none;
          margin: 0;
          padding: 0;
        }
      </style>
    `
  },

  // 编辑器右侧块管理器中显示属性配置
  blockOptions() {
    return {
      label: `
        <svg t="1595474563533" class="gjs-block-svg" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
          <defs>
            <style type="text/css"></style>
          </defs>
          <path class="gjs-block-svg-path" d="M256 768a64 64 0 1 0 128 0 64 64 0 1 0-128 0zM448 768a64 64 0 1 0 128 0 64 64 0 1 0-128 0zM640 768a64 64 0 1 0 128 0 64 64 0 1 0-128 0z"></path>
          <path class="gjs-block-svg-path" d="M972.8 320H896c0-32-38.4-64-64-64H192c-32 0-64 38.4-64 64H64c-32 0-64 32-64 64v448c0 32 44.8 64 64 64h64c0 32 44.8 64 64 64h640c32 0 64-38.4 64-64h64c32 0 64-38.4 64-64V384c0-32-25.6-64-51.2-64zM128 832H64V384h64v448z m704 64H192V320h640v576z m128-64h-64V384h64v448z"></path>
        </svg>
        <div class="gjs-block-label">轮播</div>
      `
    };
  },

  spOptions() {
    return {
      label: '轮播',
      icon: 'globe',
      author: '宗介',
      email: 'zongjie.wxt@xuelangyun.com',
      docUrl: "https://xuelangyun.yuque.com/docs/share/87057d95-c492-4746-a933-1af6be8bdaa0?# 《轮播》"
    }
  },

  // 组件属性
  componentOptions() {
    return {
      name: customCarousel,
      droppable: false,
      resizable: true,
      dmode: 'absolute',
      highlightable: false,
      childrenSelectable: false,
      traits: [
        {
          name: 'timeInterval',
          label: '定时器时间间隔(秒)',
          changeProp: 1,
          type: 'number',
          min: 1
        },
        {
          name: 'dotBgColor',
          label: '面板指示点背景色',
          changeProp: 1,
          type: 'color'
        },
        {
          name: 'dotCurrBgColor',
          label: '面板当前指示点背景色',
          changeProp: 1,
          type: 'color'
        },
        {
          name: 'dotBorderColor',
          label: '面板指示点边框颜色',
          changeProp: 1,
          type: 'color'
        }
      ],
      'timeInterval': 5,
      'dotBgColor': 'rgba(0,0,0,0)',
      'dotCurrBgColor': 'black',
      'dotBorderColor': 'gray',
    }
  },

  onModelScript() {
    const timeInterval = Boolean('{[ timeInterval ]}') ? Number('{[ timeInterval ]}') * 1000 : 5000;
    const dotBgColor = Boolean('{[ dotBgColor ]}') ? ('{[ dotBgColor ]}').toString() : 'rgba(0,0,0,0)';
    const dotCurrBgColor = Boolean('{[ dotCurrBgColor ]}') ? ('{[ dotCurrBgColor ]}').toString() : 'black';
    const dotBorderColor = Boolean('{[ dotBorderColor ]}') ? ('{[ dotBorderColor ]}').toString() : 'gray';

    const self = this;
    const _id = self.getAttribute('id');

    // 设置window 定时器
    if (window.CustomCarouseltimer === undefined) { window.CustomCarouseltimer = {}; }
    if (window.CustomCarouseltimer[_id] !== undefined) {
      clearInterval(window.CustomCarouseltimer[_id]);
    }

    let bannerWidth = this.clientWidth; //获取轮播区域的宽度

    let bannerBoxDom = $(self).children(".bannerBox")[0];
    $(self).children(".round").remove();

    // 充值banner 宽度
    if (bannerBoxDom) {
      const bannerDom = $(bannerBoxDom).children("li");
      let bannerLen = bannerDom.length;
      for (let index = 0; index < bannerLen; index += 1) {
        bannerDom[index].style.width = `${bannerWidth}px`;
      }
    }

    function animate(obj, target, callback) {
      clearInterval(obj.timer);//清除定时器防止定时器重复添加
      obj.timer = setInterval(function () {
        var step = (target - obj.offsetLeft) / 10; //定义一个步长，实现速度变化
        step = step > 0 ? Math.ceil(step) : Math.floor(step); //解决取整问题的bug
        // 解决浏览器缩小时 小于1px 浏览器不处理的问题
        const browserZoom = detectZoom();
        if (browserZoom && browserZoom < 100) {
          if (Math.abs(step * browserZoom) < 100) {
            step = step * 100 / browserZoom
            step = step > 0 ? Math.ceil(step) : Math.floor(step);
          }
        }
        if (obj.offsetLeft == target) {//判断运动距离与目标距离相等，停止运动
          clearInterval(obj.timer);
          if (callback) {
            callback();//如果有回调函数，执行回调函数
          }
        }
        obj.style.left = obj.offsetLeft + step + 'px'; //实现运动
      }, 15);
    }

    const detectZoom = function () {
      var ratio = 0, screen = window.screen, ua = navigator.userAgent.toLowerCase();

      if (window.devicePixelRatio !== undefined) {
        ratio = window.devicePixelRatio;
      } else if (~ua.indexOf('msie')) {
        if (screen.deviceXDPI && screen.logicalXDPI) {
          ratio = screen.deviceXDPI / screen.logicalXDPI;
        }
      } else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
        ratio = window.outerWidth / window.innerWidth;
      }

      if (ratio) {
        ratio = Math.round(ratio * 100);
      }

      return ratio;
    };

    // 设置鼠标进入，关闭定时器，停止滚动
    self.addEventListener('mouseover', function () {
      clearInterval(window.CustomCarouseltimer[_id]);
    })

    // 设置鼠标离开，开启定时器，开始滚动
    self.addEventListener('mouseout', function () {
      window.CustomCarouseltimer[_id] = setInterval(function () {
        nextDisplay();
      }, timeInterval)
    })

    // 设置面板指示点
    const round = document.createElement("ul");
    round.className = "round";
    round.style.position = "absolute";
    round.style.bottom = "10px";
    round.style.height = "10px";
    round.style.left = "50%";
    round.style.transform = "translateX(-50%)";
    round.style.listStyle = "none";
    self.appendChild(round);

    var length = $(bannerBoxDom).children("li:not(.clone)").length;
    for (var i = 0; i < length; i += 1) {
      var li = document.createElement('li');
      li.style.width = "10px";
      li.style.height = "10px";
      li.style.border = `1px solid ${dotBorderColor}`;
      li.style.borderRadius = "50%";
      li.style.float = "left";
      li.style.marginLeft = "10px";
      li.style.backgroundColor = dotBgColor;

      round.appendChild(li);//动态添加小圆圈，小圆圈个数跟随图片个数变化
      li.setAttribute('index', i);//设置自定义属性index
    }
    round.children[0].style.backgroundColor = dotCurrBgColor;

    var roundLi = round.children;
    for (var i = 0; i < roundLi.length; i++) {
      roundLi[i].addEventListener('click', function () {
        for (var i = 0; i < roundLi.length; i++) {////小圆圈点击事件，改变颜色和图片位置
          roundLi[i].className = '';
          roundLi[i].style.backgroundColor = dotBgColor;
        }//排他思想
        this.style.backgroundColor = dotCurrBgColor;
        var index = Number(this.getAttribute('index'));
        num = index;
        circle = index;
        var bannerWidth = self.offsetWidth;
        animate(bannerBoxDom, -index * bannerWidth);//利用index计算图片运动的距离，实现点击小圆圈的效果
      })
    }

    // 使用克隆增加一个li放在ul的最后面，实现无缝滚动的视觉效果
    $(bannerBoxDom).children(".clone").remove();
    var first = bannerBoxDom.children[0].cloneNode(true);//深克隆
    $(first).addClass("clone");
    bannerBoxDom.appendChild(first);

    var lengths = bannerBoxDom.children.length;
    bannerBoxDom.style.width = lengths * bannerWidth + 'px';

    // 鼠标点击前进按钮的点击事件
    var num = 0;
    var circle = 0;//控制小圆圈的变化
    var flag = true;
    const nextDisplay = function () {
      if (flag) { //flag节流阀防止动画运行过快
        flag = false;
        if (num == lengths - 1) {
          bannerBoxDom.style.left = 0;
          num = 0;//点击切换到最后一张的时候，位置拉回原始位置，重新赋值num
        }
        num += 1;
        animate(bannerBoxDom, -bannerWidth * num, function () {
          flag = true;
        });
        circle += 1;
        if (circle == length) {
          circle = 0;
        }
        circleChange();
      }
    }

    //把公共部分小圆圈变化封装成函数
    function circleChange() {
      for (var i = 0; i < roundLi.length; i++) {
        roundLi[i].className = '';
        roundLi[i].style.backgroundColor = dotBgColor;
      };
      roundLi[circle].style.backgroundColor = dotCurrBgColor;
    }

    //设置一个定时器
    window.CustomCarouseltimer[_id] = setInterval(function () {
      nextDisplay();//每两秒执行一次next的点击函数，实现定时轮播切换
    }, timeInterval)
  },

  onViewInit() {
    const comps = this.model.get('components');
    if (!comps.length) {
      comps.reset();
      comps.add(`
        <ul class="bannerBox" draggable="false">
          <li draggable="false"><div>轮播1</div></li>
          <li draggable="false"><div>轮播2</div></li>
          <li draggable="false"><div>轮播3</div></li>
        </ul>
      `)
    }

    this.updateScript();
    const evn = `
      change:timeInterval
      change:carouselWidth
      change:carouselHeight
      change:dotBgColor
      change:dotCurrBgColor
      change:dotBorderColor
    `
    this.listenTo(this.model, evn, this.updateScript);
    this.listenTo(this.model, evn, this.em.handleUpdates.bind(this.em));
    this.listenTo(this.em, 'update:component:style:height update:component:style:width', throttle.bind(this, this.updateScript.bind(this)));
  }
}
