<template>
  <section class="cloud-bed" :style="{ 'background-image': `url('${url}')` }">
    <div class="cloud-box">
      <span
        v-for="(item, index) in dataList"
        :key="index"
        @click="getDataInfo(item)"
        :style="{ color: item.color }"
        :class="{ active: active1 == item.name }"
      >
        {{ item.name }}
      </span>
    </div>
  </section>
</template>

<script>
import url from '/src/assets/images/词云图.png';
import { useGeologicalStore } from '/@/store/modules/geological';
import eventBus from '/@/utils/eventBus';
import { getStrUnicode } from '/@/utils/fnUtils';
import tFMapUitl from '../../../utils/TFMapUitl';
var list = [];
export default {
  name: 'WordCloud',
  data() {
    return {
      url, //背景图
      timer: null, // 球体转动速率
      radius: 0, // 词云球体面积大小
      dtr: Math.PI / 180, //鼠标滑过球体转动速度
      active: false, // 默认加载是否开启转动
      lasta: 0, // 上下转动
      lastb: 2.0, // 左右转动
      distr: true,
      tspeed: 0, // 鼠标移动上去时球体转动
      mouseX: 0,
      mouseY: 0,
      tagAttrList: [],
      tagContent: null,
      cloudContent: null,
      sinA: '',
      cosA: '',
      sinB: '',
      cosB: '',
      sinC: '',
      cosC: '',
      dataList: [],
      active1: '',
    };
  },
  mounted() {
    this.$nextTick(async () => {
      await this.GetDzRiskTypeList(); //必须同步请求数据，页面才能渲染
      this.radius = document.querySelector('.cloud-box').offsetWidth / 2;
      this.initWordCloud();
    });
  },

  // // 监听active
  // watch: {
  //   active: {
  //     handler(newValue, oldValue){
  //     if(oldValue == newValue){
  //       this.active1 = ''
  //     }
  //   },
  //   // deep: true,
  //   // immediate: true
  //   }
  // },

  beforeUnmount() {
    if (!this.timer) return;
    cancelAnimationFrame(this.timer.id);
  },
  methods: {
    // 请求地灾类型数据
    GetDzRiskTypeList() {
      const geologicalStore = useGeologicalStore();
      return new Promise((resolve) => {
        resolve(
          geologicalStore.GetDzRiskTypeList().then((res) => {
            this.dataList = res;
            var colorList = ['#8E9757', '#64B4FF', '#59EAB7', '#D99C33', '#01AAB9', '#01AAB0', '#01AAB2'];
            let valueTotal = 0;
            for (let i = 0; i < this.dataList.length; i++) {
              this.dataList[i].name1 = this.dataList[i].name;
              this.dataList[i].name = this.dataList[i].name + '(' + this.dataList[i].value + ')';
              this.dataList[i].color = colorList[i];

              valueTotal += this.dataList[i].value;
            }
            console.log('地灾数据', this.dataList);
            this.$emit('getDzTypeTotal', this.dataList.length, valueTotal);
          })
        );
      });
    },
    // 获取点击文本信息
    getDataInfo(item) {
      console.log('词云点击：', item);
      this.active1 = this.active1 == item.name ? '' : item.name;
      eventBus.emit('sayHi', item.dzlxid);
      if (list.length) list.map((i) => i.update());
      list = map.findOverlay(getStrUnicode(item.name1) + '*');
      if (list.length) list.map((i) => i.update()), map.flyToRectangle(list), tFMapUitl.addBw(map, list);
    },

    initWordCloud() {
      this.cloudContent = document.querySelector('.cloud-box');
      this.tagContent = this.cloudContent.getElementsByTagName('span');
      for (let i = 0; i < this.tagContent.length; i++) {
        let tagObj = {};
        tagObj.offsetWidth = this.tagContent[i].offsetWidth;
        tagObj.offsetHeight = this.tagContent[i].offsetHeight;
        this.tagAttrList.push(tagObj);
      }
      this.sineCosine(0, 0, 0);
      this.positionAll();
      // this.timer = setInterval(this.update, 50)
      this.timer = setAnimationFrame(() => {
        this.update();
      }, 120);
      function setAnimationFrame(render, time) {
        var nowTime = 0;
        var lastTime = Date.now();
        var diffTime = time;
        var timer = {};
        function animloop() {
          nowTime = Date.now();
          if (nowTime - lastTime > diffTime) {
            lastTime = nowTime;
            render();
          }
          timer.id = requestAnimationFrame(animloop);
        }
        animloop();
        return timer;
      }
    },
    positionAll() {
      let phi = 0;
      let theta = 0;
      let max = this.tagAttrList.length;
      let aTmp = [];
      let oFragment = document.createDocumentFragment();
      //随机排序
      for (let i = 0; i < this.tagContent.length; i++) {
        aTmp.push(this.tagContent[i]);
      }
      aTmp.sort(() => {
        return Math.random() < 0.5 ? 1 : -1;
      });
      for (let i = 0; i < aTmp.length; i++) {
        oFragment.appendChild(aTmp[i]);
      }
      this.cloudContent.appendChild(oFragment);
      for (let i = 1; i < max + 1; i++) {
        if (this.distr) {
          phi = Math.acos(-1 + (2 * i - 1) / max);
          theta = Math.sqrt(max * Math.PI) * phi;
        } else {
          phi = Math.random() * Math.PI;
          theta = Math.random() * (2 * Math.PI);
        }
        //坐标变换
        this.tagAttrList[i - 1].cx = this.radius * Math.cos(theta) * Math.sin(phi);
        this.tagAttrList[i - 1].cy = this.radius * Math.sin(theta) * Math.sin(phi);
        this.tagAttrList[i - 1].cz = this.radius * Math.cos(phi);
        this.tagContent[i - 1].style.left =
          this.tagAttrList[i - 1].cx + this.cloudContent.offsetWidth / 2 - this.tagAttrList[i - 1].offsetWidth / 2 + 'px';
        this.tagContent[i - 1].style.top =
          this.tagAttrList[i - 1].cy + this.cloudContent.offsetHeight / 2 - this.tagAttrList[i - 1].offsetHeight / 2 + 'px';
      }
    },
    update() {
      let angleBasicA;
      let angleBasicB;
      angleBasicA = this.lasta * 0.98;
      angleBasicB = this.lastb * 0.98;
      this.sineCosine(angleBasicA, angleBasicB, 0);
      for (let j = 0; j < this.tagAttrList.length; j++) {
        let rx1 = this.tagAttrList[j].cx;
        let ry1 = this.tagAttrList[j].cy * this.cosA + this.tagAttrList[j].cz * -this.sinA;
        let rz1 = this.tagAttrList[j].cy * this.sinA + this.tagAttrList[j].cz * this.cosA;

        let rx2 = rx1 * this.cosB + rz1 * this.sinB;
        let ry2 = ry1;
        let rz2 = rx1 * -this.sinB + rz1 * this.cosB;

        let rx3 = rx2 * this.cosC + ry2 * -this.sinC;
        let ry3 = rx2 * this.sinC + ry2 * this.cosC;
        let rz3 = rz2;
        this.tagAttrList[j].cx = rx3;
        this.tagAttrList[j].cy = ry3;
        this.tagAttrList[j].cz = rz3;

        let per = 350 / (350 + rz3);

        this.tagAttrList[j].x = rx3 * per - 2;
        this.tagAttrList[j].y = ry3 * per;
        this.tagAttrList[j].scale = per;
        this.tagAttrList[j].alpha = per;

        this.tagAttrList[j].alpha = (this.tagAttrList[j].alpha - 0.6) * (10 / 6);
      }
      this.doPosition();
      this.depthSort();
    },
    doPosition() {
      let len = this.cloudContent.offsetWidth / 2;
      let height = this.cloudContent.offsetHeight / 2;
      for (let i = 0; i < this.tagAttrList.length; i++) {
        this.tagContent[i].style.left = (this.tagAttrList[i].cx + len - this.tagAttrList[i].offsetWidth / 3) / 3 + 'px';
        this.tagContent[i].style.top = (this.tagAttrList[i].cy + height - this.tagAttrList[i].offsetHeight / 2) / 2 / 2 + 'px';
        // this.tagContent[i].style.fontSize = Math.ceil((14 * this.tagAttrList[i].scale) / 2) + 3 + 'px'
        this.tagContent[i].style.filter = 'alpha(opacity=' + 100 * this.tagAttrList[i].alpha + ')';
        this.tagContent[i].style.opacity = this.tagAttrList[i].alpha;
      }
    },
    depthSort() {
      let aTmp = [];
      for (let i = 0; i < this.tagContent.length; i++) {
        aTmp.push(this.tagContent[i]);
      }
      aTmp.sort((item1, item2) => item2.cz - item1.cz);
      for (let i = 0; i < aTmp.length; i++) {
        aTmp[i].style.zIndex = i;
      }
    },
    sineCosine(a, b, c) {
      this.sinA = Math.sin(a * this.dtr);
      this.cosA = Math.cos(a * this.dtr);
      this.sinB = Math.sin(b * this.dtr);
      this.cosB = Math.cos(b * this.dtr);
      this.sinC = Math.sin(c * this.dtr);
      this.cosC = Math.cos(c * this.dtr);
    },
  },
};
</script>

<style scoped>
.cloud-bed {
  width: 375px /* 354/192 */;
  height: 220px /* 245/192 */;
  margin: auto;
  margin-left: 10px;
  background-size: 90% 85% !important;
  background: no-repeat;
  position: relative;
  font-size: 30px;
}

.cloud-box {
  position: relative;
  left: 15%;
  top: 90px /* 120/192 */;
  bottom: 0;
  margin: 0 auto;
}

.cloud-box span {
  position: absolute;
  padding: 3px /* 3/192 */ 6px /* 6/192 */;
  top: 0;
  font-weight: bold;
  font-size: 16px /* 16/192 */;
  text-decoration: none;
  left: 0;
  /* background-image: linear-gradient(to bottom, red, #fff); */
  background-clip: text;
  color: transparent;
  /* width: 110px */
  /* 110/192 */
  height: 50px /* 50/192 */;
  border-radius: 50%;
  text-align: center;

  display: flex;
  align-items: center;
  justify-content: center;

  /* line-height: 50px;
      overflow:hidden;
      white-space: nowrap;
      text-overflow: ellipsis; */
}

.active {
  /* background: #fd7522; */
  font-size: 26px !important;
  /* border: 1px solid #fd7522;
  color: #fff; */
}
</style>
