<template>
  <div class="layoutBox ts-zyl">
    <div class="control">
      <span>{{ TSTYOBJ.store.parseTime(TSTYOBJ.store.currentTimestamp) }}</span>
      <!--<span>{{ TSTYOBJ.store.currentTimestamp }}</span>-->
      <!--      <button :disabled="TSTYOBJ.editorMode.PLAYING==TSTYOBJ.store.editorMode" @click="play">play</button>
            <button :disabled="TSTYOBJ.editorMode.EDITING==TSTYOBJ.store.editorMode" @click="stop">stop</button>-->
      <div class="btn">
        <svg
            :aria-disabled="true"
            v-if="TSTYOBJ.clock.status==TSTYOBJ.timeStatus.STOP||TSTYOBJ.clock.status==TSTYOBJ.timeStatus.PAUSE"
            class="icon icon-bofang"
            aria-hidden="true"
            @click="play"
        >
          <use xlink:href="#icon-bofang"></use>
        </svg>
        <svg
            v-else
            class="icon icon-bofang"
            aria-hidden="true"
            @click="pause"
        >
          <use xlink:href="#icon-zanting"></use>
        </svg>
        <!---->
        <svg
            :class="['icon' ,'icon-zhongzhi']"
            aria-hidden="true"
            @click=" ()=>{stop()}">
          <use xlink:href="#icon-zhongzhi"></use>
        </svg>
      </div>
      <div
          :class="[(TSTYOBJ.clock.status==TSTYOBJ.timeStatus.PLAY&&TSTYOBJ.store.editorMode==TSTYOBJ.editorMode.PLAYING)?'disabledBtn':'','multiple']"
          @click="openMultiple">
        <!--新增25-->
        倍数×{{ TSTYOBJ.store.multiplier }}
      </div>
    </div>
    <div class="layoutBoxs">
      <div class="layout">
        <Grid :Store="TSTYOBJ.store"></Grid>
        <div class="TLContainer">
          <div class="timelineCursorBox" :style="cursorStyle">
            <!--@mousedown="mousedown"-->
            <!--@mouseup="mouseup"-->
            <!--@mousemove="mousemove"-->
            <span class="timeline-icon16" v-drags="timing"></span>
          </div>

          <TimeScale :Store="TSTYOBJ.store" :Clock="TSTYOBJ.clock" @action="action"></TimeScale>
          <Chart ref="Chart" :Store="TSTYOBJ.store" :action="action" @action="action"></Chart>
        </div>
        <!--<eventDetail></eventDetail>-->
      </div>
    </div>
    <div class="multipleSelect">
      <template v-for="item in multipliers">
        <!--新增-->
        <div @click="changeMultiple(item)">{{ item }}</div>
      </template>
    </div>

  </div>
</template>

<script>

import Grid from "@/components/TS/grid/Grid.vue";
import TimeScale from "@/components/TS/scale/TimeScale.vue"
import Chart from "@/components/TS/chart/Chart.vue"
import {dragElement} from "./utils/drag";
import "./rootCss.css"
// import eventDetail from "@/components/TS/detail/eventDetail.vue";
export default {
  name: "deduction",
  props: ['TSTYOBJ', "action"],
  components: {
    Grid,
    TimeScale,
    Chart,

    /*eventDetail*/
  },
  computed: {
    cursorStyle() {
      return {
        left: `${this.TSTYOBJ.store.scales.cursorLeft || 0}px`,
      };
    },

  },
  data() {
    return {
      multipliers: [
        0.0625, 0.125, 0.25, 0.5, 1, 2, 4, 6, 8, 16, 32, 64, 128, 256,
      ],
    }
  },
  directives: {
    drags: dragElement,
  },
  beforeCreate() {

  },
  mounted() {

    console.log("+++", this.TSTYOBJ)
  },
  methods: {
    changeMultiple(item) {
      this.TSTYOBJ.store.multiplier = item;
      // 播放状态下，才生效
      if (this.TSTYOBJ.clock.status != this.TSTYOBJ.timeStatus.PLAY) {

        // 新增27
        let guijis = this.returnFun();
        guijis.forEach((key) => {
          ts_Map.get(key).speed = ts_Map.get(key).speed * item;
        });

        function isextend(task) {
          return task.callback == 'extend';
        }

        let filtered = this.TSTYOBJ.store.tasks.filter(isextend);
        filtered.forEach(task => {
          ts_Map.get(Number(task.source_id)).spreadTime = (task.duration * 1000 / item)
        })
        /*let guijis = this.returnFun();
        guijis.forEach((key) => {
          ts_Map.get(key).speed = ts_Map.get(key).oneSpeed * Store.multiplier;
        });
        if (Clock.isAction) {
          this.stop();
          // this.start(1);
          this.start(1);
        }*/
      }
      this.$changeComponentShow(".multipleSelect", false);

    },
    openMultiple(e) {
      if (!(TSTYOBJ.clock.status == TSTYOBJ.timeStatus.PLAY && TSTYOBJ.store.editorMode == TSTYOBJ.editorMode.PLAYING)) {
        this.$changeComponentShow(".multipleSelect", true);
        $(".multipleSelect")[0].style.left = e.layerX + 10 + "px";
        $(".multipleSelect")[0].style.top = e.layerY + 5 + "px";
      }

    },
    timing() {
      let currentTasks = TSTYOBJ.store.getTaskInStamp()
      currentTasks.forEach(task => {
        if (task) {
          // console.log("执行事件对象", task);
          if (task.detail && typeof task.detail == "string") {
            task.detail = JSON.parse(task.detail);
          }
          switch (task.callback) {
            case 'pathMove':
              let TrajectoryMotionObject = ts_Map.get(task.ID + task.callback + task.source_id,);
              /*
               TrajectoryMotionObject.moveCallBack(tsEntitys);*/
              let tsEntitys = ts_Map.get(Number(task.source_id));
              tsEntitys.show = true
              // console.log("(TSTYOBJ.store.currentTimestamp-task.start_time)/1000/TSTYOBJ.store.multiplier",(TSTYOBJ.store.currentTimestamp-task.start_time)/1000/TSTYOBJ.store.multiplier)

              TrajectoryMotionObject.speed = TrajectoryMotionObject.oldSpeed
              TrajectoryMotionObject.setMovePositionByTime((TSTYOBJ.store.currentTimestamp - task.start_time) / 1000)

              break;
            case 'extend':
              let entity = ts_Map.get(Number(task.source_id))
              entity.spreadTime = (task.duration * 1000)
              entity.setSpreadProgressByTime((TSTYOBJ.store.currentTimestamp - task.start_time))
              break
            default:
              //新增0918
              let tsEntity = ts_Map.get(Number(task.source_id));
              if (tsEntity && typeof tsEntity[task.callback] == "function") {
                if (task.callback == "flicker") {
                  let detail = task.detail;
                  typeof detail == "string" && (detail = JSON.parse(detail));
                  tsEntity[task.callback](detail.times / this.TSTYOBJ.store.multiplier, detail.number);
                } else tsEntity[task.callback]();
              }
              break;
          }
        }
      })
      if ($root_home_index.eventBox) {
        window.dispatchEvent(window.EventsNameMap.get("changeStampEventBox"));

      }
    },
    // 停止
    stop(isStopBtn = true) {
      console.log("stop", isStopBtn)
      //  不管任何情况，停止按钮都将当前时间设为初始时间
      //  并将编辑器模式设为编辑模式，时间轴设为停止状态
      // （暂停播放除外）
      this.TSTYOBJ.store.editorMode = this.TSTYOBJ.editorMode.EDITING
      this.TSTYOBJ.clock.stopAnimation()
      Array.from(AudioMap.values()).forEach(item => {
        item.pause()
      })
      if (isStopBtn) {
        this.pauseTrajectoryMotion()
        TSTYOBJ.store.currentTimestamp = TSTYOBJ.store.startTimestamp
        this.TSTYOBJ.clock.status = this.TSTYOBJ.timeStatus.STOP
        this.TSTYOBJ.store.scales.scrollLeft = 0
        this.TSTYOBJ.store.scales.cursorLeft = 0
        this.Revert()
      } else {
        this.pauseTrajectoryMotion()
        this.Revert("pause")
        this.TSTYOBJ.clock.status = this.TSTYOBJ.timeStatus.PAUSE


      }
      /* console.log("stop")
       if(this.TSTYOBJ.clock.status==this.TSTYOBJ.timeStatus.PAUSE&&isPause!=null){
         console.log("暂停事件")
         //暂停事件
         this.TrajectoryMotion("pause")
       }else if (this.TSTYOBJ.store.editorMode != this.TSTYOBJ.editorMode.EDITING) {
         this.TSTYOBJ.clock.status=this.TSTYOBJ.timeStatus.STOP
         // 停止事件
         console.log("停止事件")
         this.TrajectoryMotion("stop")
         // 恢复原始状态
         this.Revert()

         if(!isPause){
           this.TSTYOBJ.store.editorMode = this.TSTYOBJ.editorMode.EDITING
           // this.TSTYOBJ.store.panelWidth -= this.TSTYOBJ.store.scales.gridWidth
           this.$nextTick(() => {
             TSTYOBJ.renderLine(this.$nextTick)
             TSTYOBJ.renderLabel({left: 0})
             // TSTYOBJ.store.updateTimeLineRightRest()
           })

           // this.TSTYOBJ.store.currentTimestamp=this.TSTYOBJ.store.startTimestamp
           this.TSTYOBJ.store.scales.scrollLeft=0
           this.TSTYOBJ.store.scales.cursorLeft=0
         }else{

         }

       }else if(!isPause){
         this.TSTYOBJ.store.scales.scrollLeft=0
         this.TSTYOBJ.store.scales.cursorLeft=0
       //   恢复原始状态
         this.Revert()
       }
       */

      // 停止时间流逝

    },
    Revert(flag = null) {
      if (flag == null) {
        this.TSTYOBJ.store.tasks.forEach(item => {
          console.log("Revert", item)
          let zTreeObj = $.fn.zTree.getZTreeObj("treeDemos");
          let idKey = zTreeObj.setting.data.simpleData.idKey;
          let node = zTreeObj.getNodeByParam(idKey, item.source_id, null);
          let entity = ts_Map.get(Number(item.source_id));
          switch (item.callback) {
            case "flicker":
              entity && entity.flicker(1, 1);
              break;
            case "extend":
              console.log(" entity.spreadState=false")
              entity.spreadState = false
              entity.spreadTime = (item.duration * 1000)
              entity.setSpreadProgressByTime(item.duration * 1000)


              break
            case "Animation":
              ts_Map.get(Number(item.source_id)).activeAnimate=""
              break
            case "pathMove":
              /*let TrajectoryMotionMapKey = item.ID + "pathMove" + item.source_id
              let TrajectoryMotionObject = ts_Map.get(TrajectoryMotionMapKey);
              TrajectoryMotionObject.setMovePositionByTime(0)*/
              //   将模型改回节点树上编辑的样子
              let model=ts_Map.get(Number(item.source_id))
              model.rotateX=node.detail.rotate.x
              model.rotateY=node.detail.rotate.y
              model.rotateZ=node.detail.rotate.z
              model.lng= node.detail.position.lng
              model.lat= node.detail.position.lat
              model.alt= node.detail.position.alt
              break;
          }
        })

      } else if (flag == 'pause') {
        this.TSTYOBJ.store.tasks.forEach(item => {
          let zTreeObj = $.fn.zTree.getZTreeObj("treeDemos");
          let idKey = zTreeObj.setting.data.simpleData.idKey;
          let node = zTreeObj.getNodeByParam(idKey, item.source_id, null);
          let entity = ts_Map.get(Number(item.source_id));
          switch (item.callback) {
            case "flicker":
              entity && entity.flicker(1, 1);
              break;
            case "extend":
              entity.spreadState = false
              break
          }
        })
      }
    },
    // 暂停模式
    pause() {
      // this.TSTYOBJ.clock.status=this.TSTYOBJ.timeStatus.PAUSE
      this.TSTYOBJ.store.editorMode = this.TSTYOBJ.editorMode.EDITING
      // TSTYOBJ.store.currentTimestamp = TSTYOBJ.store.startTimestamp
      this.TSTYOBJ.clock.status = this.TSTYOBJ.timeStatus.PAUSE
      this.stop(false)
    },
    // 播放按钮
    play() {
      // 如果编辑器在编辑模式，时间轴为停止状态则先将当前时间设为起始时间
      if (this.TSTYOBJ.store.editorMode == this.TSTYOBJ.editorMode.EDITING &&
          (this.TSTYOBJ.clock.status == this.TSTYOBJ.timeStatus.STOP && TSTYOBJ.store.currentTimestamp != TSTYOBJ.store.startTimestamp ||
              this.TSTYOBJ.store.currentTimestamp > this.TSTYOBJ.store.getTotalTime())) {
        console.log("++++++++++++++")
        this.Revert()
        TSTYOBJ.store.currentTimestamp = TSTYOBJ.store.startTimestamp
      }
      // 编辑器为播放模式，时间轴为播放状态
      this.TSTYOBJ.store.editorMode = this.TSTYOBJ.editorMode.PLAYING
      this.TSTYOBJ.clock.status = this.TSTYOBJ.timeStatus.PLAY
      // this.TSTYOBJ.store.editorMode = (this.TSTYOBJ.store.editorMode==0?1:0)
      // this.TSTYOBJ.clock.status =( this.TSTYOBJ.clock.status==1?2:1)//this.TSTYOBJ.timeStatus.PLAY==
      this.$nextTick(() => {
        TSTYOBJ.renderLine(this.$nextTick)
        TSTYOBJ.renderLabel({left: 0})
        TSTYOBJ.store.updateTimeLineRightRest()
      })
      //新情况
      let currentTasks = this.TSTYOBJ.store.getTaskInStamp()
      currentTasks.forEach(task => {
        console.log("play的todoEvent")
        this.todoEvent(null, task);
      })

      // this.TrajectoryMotion("resume")
      this.TSTYOBJ.clock.animation(this.TSTYOBJ.store, (currentTime, diff, timeStamp) => {
        this.TSTYOBJ.store.currentTimestamp = currentTime
        // 当前与初始时间戳差值
        let goTimestamp = currentTime - this.TSTYOBJ.store.startTimestamp;
        // 当前时间相对起始点的位置
        let left = (goTimestamp / 1000) * this.TSTYOBJ.store.scales.preSecondPx
        // 获取光标轴dom元素
        let dom = document.getElementsByClassName("timelineCursorBox")[0]
        //光标原始位置
        let originLeft = dom.style.left.split("px")[0] || 0
        // dom.style.left = left - originLeft - this.TSTYOBJ.store.scales.scrollLeft + "px"
        // dom.style.transform = `translateX(${left - originLeft - this.TSTYOBJ.store.scales.scrollLeft}px)`
        // document.documentElement.style.setProperty('--timelineCursorBox-left', left - originLeft - this.TSTYOBJ.store.scales.scrollLeft + "px");
        /* console.log(dom.style.left)
         console.log(this.TSTYOBJ.store.preSecondPx)
         console.log(left)
         console.log(originLeft)
         console.log(this.TSTYOBJ.store.scales.scrollLeft)*/
        this.$forceUpdate();
        // console.log("444", currentTime, diff, timeStamp)
      }, this.animation)
    },
    //操作机动事件对象
    pauseTrajectoryMotion() {
      //status:pause,resume,stop(0)
      let currentTasks = TSTYOBJ.store.getTaskInStamp()
      console.log("currentTasks", currentTasks)
      currentTasks.forEach(task => {
        if (task.callback == 'pathMove') {
          let TrajectoryMotionMapKey = task.ID + task.callback + task.source_id
          let TrajectoryMotionObject = ts_Map.get(TrajectoryMotionMapKey);
          TrajectoryMotionObject.pause()
        }
      })
    },
    animation() {

      if (TSTYOBJ.clock.status == TSTYOBJ.timeStatus.PLAY) {
        let timeId = Math.round(this.TSTYOBJ.store.currentTimestamp / 1000);
        timeId *= 1000;
        let taskIds = [];
        // 原始情况
        // 以起始时间+resouce_id为key，生成事件map+
        let dataMap = this.TSTYOBJ.store.dealData("start_time");
        let endTimeEventMap = this.TSTYOBJ.store.dealData("end_time");

        // 新增26
        // 循环获取key
        let fun = (map, isEnd = false) => {
          let keys = Array.from(map.keys());
          for (let i = 0; i < keys.length; i++) {
            if (String(keys[i]).indexOf(timeId) > -1) {
              taskIds.push(keys[i]);
            }
          }
          taskIds.forEach((item) => {
            let res = map.get(item);
            this.todoEvent(timeId, res, isEnd);
          });
        }
        fun(dataMap)
        fun(endTimeEventMap, true)


        if (this.TSTYOBJ.store.currentTimestamp > this.TSTYOBJ.store.getTotalTime()) {
          this.stop(false);
        }
      }

    },
    todoEvent(item, res, isEnd = false) {
      if (res) {
        if (res.detail && typeof res.detail == "string") {
          res.detail = JSON.parse(res.detail);
        }
        // 执行时间滑块的结束事件
        if (isEnd) {
          console.log("执行结束事件", res);
          switch (res.callback) {
            case 'audio':
              Array.from(AudioMap.values()).forEach(item => {
                item.pause()
              })
              break
            case 'Animation':
              ts_Map.get(Number(res.source_id)).activeAnimate=""
              break
          }
        } else {
          console.log("执行事件对象", res);
          // 执行时间滑块的开始事件
          switch (res.callback) {
            case 'pathMove':
              let TrajectoryMotionObject = ts_Map.get(res.ID + res.callback + res.source_id);
              TrajectoryMotionObject.speed = TrajectoryMotionObject.oldSpeed * this.TSTYOBJ.store.multiplier
              TrajectoryMotionObject.state = !TrajectoryMotionObject.state
              TrajectoryMotionObject.setMovePositionByTime((this.TSTYOBJ.store.currentTimestamp - res.start_time) / 1000 / this.TSTYOBJ.store.multiplier)
              // TrajectoryMotionObject.state=true

              break
            case 'extend':
              // ts_Map.get(Number(res.source_id))
              console.log("暂停后继续播放 相对时间", (TSTYOBJ.store.currentTimestamp - res.start_time))
              ts_Map.get(Number(res.source_id)).setSpreadProgressByTime((TSTYOBJ.store.currentTimestamp - res.start_time))
              ts_Map.get(Number(res.source_id)).spreadTime = (res.duration * 1000) / this.TSTYOBJ.store.multiplier
              ts_Map.get(Number(res.source_id)).spreadState = true
              break
            case 'audio':

              let audio = new Audio();
              audio.src = "/admin/yjearth4.0/api/v1/preview/pdf?id=" + res.detail.id;
              audio.loop = true
              audio.volume = res.detail.volume||0.5
              audio.playbackRate = this.TSTYOBJ.store.multiplier
              audio.addEventListener("canplaythrough", event => {
                /* 音频可以播放；如果权限允许则播放 */
                audio.play();
              });
              AudioMap.set(res.ID, audio)
              // new Audio
              break
            case 'Animation':
              ts_Map.get(Number(res.source_id)).activeAnimate= res.detail.animationName
              break
            default:
              //新增0918
              let tsEntity = ts_Map.get(Number(res.source_id));
              if (tsEntity && typeof tsEntity[res.callback] == "function") {
                if (res.callback == "flicker") {
                  let detail = res.detail;
                  typeof detail == "string" && (detail = JSON.parse(detail));
                  tsEntity[res.callback](detail.times / this.TSTYOBJ.store.multiplier, detail.number);
                } else tsEntity[res.callback]();
              }
              break;
          }
        }


      }
    },
    //返回机动对象key
    returnFun() {
      function isTrajectoryMotion(element) {
        return String(element).indexOf("pathMove") > -1;
      }

      let filtered = Array.from(ts_Map.keys()).filter(isTrajectoryMotion);
      return filtered;
    },
  },
}
</script>

<style lang="scss" scoped>
.layoutBox {
  //height: 230px;
  background: rgba(0, 0, 0, 0.53);
  //display: flex;
  //flex-direction: column;
  //position: relative;
  .control {
    display: flex;
    height: 30px;
    line-height: 30px;
    color: #fff;
    justify-content: space-between;
    width: 400px;

    & > span {
      display: inline-block;
      width: 200px;
    }


    .icon {
      width: 18px;
      height: 18px;
      cursor: pointer;
    }

    .btn {
      margin: 0 vw(15);
    }

    .disabledBtn {
      cursor: no-drop;
      filter: brightness(0.7);
    }
  }

  .layoutBoxs {
    //height: 230px;
    height: vh(230);;
    position: relative;
  }


  .multipleSelect {
    border: 1px solid;
    position: absolute;
    z-index: 999;
    top: 0;
    color: #fff;
    width: vw(82);
    height: vh(165);
    background: rgba(0, 63, 63, 1);
    overflow-y: auto;
    font-size: px2font(16);
    display: none;

    & > div {
      cursor: pointer;
      margin: vh(4) 0;
    }
  }

  .layout {
    display: flex;
    width: 100%;
    flex: auto;
    height: 100%;
    position: absolute;

    .TLContainer {
      position: relative;
      overflow: hidden;
      flex: auto;
      display: flex;
      flex-direction: column;


      .timelineCursorBox {
        position: absolute;
        border-right: 0.5px red solid;
        height: calc(100% - 16px);
        z-index: 9;
        //left: 10px;
        top: 16px;
        transition: transform 0.001s ease-in-out;

        .timeline-icon16 {
          display: block;
          position: absolute;
          width: 16px;
          height: 16px;
          //width: vw(16);
          //height: vw(16);
          transform: translate(-50%, -16px);
          background: url("../../assets/img/indicator.png") no-repeat;
          cursor: pointer;
        }
      }
    }
  }
}
</style>
