<template>
  <div class="container">
    <div>
      <div class="app-canvas">
        <el-row type="flex" align="middle" style="height: 40px;">
          <el-col :span="7">
            <el-button @click="big" type="danger" icon="el-icon-circle-plus-outline" >放大</el-button>
            <el-button @click="small" type="danger" icon="el-icon-remove-outline" >缩小</el-button>
            <el-button @click="replay" :disabled="isDisabled" type="success" :icon="buttonIcon" >回放</el-button>
          </el-col>
          <el-col :span="17">
            <el-progress v-show="isShow" :percentage="percentage"></el-progress>
          </el-col>
        </el-row>
        <el-row>
          <div id="page_canvas"></div>
        </el-row>
      </div>
    </div>
    <div class="right-board">
        <el-divider content-position="left">平台无人机</el-divider>
          <span>位置&nbsp;&nbsp;</span><label>{{ uavlo }}</label><br>
          <span>速度&nbsp;&nbsp;</span><label>{{ uavsp }}</label><br>
          <span>姿态&nbsp;&nbsp;</span><label>{{ uavpo }}</label><br>
        <el-divider content-position="left">目标无人机群</el-divider>
        <li v-for='(item, index) in targetAry' :key="index">
          <span>编号&nbsp;&nbsp;</span><label>{{ item.name }}</label><br>
          <span>位置&nbsp;&nbsp;</span><label>{{ item.loc }}</label><br>
          <span>速度&nbsp;&nbsp;</span><label>{{ item.sp }}</label><br>
          <span>姿态&nbsp;&nbsp;</span><label>{{ item.po }}</label><br>
        </li>
    </div>
  </div>
</template>

<script>
import * as PIXI from "pixi.js";

export default {
  data() {
    return {
      webSocket: null,
      app: null,
      texture: null,
      sprite: null,
      targetTexture: null,
      targetSprite: null,
      container: null,
      line: null,
      targetLine: null,
      dueLine: null,
      uavlo: "x: 0, y: 0",
      uavsp: "0 m/s",
      uavpo: "x: 0, y: 0",
      prex: 0,
      prey: 0,
      tarprex: 0,
      tarprey: 0,
      dueprex: 0,
      dueprey: 0,
      isDisabled: true,
      isShow: false,
      percentage: 0,
      current: 0,
      totalPercentage: 0,
      buttonIcon: "el-icon-video-play",
      bizId: "",
      taskId: "",
      targetUavAry: [],
      targetCircle: [],
      targetText: [],
      targetAry: [],
    };
  },
  created() {
    const taskId = this.$route.params && this.$route.params.taskId;
    if (taskId) {
      this.taskId = taskId;
      this.connectWebSocket();
    }
  },
  mounted() {
    this.initCanvas();
  },
  methods: {
    connectWebSocket() {
      const wsUri = "ws://127.0.0.1:8080/websocket/message";
      this.webSocket = new WebSocket(wsUri);
      const self = this;

      this.webSocket.onopen = function (event) {
        self.initContainer();
        self.webSocket.send("RUN:" + self.taskId);
        console.log("WebSocket连接成功!");
      };

      this.webSocket.onmessage = function (event) {
        self.app.stage.addChild(self.container);
        const dataObj = JSON.parse(event.data);
        if (self.isShow) {
          self.current++;
          self.percentage = Math.round((self.current / self.totalPercentage) * 100);
          if (self.percentage === 100) {self.buttonIcon = "el-icon-video-play";}
        } else {
          self.totalPercentage++;
        }
        self.bizId = dataObj.bizId;
        self.isDisabled = !(dataObj.finished === 'true');

        if (dataObj.platformAircraft != null) {
          const lx = dataObj.platformAircraft.coordinateX;
          const ly = dataObj.platformAircraft.coordinateY;
          self.sprite.x = lx;
          self.sprite.y = ly;
          self.uavlo = "x:" + lx + ", y:" + ly;
          self.uavsp = dataObj.platformAircraft.velocity + " m/s";
          self.uavpo = "x:" + dataObj.platformAircraft.aircraftPoseX + ", y:" + dataObj.platformAircraft.aircraftPoseY;

          //平台无人机轨迹
          self.drawLine(lx, ly);
        } else if (dataObj.targetAircraft != null) {
          let tx = 0;
          let ty = 0;
          if (self.targetUavAry.length === 0) {
            const total = dataObj.targetAircraft[0].aircrafts.length;
            for (let i = 0; i < total; i++) {
              //目标无人机群
              const uav = new PIXI.Sprite(self.targetTexture);
              uav.anchor.set(0.5);
              uav.scale.set(0.06);
              uav.x = dataObj.targetAircraft[0].aircrafts[i].coordinateX;
              uav.y = dataObj.targetAircraft[0].aircrafts[i].coordinateY;
              self.targetUavAry.push(uav);
              self.container.addChild(uav);

              const fx = uav.x - 37;
              const fy = uav.y - 25;

              //编号-圆圈
              const circle = new PIXI.Graphics();
              circle.beginFill(0xFF0000); // 红色
              circle.drawCircle(0, 0, 10);
              circle.endFill();
              circle.x = fx;
              circle.y = fy;
              self.targetCircle.push(circle);

              //编号-数字
              const text = new PIXI.Text(dataObj.targetAircraft[0].aircrafts[i].aircraftNumber,
                { fontFamily: 'Arial', fontSize: 14, fill: 0xFFFFFF, align: 'center'});
              text.anchor.set(0.5);
              // 计算文字位置以便在圆形内居中
              text.x = fx;
              text.y = fy;
              self.targetText.push(text);

              self.container.addChild(circle);
              self.container.addChild(text);

              const newObj = {
                name: dataObj.targetAircraft[0].aircrafts[i].aircraftNumber,
                loc:'x:' + uav.x +' , y:' + uav.y,
                sp:dataObj.targetAircraft[0].aircrafts[i].velocity + ' m/s',
                po:'x:' + dataObj.targetAircraft[0].aircrafts[i].aircraftPoseX +' , y:' + dataObj.targetAircraft[0].aircrafts[i].aircraftPoseY
              };
              self.targetAry.push(newObj);

              if (dataObj.targetAircraft[0].aircrafts[i].piloted) {
                tx = uav.x;
                ty = uav.y;
              }
            }
          } else {
            for (let i = 0; i < self.targetUavAry.length; i++) {
              const uav = self.targetUavAry[i];
              uav.x = dataObj.targetAircraft[0].aircrafts[i].coordinateX;
              uav.y = dataObj.targetAircraft[0].aircrafts[i].coordinateY;
              self.targetAry.splice(i, 1,
                {name: dataObj.targetAircraft[0].aircrafts[i].aircraftNumber,
                  loc:'x:' + uav.x +' , y:' + uav.y,
                  sp:dataObj.targetAircraft[0].aircrafts[i].velocity + ' m/s',
                  po:'x:' + dataObj.targetAircraft[0].aircrafts[i].aircraftPoseX +' , y:' + dataObj.targetAircraft[0].aircrafts[i].aircraftPoseY
                }
              );

              const fx = uav.x - 37;
              const fy = uav.y - 25;

              const circle = self.targetCircle[i];
              circle.x = fx;
              circle.y = fy;

              const text = self.targetText[i];
              text.x = fx;
              text.y = fy;

              if (dataObj.targetAircraft[0].aircrafts[i].piloted) {
                tx = uav.x;
                ty = uav.y;
              }
            }
          }

          //目标无人机群轨迹
          self.drawTargetLine(tx, ty);
        }

        //平台无人机预定轨迹
        /* let fpLen = dataObj.platformAircraft.flightpath.length;
        if (fpLen > 0) {
          let dx = 0;
          let dy = 0;
          for (let i = 0; i < fpLen; i++) {
            dx = dataObj.platformAircraft.flightpath[i].coordinateX;
            dy = dataObj.platformAircraft.flightpath[i].coordinateY;
            console.log('prex=' + self.dueprex + ', prey=' + self.dueprey);
            if (self.dueprex === 0 && self.dueprey === 0) {
              self.dueLine.moveTo(dx, dy);
              self.dueprex = dx;
              self.dueprey = dy;
            } else {
              self.dueLine.moveTo(self.dueprex, self.dueprey);
            }
            self.dueLine.lineTo(dx, dy);
            self.dueprex = dx;
            self.dueprey = dy;
            console.log('x=' + dx + ', y=' + dy);
          }
        } */
      };

      this.webSocket.onclose = function (event) {
        self.clearContainer(self.container);
        //数组清空
        self.targetUavAry.splice(0, self.targetUavAry.length);
        self.targetAry.splice(0, self.targetAry.length);
        self.targetCircle.splice(0, self.targetCircle.length);
        self.targetText.splice(0, self.targetText.length);
        console.log('WebSocket连接断开!');
      };

      this.webSocket.onerror = function(event) {
        console.log('WebSocket连接异常: ' + event.code + ' ' + event.reason + ' ' + event.wasClean);
      };
    },

    big() {
      this.container.scale.x += 0.1;
      this.container.scale.y += 0.1;
    },
    small() {
      this.container.scale.x -= 0.1;
      this.container.scale.y -= 0.1;
    },
    replay() {
      if (this.webSocket) {
        this.clearContainer(this.container);
        //数组清空
        this.targetUavAry.splice(0, this.targetUavAry.length);
        this.targetAry.splice(0, this.targetAry.length);
        this.targetCircle.splice(0, this.targetCircle.length);
        this.targetText.splice(0, this.targetText.length);
        this.initContainer();
        this.webSocket.send("REPLAY:" + this.bizId);
        this.isShow = true;
        this.buttonIcon = "el-icon-video-pause";
        this.current = 0;
        this.dueprex = 0;
        this.dueprey = 0;
      } else {
        console.log("WebSocket未连接！");
      }
    },
    drawLine(x, y) {
      if (this.prex === 0 && this.prey === 0) {
          this.line.moveTo(x, y);
          this.prex = x;
          this.prey = y;
      } else {
          this.line.moveTo(this.prex, this.prey);
      }
      this.line.lineTo(x, y);
    },
    drawTargetLine(x, y) {
      if (this.tarprex === 0 && this.tarprey === 0) {
        this.targetLine.moveTo(x, y);
        this.tarprex = x;
        this.tarprey = y;
      } else {
        this.targetLine.moveTo(this.tarprex, this.tarprey);
      }
      this.targetLine.lineTo(x, y);
    },
    initContainer(){
      //创建容器
      this.container = new PIXI.Container();

      //创建一个纹理
      this.texture = PIXI.Texture.from("./textures/uav.png");
      //创建一个精灵
      this.sprite = new PIXI.Sprite(this.texture);
      this.sprite.anchor.set(0.5);
      this.sprite.scale.set(0.1);
      this.container.addChild(this.sprite);

      this.targetTexture = PIXI.Texture.from("./textures/uav-tar.png");
      // this.targetSprite = new PIXI.Sprite(this.targetTexture);
      // this.targetSprite.anchor.set(0.5);
      // this.targetSprite.scale.set(0.06);
      // this.container.addChild(this.targetSprite);

      this.line = new PIXI.Graphics();
      this.line.lineStyle(1, 0xff0000, 1);
      this.container.addChild(this.line);

      this.targetLine = new PIXI.Graphics();
      this.targetLine.lineStyle(1, 0xeeee00, 1);
      this.container.addChild(this.targetLine);

      this.dueLine = new PIXI.Graphics();
      this.dueLine.lineStyle(1, 0x66cd00, 1);
      this.container.addChild(this.dueLine);

      //设置container为交互式
      this.container.interactive = true;
      //监听鼠标按下事件
      this.container.buttonMode = true;

      // 拖曳状态变量
      let dragging = false;
      let offsetX = 0;
      let offsetY = 0;

      this.container.on('pointerdown', (event) => {
        dragging = true;
        offsetX = this.container.x - event.data.global.x;
        offsetY = this.container.y - event.data.global.y;
      });

      // 监听鼠标移动事件
      this.container.on('pointermove', (event) => {
        if (dragging) {
          this.container.x = event.data.global.x + offsetX;
          this.container.y = event.data.global.y + offsetY;
        }
      });

      // 监听鼠标松开事件
      this.container.on('pointerup', () => {
        dragging = false;
      });

      // 监听鼠标松开事件（为了处理在容器外部松开鼠标的情况）
      this.app.stage.on('pointerup', () => {
        dragging = false;
      });

    },
    clearContainer(c) {
      while (c.children.length > 0) {
        c.removeChild(c.children[0]);
      }
    },
    initCanvas() {
      const pageCanvas = document.getElementById("page_canvas");
      const width = pageCanvas.offsetWidth;
      //const height = pageCanvas.offsetHeight;
      this.app = new PIXI.Application({
        width: width, // default: 800 宽度
        height: window.innerHeight, // default: 600 高度
        antialias: true, // default: false 反锯齿
        transparent: false, // default: false 透明度
        resolution: 1, // default: 1 分辨率
        backgroundAlpha: 0, // 设置背景颜色透明度   0是透明
      });
      this.app.renderer.backgroundColor = 0x66CCFF; // 设置canvas背景颜色
      // 将创建好的canvas添加到元素当中去
      pageCanvas.appendChild(this.app.view);
    },
  },
  beforeDestroy() {
    if (this.webSocket) {
      this.webSocket.close();
    }
  }
};
</script>

<style scoped>
.container {
  display: grid;
  grid-template-columns: 80% 20%; /* 两栏按比例分 */
}
.right-board {
  padding: 2px; margin: 2px;height:730px;
  overflow: auto; /* 当内容超出元素边界时显示滚动条 */
}
.app-canvas {
  padding: 5px;
  margin: 5px;
}
</style>
