<template>
  <Zoom :size="size" :name="name" :onlyClass="onlyClass" :config="config">
    <div class="loopScreen Application-container">
      <!-- <button @click="lastPage">上一页1</button> -->
      <!-- <button @click="nextPage">下一页</button> -->
      <div class="baseBottom">
        <div class="baseCircle">
          <div class="point"></div>
          <div class="point-r"></div>
          <div class="point-l"></div>
          <div class="point-f"></div>
        </div>
        <div class="baseCircleTree">
          <div
            :class="item.treeId"
            v-for="(item, index) in images"
            :key="index"
            class="baseLine"
            @click="() => rotatePoint(item.treeId)"
          >
            <div class="baseLineImg"></div>
            <div class="baseLinePoint"></div>
            <div class="baseLineUrl">
              <img
                class=""
                :src="item.url ? item.url : Image"
                alt=""
                :style="{ 'z-index': item.zIndex }"
              />
            </div>
          </div>
        </div>
        <div
          class="baseInfoTag"
          v-for="(item, index) in knowledgeList"
          :key="index"
        >
          <div
            :class="'baseInfoTag-content ' + item.className"
            @click="handelClick(item)"
            v-if="index <= 2"
          >
            <span class="baseInfoTag-text" :title="item.content">{{
              item.content
            }}</span>
            <i class="rectangle-icon"></i>
          </div>
        </div>
        <div class="baseInfoTag">
          <div class="baseInfoTag-content bottom">
            <div class="title" @click="titleClick(frontText)">
              <span :title="frontText.title">{{ frontText.title }}</span>
              <i class="rectangle-icon"></i>
            </div>
            <div class="content">
              {{ frontText.frontText }}
            </div>
            <div class="count">
              <div class="rectangle-text">
                <span class="rectangle-count-icon"></span>
                <span class="rectangle-count">{{ frontText.count }}</span>
              </div>
              <i class="rectangle-icon1"></i>
            </div>
          </div>
        </div>
      </div>
    </div>
  </Zoom>
</template>
<script setup lang="ts">
/* eslint-disable */
import {
  reactive,
  toRaw,
  ref,
  getCurrentInstance,
  onMounted,
  defineProps,
  computed,
} from "vue";
import {
  frontTextDefault,
  knowledgeListDefault,
  imagesDefault,
  initDataDefault,
} from "./rotationChart";
import Zoom from "./zoom.vue";
import Image from "./default.png";
import request from "../../utils/request";

const props = defineProps({
  moduleId: String,
  size: {
    type: Object,
    default: () => ({}),
  },
  config: {
    type: Object,
    default: () => ({}),
  },
  propValue: {
    type: Object,
    default: () => ({}),
  },
});

const name = computed(() => {
  return props.config.component;
})

// const groups = ['basics', 'window'];
let convertToken = ref("");
let metaData = ref([]);
let imgs = ref([]);

let frontText = ref(frontTextDefault);
let knowledgeList = ref(knowledgeListDefault);
let images = ref(imagesDefault);

let allTreeIds = [
  ".point-f-tree",
  ".point-r-tree",
  ".point-tree",
  ".point-l-tree",
];
let currentId = ref(1);
let looping = ref(false);

let initDatas = reactive(initDataDefault);

// 运动轨迹正转
let resetData = reactive({});
const move = (data, directType) => {
  console.log("从" + data.a + "到" + data.move);

  let limit = data.move;
  // 判断由正到负还是由负到正
  let direct = data.a < data.move;

  function circleMove() {
    let PI = Math.PI;
    data.a = directType
      ? ((data.a + PI / 360) % (PI * 2)) + 0.01
      : ((data.a - PI / 360) % (PI * 2)) - 0.01;

    let param = direct ? Math.ceil(data.a*10000) >= Math.ceil(limit*10000) : Math.ceil(data.a*10000) <= Math.ceil(limit*10000);

    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) });
      }
    } else {
      // 设置定位转动
      rotate(data, data.point);
      rotate(data, data.tree);
      window.requestAnimationFrame(circleMove);
    }
  }

  window.requestAnimationFrame(circleMove);
};

let onlyClass = ref('chart3d-' + props.moduleId)

const 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);
  let dom = document.querySelector(`.${onlyClass.value} ${id}`)
  if (id && dom) {
    dom.style.left = px + "px";
    dom.style.top = py + "px";
  }
}

// 初始化转动
const init = (initData: any, direct: Boolean) => {
  move(initData.Back, direct); // 后面
  move(initData.Right, direct); // 右边
  move(initData.Left, direct); // 左边
  move(initData.Front, direct); // 前面
  onlyClass.value = 'chart3d-' + props.moduleId
};

// 上一页
const lastPage = () => {
  if (looping.value) {
    console.log("正在旋转中....");
    return;
  }
  looping.value = 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.71) {
      d.a = d.move = -1.601;
    } else if (d.a > 0 && d.a === 1.601) {
      d.a = d.move = -4.71;
    }
    resetDataReverse[key] = d;
  });

  startCircle("last");

  // console.log(resetDataReverse)
  let currentData = { ...toRaw(resetDataReverse) };
  let nextPositions = {
    "-4.71": -0.05, // 后
    "-0.05": -1.601, // 右
    "-1.601": -3.201, // 前
    "-3.201": -4.71, // 左
  };
  let newData = {};
  Object.keys(currentData).forEach((key) => {
    const item = currentData[key];
    newData[key] = {
      ...item,
      move: nextPositions[String(item.a)],
    };
  });
  init(newData, false);

  currentId.value = currentId.value - 1;
  if (currentId.value < 0) {
    currentId.value = 3;
  }
};
// 下一页
const nextPage = () => {
  if (looping.value) {
    console.log("正在旋转中....");
    return;
  }
  looping.value = 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.71) {
      d.a = d.move = 1.601;
    } else if (d.a < 0 && d.a === -1.601) {
      d.a = d.move = 4.71;
    }
    resetDataReverse[key] = d;
  });

  startCircle("next");

  let currentData = { ...toRaw(resetData) };
  let nextPositions = {
    4.71: 0.05, // 后
    0.05: 1.601, // 右
    1.601: 3.201, // 前
    3.201: 4.71, // 左
  };
  let newData = {};
  Object.keys(currentData).forEach((key) => {
    const item = currentData[key];
    newData[key] = {
      ...item,
      move: nextPositions[String(item.a)],
    };
  });
  init(newData, true);

  currentId.value = currentId.value + 1;
  if (currentId.value > 3) {
    currentId.value = 0;
  }

  textChange();
};

// 设置前面文字颜色和文字
const setFrontText = (frontArticleObj) => {
  frontText.value = { ...frontArticleObj };
  frontText.value.title = frontArticleObj.content;
  frontText.value.frontText = frontArticleObj.summary;
  frontText.value.count = frontArticleObj.isLike <= 999 ? frontArticleObj.isLike : '999+';
  frontText.value.url = frontArticleObj.url;
};

// 顺时针转动设置文字
const textChange = () => {
  let front = currentId.value;
  let right = currentId.value + 1 > 3 ? 0 : currentId.value + 1;
  let left = currentId.value - 1 < 0 ? 3 : currentId.value - 1;
  let back = right + 1 > 3 ? 0 : right + 1;

  const kClone = toRaw(knowledgeList.value);
  knowledgeList.value = [
    {
      ...kClone[1],
      className: "top",
    },
    {
      ...kClone[3],
      className: "left",
    },
    {
      ...kClone[0],
      className: "right",
    },
    {
      ...kClone[2],
      className: "front",
    },
  ];
  setFrontText(knowledgeList.value[3]);
};

// 转动停止后
const resetInit = () => {
  console.log("转动完成=======");

  //转动完成后设置前面图片的放大
  let imageDom: Element | any = document.querySelector(`.${onlyClass.value} ${allTreeIds[currentId.value]} img`)
  imageDom.className = "pointTTree";
  let lineDom: Element | any = document.querySelector(`.${onlyClass.value} ${allTreeIds[currentId.value]} .baseLineImg`)
  lineDom.className = "baseLineImg imgVisible";

  // 柱子层级调高
  const otherDom = allTreeIds.filter((t) => t !== allTreeIds[currentId.value]);
  const baseLineDom0: Element | any = document.querySelector(`.${onlyClass.value} ${otherDom[0]} .baseLineImg`)
  baseLineDom0.className ="baseLineImg imgZIndex";
  const baseLineDom1: Element | any = document.querySelector(`.${onlyClass.value} ${otherDom[1]} .baseLineImg`)
  baseLineDom1.className = "baseLineImg imgZIndex";
  const baseLineDom2: Element | any = document.querySelector(`.${onlyClass.value} ${otherDom[2]} .baseLineImg`)
  baseLineDom2.className = "baseLineImg imgZIndex";
  setTimeout(() => {
    looping.value = false;

    document.querySelectorAll(`.${onlyClass.value} .baseInfoTag`).forEach((dom: Element | any) => {
      dom.style.display = "block";
    });
  }, 300);
};

// 转动开始时
const startCircle = (arg) => {
  document.querySelectorAll(`.${onlyClass.value} .baseInfoTag`).forEach((dom) => {
    dom.style.display = "none";
  });

  const hasZoom = document.querySelector(`.${onlyClass.value} img.pointTTree`);
  const hasVisible = document.querySelector(
    `.${onlyClass.value} ${allTreeIds[currentId.value]} .imgVisible`
  );

  if (hasZoom) {
    hasZoom.className = "";
    hasVisible.className = "baseLineImg";
  }

  setIndexForLoop(arg);
};

const setIndexForLoop = (arg: string) => {
  let front = currentId.value;
  let right = currentId.value + 1 > 3 ? 0 : currentId.value + 1;
  let left = currentId.value - 1 < 0 ? 3 : currentId.value - 1;
  let back = right + 1 > 3 ? 0 : right + 1;

  // 转动时柱子调高层级
  allTreeIds.forEach((dom) => {
    let domE: Element | any = document.querySelector(`.${onlyClass.value} ${dom} .baseLineImg`)
    domE.className = "baseLineImg";
  });

  let direct = [back, left, front, right];
  if (arg === "next") {
    // 转动时图片层级按 右 前 左 后调层级
    direct = [back, left, front, right];
  }

  if (arg === "last") {
    // 转动时图片层级按 左 前 后 右调层级
    direct = [right, back, front, left];
  }

  // console.log(direct, 'uuuuuuuuuuuuuuuuu')

  direct.forEach((d, i) => {
    // console.log(allTreeIds[d], 2 + i)
    // document.querySelector(`${allTreeIds[d]} .baseLineUrl img`).style.zIndex = 2 + i;
    const idx = images.value.findIndex((item) =>
      allTreeIds[d].includes(item.treeId)
    );
    images.value[idx].zIndex = 2 + i;
  });
};

// 干掉图片上的文字
const clearImageText = () => {
  document.querySelectorAll(`.${onlyClass.value} .baseInfoTag`).forEach((dom) => {
    dom.style.display = "none";
  });
};

const rotatePoint = (id) => {
  let left = currentId.value - 1;
  if (currentId.value - 1 < 0) {
    left = 3;
  }
  // let right = currentId.value + 1;
  // if (currentId.value + 1 > 3) {
  //   right = 0;
  // }

  if (allTreeIds[left].includes(id)) {
    lastPage();
  } else {
    nextPage();
  }
  setTimeout(() => {
    const dom = document.querySelector(`.${onlyClass.value} ${allTreeIds[currentId.value]}`);
    console.log(dom);
  });
};

const dom = getCurrentInstance();
const handelClick = (item) => {
  dom.appContext.config.globalProperties.$workspace.openWithTab({
    url:
      item.url.split("#/")[0] +
      `?access_token=${convertToken.value}#/` +
      item.url.split("#/")[1],
    caption: "知识地图",
    id: workspaceId.kmsatlas,
  });
};
const titleClick = (item) => {
  console.log(item);
  dom.appContext.config.globalProperties.$workspace.openWithTab({
    url:
      item.url.split("#/")[0] +
      `?access_token=${convertToken.value}#/` +
      item.url.split("#/")[1],
    caption: "知识地图",
    id: workspaceId.kmsatlas,
  });
};

// 初始化设置数据和图片
const setInitData = (kMapData) => {
  metaData.value = kMapData.data;

  knowledgeList.value = [
    {
      content: kMapData.data[2].articleTitle,
      className: "top",
      ...kMapData.data[2],
    },
    {
      content: kMapData.data[3].articleTitle,
      className: "left",
      ...kMapData.data[3],
    },
    {
      content: kMapData.data[1].articleTitle,
      className: "right",
      ...kMapData.data[1],
    },
    {
      content: kMapData.data[0].articleTitle,
      className: "front",
      ...kMapData.data[3],
    },
  ];

  // 设置背景图
  images.value.forEach((item, index) => {
    images.value[index].url = knowledgeList.value[index].imgUrl;
    //  + `&access_token=${convertToken.value}`;
  });
  setFrontText(knowledgeList.value[3]);
};
let allUrl = ref(JSON.parse(localStorage.getItem("visualDomain"))?.all);
let kmsUrl = ref(JSON.parse(localStorage.getItem("visualDomain"))?.kms);
let getKnowledgeMap = (params) => {
  return request({
    url:
      kmsUrl.value + "/kms-visual-portal-service/visual-kmap/getKnowledgeMap",
    method: "GET",
    params,
  });
};

onMounted(async () => {
  clearImageText();

  // const convertTokenFun = await ComponentService.convertToken2();
  let isInit = false
  const kMapData = await getKnowledgeMap({
    author: "",
    classify: "",
    current: 1,
    department: "",
    latitudeId: "",
    mapName: "",
    publicTimeBegin: "",
    publicTimeEnd: "",
    size: 10,
  }).catch((err) => {
    init(initDatas, true);
    isInit = true
  });

  if (kMapData && kMapData.data) {
    if (kMapData.data.length >= 4) {
      console.log('=====', kMapData)
      setInitData(kMapData);
    } else {
      let result = [];
      console.log(kMapData.data);
      [1, 2, 3, 4].forEach((item, index) => {
        console.log(index);
        if (kMapData.data[index]) {
          result.push(kMapData.data[index]);
        } else {
          result.push({
            articleTitle: "暂无",
          });
        }
      });
      setInitData({ data: result });
    }
  }
  // else{
  //   let result = [];
  //   [1, 2, 3, 4].forEach((item, index) => {
  //     result.push({
  //       articleTitle: "暂无",
  //       imgUrl: ""
  //     });
  //   })
  //   setInitData({ data: result });
  // }

  !isInit && init(initDatas, true);
});

// watch(()=> props.size, (val)=> {
//   console.log(val, '333333333333333333333333')
// })
</script>

<style>
/* body {
  width: 100%;
  min-height: 100vh;
  background: linear-gradient(0deg, #CFDEEE, #AACBEA);
} */

.item {
  width: 380px;
  height: 260px;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.item img {
  width: 100%;
  height: auto;
}

.item .caption {
  position: absolute;
  font-weight: bold;
  bottom: 5px;
}

/* 下面是 轮播图有关的样式 */
.loopScreen {
  display: flex;
  justify-content: center;
  /* align-items: center; */
  position: absolute;
  /* width: 934px;
  height: 487px; */
  width: 100%;
  height: 100%;
  /* top: 423px; */
  /* left: 12px; */
  overflow: hidden;

}

.loopScreen .item {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  transition: all 0.5s ease-out;
}

.loopScreen .baseBottom {
  position: relative;
  left: 0px;
  top: 266px;
  background: url(/srcDev/assets/images/baseImg.png) no-repeat center center;
  width: 928px;
  height: 224px;
  /* height: 46%; */
}

.loopScreen .baseBottom .baseCircle {
  position: absolute;
  top: -240px;
  left: 146px;
  /* border: 1px solid; */
  border-radius: 1000px;
  width: 642px;
  /* height: 642px; */
  width: 69%;
  transform: translate3d(0px, 0px, 0px) translate(0%, 0%)
    rotate3d(1, 0, 0, 79deg);
}

.loopScreen .baseBottom .baseCircle .point {
  position: absolute;
  left: 0px;
  top: 0px;
  /* background: red; */
  width: 5px;
  height: 10px;
  border-radius: 10px;
}

.loopScreen .baseBottom .baseCircleTree {
  position: absolute;
  top: -240px;
  left: 146px;
  width: 642px;
  height: 642px;
  width: 69%;
  transform: translate3d(0px, 0px, 0px) translate(0%, 0%)
    rotate3d(1, 0, 0, 79deg);
  top: -107%;
  left: 16%;
}

.loopScreen .baseBottom .baseCircleTree .baseLine {
  position: absolute;
  left: 0px;
  top: 40px;
}

.loopScreen .baseBottom .baseCircleTree .baseLine .baseLineImg {
  background: url(/srcDev/assets/images/line.png) no-repeat;
  background-size: 100% 100%;
  width: 41px;
  height: 873px;
  position: relative;
  top: -731px;
  left: -20px;
  /* top: -45%;
  left: -8%; */
}

.imgVisible {
  visibility: hidden;
}

.imgZIndex {
  z-index: 5;
}

.imgZIndexS {
  z-index: 1;
}

.loopScreen .baseBottom .baseCircleTree .point-tree img,
.loopScreen .baseBottom .baseCircleTree .point-r-tree img,
.loopScreen .baseBottom .baseCircleTree .point-l-tree img,
.loopScreen .baseBottom .baseCircleTree .point-f-tree img {
  width: 226px;
  max-width: 226px;
  height: 742px;
  position: relative;
  display: inline-block;
  top: -2319px;
  left: -114px;
  background: #fff;
  padding: 8px 2px;
  border-radius: 10px 10px 10px 10px/40px 40px 40px 40px;
  transition: all 0.5s;
}
/* #point-r-tree img {
  z-index: 10;
} */

img.pointTTree {
  transition: all 0.5s;
  top: -2033px !important;
  width: 308px !important;
  max-width: 308px !important;
  left: -149px !important;
  height: 925px !important;
  z-index: 10 !important;
  padding: 23px 4px !important;
}
.baseInfoTag {
  width: 50%;
  background-repeat: no-repeat;
  margin-right: 19px;
  /* box-shadow: 0px 8px 12px 1px rgba(9,53,93,.34); */
  position: relative;
}
.baseInfoTag-content {
  width: 232px;
  height: 32px;
  background: rgba(0, 0, 0, 0.5);
  color: #ffff;
  font-size: 16px;
  position: absolute;
  bottom: 0;
  display: flex;
  align-items: center;
  font-family: alibaba-r;
  border-bottom-right-radius: 10px;
  border-bottom-left-radius: 10px;
  overflow: hidden;
  cursor: pointer;
}
.baseInfoTag-content span {
  margin-left: 16px;
  font-size: 16px;
  font-family: Alibaba-R;
  font-weight: 500;
  color: #fff;
}
.baseInfoTag-content.top {
  position: absolute;
  top: -148px;
  left: 353px;
  width: 226px !important;
}

.baseInfoTag-content.top span.baseInfoTag-text,
.baseInfoTag-content.right span.baseInfoTag-text,
.baseInfoTag-content.left span.baseInfoTag-text {
  position: absolute;
  left: 0px;
  top: 5px;
  animation-name: moveExamTop;
  animation-duration: 1s;
  display: inline-block;
  width: 90%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: left;
}
@keyframes moveExamTop {
  0% {
    left: -100px;
    top: 5px;
  }
  100% {
    left: 0px;
    top: 5px;
  }
}

.baseInfoTag-content.bottom {
  top: -77px;
  left: 311px;
  width: 304px !important;
  height: 168px;
  display: block;
  /* animation-name: moveExamBottom;
  animation-duration: 1s; */
  border-radius: 5px;
}
.baseInfoTag-content.bottom .title {
  width: 100%;
  display: block;
  position: absolute;
  top: 23px;
}
@keyframes moveExamLeft {
  0% {
    left: -100px;
    top: 23px;
  }
  100% {
    left: 0px;
    top: 23px;
  }
}
.baseInfoTag-content.bottom .title span {
  font-size: 18px;
  font-weight: 500;
  color: #ffffff;

  display: inline-block;
  animation-name: moveExamLeft;
  animation-duration: 1s;
  width: 95%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: left;
}
.baseInfoTag-content.bottom .content {
  display: block;
  position: absolute;
  top: 86px;
  padding: 0 12px;
  font-weight: 500;
  font-size: 14px;
  color: #e6f0f9;
  font-family: alibaba-r;
  animation-name: moveExamLeft;
  animation-duration: 1s;
}
@keyframes moveExamLeft {
  0% {
    left: -100px;
    top: 86px;
  }
  100% {
    left: 0px;
    top: 86px;
  }
}

.baseInfoTag-content.left {
  top: -91px;
  left: 33px;
  width: 226px !important;

  /* animation-name: moveExamLeft;
  animation-duration: 1s; */
}
.baseInfoTag-content.right {
  position: absolute;
  top: -84px;
  left: 675px;
  width: 226px !important;
  z-index: 0;
  /* 
  animation-name: moveExamRight;
  animation-duration: 1s; */
}
.rectangle-icon {
  width: 5px;
  height: 21px;
  background-image: url(/srcDev/assets/images/rectangle1.png);
  position: absolute;
  left: 0;
}
.rectangle-text {
  width: 54px;
  height: 26px;
  position: absolute;
  right: 7px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.rectangle-text span {
  margin-left: 5px;
}

.rectangle-count {
  /* position: absolute; */
  right: 7px;
  color: #ff4e4a !important;
  z-index: 10;
}
.rectangle-count-icon {
  width: 11px;
  height: 14px;
  background-image: url(/srcDev/assets/images/fire.png);
  /* position: absolute; */
  right: 39px;
  z-index: 18;
  background-repeat: no-repeat;
  top: 4px;
}
.rectangle-icon1 {
  width: 93px;
  height: 28px;
  background-image: url(/srcDev/assets/images/circle.png);
  position: absolute;
  right: 0;
  background-repeat: no-repeat;
  top: -1px;
}
</style>
