// @ts-nocheck
import { App, defineComponent, onMounted, ref, reactive, toRaw } from 'vue';
import { initDatas } from './init'
import './index.css'

let timer = null
let timer1 = null
let timer2 = null
let timer3 = null

const RotationChart3d = defineComponent(()=> {
  let imgs = [
    'https://img2.baidu.com/it/u=923771995,3123797363&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
    'https://img1.baidu.com/it/u=1348924226,4183720365&fm=253&fmt=auto&app=120&f=JPEG?w=1200&h=750',
    'https://img1.baidu.com/it/u=3097007933,3775451098&fm=253&fmt=auto&app=120&f=JPEG?w=1200&h=750',
    'https://img0.baidu.com/it/u=1611332541,1083111576&fm=253&fmt=auto&app=120&f=JPEG?w=1024&h=640'
  ]
  
  let images = [
    { url: imgs[0], treeId: "point-tree", pointId: 'point', zIndex: 2 },
    { url: imgs[1], treeId: "point-r-tree", pointId: 'point-r', zIndex: 5 },
    { url: imgs[2], treeId: "point-f-tree", pointId: 'point-f', zIndex: 4 },
    { url: imgs[3], treeId: "point-l-tree", pointId: 'point-l', zIndex: 3 },
  ]
  
  let allTreeIds = ["#point-f-tree", "#point-r-tree", "#point-tree", "#point-l-tree"]
  let currentId = 1
  let looping = false
  
  // 设置位置
  function rotate(point, id) {
    let px = point.x + point.r * Math.cos(point.a); // <-- that's the maths you need
    let py = point.y + point.r * Math.sin(point.a);
  
    if (id && document.querySelector(id)) {
      document.querySelector(id).style.left = px + "px";
      document.querySelector(id).style.top = py + "px";
    }
  }
  
  // 运动轨迹正转
  let resetData = {}
  const move = (data, timer, directType) => {
    console.log('从' + data.a + '到' + data.move)
  
    let limit = data.move
    // 判断由正到负还是由负到正
    let direct = data.a < data.move
    // 运动
    // clearInterval(timer)
    // timer = setInterval(circleMove, 5);
  
    function circleMove() {
      let PI = Math.PI
      data.a = directType ? (data.a + PI / 360) % (PI * 2) : (data.a - PI / 360) % (PI * 2)
  
      let param = direct ? data.a >= limit : data.a <= limit
      if (param) {
        // 设置到初始位置
        data.a = data.move
        rotate(data, data.point);
        rotate(data, data.tree);
  
        // 结束后的位置
        resetData[data.id] = data
  
        // 全部转动完成之后
        if (Object.keys(resetData).length === 4) {
          resetInit({ ...toRaw(resetData) })
        }
        // clearInterval(timer)
      } else { // 设置定位转动
        rotate(data, data.point);
        rotate(data, data.tree);
        window.requestAnimationFrame(circleMove);
      }
    }
    window.requestAnimationFrame(circleMove);
  }
  
  // 初始化转动
  const init = (initData, direct) => {
    move(initData.Back, timer, direct)    // 后面
    move(initData.Right, timer3, direct)    // 右边
    move(initData.Left, timer1, direct)    // 左边
    move(initData.Front, timer2, direct)    // 前面
  }
  
  // 上一页
  const lastPage = () => {
    if (looping) {
      console.log('正在旋转中....')
      return
    }
    looping = true
  
    // 设置反向旋转规则
    let resetDataReverse = {}
    Object.keys(resetData).map((key) => {
      let d = resetData[key]
      if (d.a > 0 && d.a === 0.05) {
        d.a = d.move = -0.05
      } else if (d.a > 0 && d.a === 3.201) {
        d.a = d.move = -3.201
      } else if (d.a > 0 && d.a === 4.67) {
        d.a = d.move = -1.601
      } else if (d.a > 0 && d.a === 1.601) {
        d.a = d.move = -4.67
      }
      resetDataReverse[key] = d
    })
  
    startCircle('last')
  
    // console.log(resetDataReverse)
    let currentData = { ...toRaw(resetDataReverse) }
    let nextPositions = {
      '-4.67': -0.05, // 后
      '-0.05': -1.601, // 右
      '-1.601': -3.201, // 前
      '-3.201': -4.67, // 左
    }
    let newData = {}
    Object.keys(currentData).forEach((key) => {
      const item = currentData[key]
      newData[key] = {
        ...item,
        move: nextPositions[String(item.a)]
      }
    })
    init(newData)
  
    currentId = currentId - 1
    if (currentId < 0) {
      currentId = 3
    }
  }
  // 下一页
  const nextPage = () => {
    if (looping) {
      console.log('正在旋转中....')
      return
    }
    looping = true
  
    // 设置正向旋转规则
    let resetDataReverse = {}
    Object.keys(resetData).map((key) => {
      let d = resetData[key]
      if (d.a < 0 && d.a === -0.05) {
        d.a = d.move = 0.05
      } else if (d.a < 0 && d.a === -3.201) {
        d.a = d.move = 3.201
      } else if (d.a < 0 && d.a === -4.67) {
        d.a = d.move = 1.601
      } else if (d.a < 0 && d.a === -1.601) {
        d.a = d.move = 4.67
      }
      resetDataReverse[key] = d
    })
  
    startCircle('next')
  
    let currentData = { ...toRaw(resetData) }
    let nextPositions = {
      '4.67': 0.05, // 后
      '0.05': 1.601, // 右
      '1.601': 3.201, // 前
      '3.201': 4.67, // 左
    }
    let newData = {}
    Object.keys(currentData).forEach((key) => {
      const item = currentData[key]
      newData[key] = {
        ...item,
        move: nextPositions[String(item.a)]
      }
    })
    init(newData, true)
  
    currentId = currentId + 1
    if (currentId > 3) {
      currentId = 0
    }
  }
  // 转动停止后
  const resetInit = () => {
    //转动完成后设置前面图片的放大
    console.log(document.querySelector(`${allTreeIds[currentId]} img`))
    document.querySelector(`${allTreeIds[currentId]} img`).className = 'pointTTree'
    document.querySelector(`${allTreeIds[currentId]} .baseLineImg`).className = 'baseLineImg imgVisible'
  
    // 柱子层级调高
    const otherDom = allTreeIds.filter((t) => t !== allTreeIds[currentId])
    document.querySelector(`${otherDom[0]} .baseLineImg`).className = 'baseLineImg imgZIndex'
    document.querySelector(`${otherDom[1]} .baseLineImg`).className = 'baseLineImg imgZIndex'
    document.querySelector(`${otherDom[2]} .baseLineImg`).className = 'baseLineImg imgZIndex'
  
    setTimeout(() => {
      looping = false
    }, 300)
  }
  // 转动开始时
  const startCircle = (arg) => {
    const hasZoom = document.querySelector('img.pointTTree')
    const hasVisible = document.querySelector(`${allTreeIds[currentId]} .imgVisible`)
    if (hasZoom) {
      hasZoom.className = ''
      hasVisible.className = 'baseLineImg'
    }
  
    setIndexForLoop(arg)
  }
  
  const setIndexForLoop = (arg) => {
    let front = currentId
    let right = currentId + 1 > 3 ? 0 : currentId + 1
    let left = currentId - 1 < 0 ? 3 : currentId - 1
    let back = right + 1 > 3 ? 0 : right + 1
  
    // 转动时柱子调高层级
    allTreeIds.forEach((dom) => {
      document.querySelector(`${dom} .baseLineImg`).className = 'baseLineImg'
    })
  
    let direct = [back, left, front, right]
    if (arg === 'next') {    // 转动时图片层级按 右 前 左 后调层级
      direct = [back, left, front, right]
    }
  
    if (arg === 'last') {    // 转动时图片层级按 左 前 后 右调层级
      direct = [right, back, front, left]
    }
    direct.forEach((d, i) => {
      document.querySelector(`${allTreeIds[d]} .baseLineUrl img`).style.zIndex = 2 + i
    })
  }
  
  const updateRequest = () => {
    var lastTime = 0;
      var vendors = ['ms', 'moz', 'webkit', 'o'];
      for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
          window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
          window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame'];
      }
      if (!window.requestAnimationFrame) window.requestAnimationFrame = function(callback, element) {
          var currTime = new Date().getTime();
          var timeToCall = Math.max(0, 16 - (currTime - lastTime));
          var id = window.setTimeout(function() {
              callback(currTime + timeToCall);
          }, timeToCall);
          lastTime = currTime + timeToCall;
          return id;
      };
      if (!window.cancelAnimationFrame) window.cancelAnimationFrame = function(id) {
          clearTimeout(id);
      };
  }
  
  onMounted(() => {
    updateRequest()
    
    let initData = initDatas
    init(initData, true)
  })

  return ()=><div class="loopScreen">
    <button onClick={lastPage}>上一页</button>
    <button onClick={nextPage}>下一页</button>
    <div class="baseBottom">
      <div class="baseCircle">
        <div id="point"></div>
        <div id="point-r"></div>
        <div id="point-l"></div>
        <div id="point-f"></div>
      </div>
      <div class="baseCircleTree">
        {
          images.map((item, index)=> {
            return <div id={item.treeId} key={index} class="baseLine">
              <div class="baseLineImg"></div>
              <div class="baseLinePoint"></div>
              <div class="baseLineUrl">
                <img class="" src={item.url} alt="" style={{ 'z-index': item.zIndex }} />
              </div>
            </div>
          })
        } 

      </div>
    </div>
  </div>
});

RotationChart3d.install = (app: App) => {
  app.component(RotationChart3d.name, RotationChart3d);
};

export default RotationChart3d;
