<template>
  <div>
    <UavList></UavList>
    <Player
      class="player"
      ref="player"
      v-if="showPlayer"
      :pointListFlag="pointListFlag"
      @getAiPopup="getAiPopup"
      @imgUrl="getimgUrl"
      @startLinePoint="startLinePoint"
      :scheduleData="scheduleData"
      :keyFlag="keyFlag"
      :NXdata="NXdata"
      @changeLableName="(e) => (lineLableName = e)"
      :lineLableName="lineLableName"
      :device="uav"
      @AIDialog="(e, val) => getAIDialog(e, val)"
      @continue="continueReset"
      :videoItem="videoItem"
      :showCenter="showCenter"
    />
    <ControlPanel v-if="showPanel"></ControlPanel>
  </div>
</template>

<script>
import { mapState } from "vuex";
import UavList from "./components/uavList";
import Player from "./components/player";
import ControlPanel from "./components/controlPanel";
import linkFusion from "./mixins/linkFusion";

export default {
  name: "UavApplications",
  mixins: [linkFusion],
  components: {
    UavList,
    Player,
    ControlPanel,
  },
  data() {
    return {
      pointListFlag: false,
      aiPopup: null, //识别图标
      scheduleData: {}, //航线执行进度
      keyFlag: false, //NX状态
      NXdata: {}, //NX数据
      lineLableName: "", //当前航线标签
      videoItem: 0,
      showCenter: false,
    };
  },
  computed: {
    ...mapState("MMCFlightControlCenter/uavApplications", [
      "uav",
      "showPlayer",
      "showPanel",
    ]),
    taskId() {
      return this.$store.state.fckernel.taskId;
    },
    YJTaskInfo() {
      return this.$store.state.fckernel.YJTaskInfo;
    },
    lineInfo() {
      return this.$store.state.fckernel.lineInfo;
    },
    uav_mounts() {
      let { mounts } = this.uav.control;
      return mounts
        .map((item) => {
          let find_item = this.mount.list.find(
            (m) => m.name === item.gimbalName
          );
          return find_item || undefined;
        })
        .filter((item) => item);
    },
  },
  created() {
    // 等待航线上传成功在执行
    // 判断是否以一键任务
    /* Bus.$on("off_take", () => {
      this.takeOff = true;
    }); */
  },
  mounted() {},
  beforeDestroy() {},
  methods: {
    // 结束任务确认框，确定结束任务
    async queding() {
      this.$refs.ControlMenu.queding();
      this.endRenwu = false;
    },
    getAiPopup(val) {
      this.aiPopup = val;
    },
    startLinePoint() {
      this.pointListFlag = !this.pointListFlag;
      if (this.pointListFlag) {
        this.pointFlag = true;
        setTimeout(() => {
          this.pointFlag = false;
        }, 1000);
      }
    },
    continueReset() {
      setTimeout(() => {
        this.resetSwim();
      }, 3000);
    },
    getAIDialog(e, val) {
      this.AIFlag = e;
      this.aiTitle = val;
      setTimeout(() => {
        this.resetSwim();
      }, 3000);
      // this.$refs.P3.$refs.ItemA.text="盐城公安提醒您不私自下水游泳不擅自与他人结伴游泳不在无成年人带领的情况下游泳不到无安全设施无救援人员的水域游泳不到不熟悉的水域游泳不擅自下水施救"
      // this.$refs.P3.$refs.ItemA.handleSendTTSText()
    },
    //检测
    resetSwim() {
      let data = {
        data: "AUTO_MISSION",
        type: 513,
      };
      this.uav_mqtt_fn(data);
      this.AIFlag = false;
      setTimeout(() => {
        this.$refs["player"][0].setAll();
      }, 1000);
    },
    getcanvas(val, item) {
      let data = null;
      if (item.jsonData) {
        data = JSON.parse(item.jsonData);
      } else {
        data = item;
      }
      // let targets = data.targets;
      setTimeout(() => {
        this.canvas = this.$refs.canvas;
        this.canvas.width = 1000;
        this.canvas.height = 500;
        this.image = new Image();
        this.image.src = val;
        this.image.onload = () => {
          if (this.aiType >= 4 && this.aiType != 13) {
            this.drawImage(data.targets);
          } else if (this.aiType == 1) {
            this.drawImage(data.detections);
          } else if (this.aiType == 2) {
            this.drawImage(data.aiPlateShiJuResultInfoDtoList);
          } else if (this.aiType == 3 || this.aiType == 13) {
            this.drawImage(data);
          }
        };
      }, 50);
    },
    drawImage(list) {
      this.ctx = this.canvas.getContext("2d");
      this.ctx.drawImage(
        this.image,
        0,
        0,
        this.canvas.width,
        this.canvas.height
      );
      this.ctx.lineWidth = 2;
      this.ctx.strokeStyle = "red";
      if (this.aiType >= 4 && this.aiType != 13) {
        list.forEach((targets) => {
          let plate_detection = {
            x: 0,
            y: 0,
            h: 0,
            w: 0,
          };
          plate_detection.x =
            (this.canvas.width * targets.bbox.box.left_top_x) /
            this.image.width;
          plate_detection.y =
            (this.canvas.height * targets.bbox.box.left_top_y) /
            this.image.height;
          plate_detection.h =
            (this.canvas.height *
              (targets.bbox.box.right_bottom_y - targets.bbox.box.left_top_y)) /
            this.image.height;
          plate_detection.w =
            (this.canvas.width *
              (targets.bbox.box.right_bottom_x - targets.bbox.box.left_top_x)) /
            this.image.width;

          this.ctx.strokeRect(
            plate_detection.x,
            plate_detection.y,
            plate_detection.w,
            plate_detection.h
          );
          this.ctx.fillStyle = "rgba(0,0,0,0.8)";
          let text =
            targets.bbox.label +
            ":" +
            (targets.bbox.prob * 100).toFixed(2) +
            "%（相似度）";
          let offX = 0;
          let offY = 0;
          if (plate_detection.x + text.length * 11 > 1000) {
            offX = 1000 - text.length * 11;
          } else {
            offX = plate_detection.x - 5;
          }
          if (plate_detection.y - 20 < 0) {
            offY = plate_detection.y + plate_detection.h;
          } else {
            offY = plate_detection.y - 22;
          }
          this.ctx.fillRect(
            // plate_detection.x - 5,
            offX,
            offY,
            text.length * 11,
            20
          );
          this.ctx.fillStyle = "white"; // 设置文本颜色
          this.ctx.font = "16px Arial"; // 设置文本字体大小和样式
          this.ctx.fillText(
            text,
            // plate_detection.x - 5,
            offX,
            offY + 15
          ); // 绘制文本
        });
      } else if (this.aiType == 1) {
        list.forEach((targets) => {
          let plate_detection = {
            x: 0,
            y: 0,
            h: 0,
            w: 0,
          };
          plate_detection.x =
            (this.canvas.width * targets.x) / this.image.width;
          plate_detection.y =
            (this.canvas.height * targets.y) / this.image.height;
          plate_detection.h =
            (this.canvas.height * targets.h) / this.image.height;
          plate_detection.w =
            (this.canvas.width * targets.w) / this.image.width;

          this.ctx.strokeRect(
            plate_detection.x,
            plate_detection.y,
            plate_detection.w,
            plate_detection.h
          );
          this.ctx.fillStyle = "rgba(0,0,0,0.5)";
          this.ctx.fillRect(
            plate_detection.x - 5,
            plate_detection.y - 22,
            20,
            20
          );
          this.ctx.fillStyle = "white"; // 设置文本颜色
          this.ctx.font = "12px Arial"; // 设置文本字体大小和样式
          this.ctx.fillText("人", plate_detection.x - 3, plate_detection.y - 8); // 绘制文本
        });
      } else if (this.aiType == 2) {
        list.forEach((targets) => {
          let plate_detection = {
            x: 0,
            y: 0,
            h: 0,
            w: 0,
          };
          plate_detection.x =
            (this.canvas.width * targets.yiSaPlateDetection.x) /
            this.image.width;
          plate_detection.y =
            (this.canvas.height * targets.yiSaPlateDetection.y) /
            this.image.height;
          plate_detection.h =
            (this.canvas.height * targets.yiSaPlateDetection.h) /
            this.image.height;
          plate_detection.w =
            (this.canvas.width * targets.yiSaPlateDetection.w) /
            this.image.width;

          this.ctx.strokeRect(
            plate_detection.x,
            plate_detection.y,
            plate_detection.w,
            plate_detection.h
          );
          this.ctx.fillStyle = "rgba(0,0,0,0.5)";
          this.ctx.fillRect(
            plate_detection.x - 5,
            plate_detection.y - 22,
            60,
            20
          );
          this.ctx.fillStyle = "white"; // 设置文本颜色
          this.ctx.font = "12px Arial"; // 设置文本字体大小和样式
          this.ctx.fillText(
            targets.plateNum,
            plate_detection.x - 3,
            plate_detection.y - 8
          ); // 绘制文本
        });
      } else if (this.aiType == 3) {
        list.forEach((targets) => {
          let plate_detection = {
            x: 0,
            y: 0,
            h: 0,
            w: 0,
          };
          plate_detection.x =
            (this.canvas.width * targets.bbox[0]) / this.image.width;
          plate_detection.y =
            (this.canvas.height * targets.bbox[1]) / this.image.height;
          plate_detection.h =
            (this.canvas.height * (targets.bbox[3] - targets.bbox[1])) /
            this.image.height;
          plate_detection.w =
            (this.canvas.width * (targets.bbox[2] - targets.bbox[0])) /
            this.image.width;

          this.ctx.strokeRect(
            plate_detection.x,
            plate_detection.y,
            plate_detection.w,
            plate_detection.h
          );
          this.ctx.fillStyle = "rgba(0,0,0,0.5)";
          this.ctx.fillRect(
            plate_detection.x - 5,
            plate_detection.y - 22,
            20,
            20
          );
          this.ctx.fillStyle = "white"; // 设置文本颜色
          this.ctx.font = "16px Arial"; // 设置文本字体大小和样式
          this.ctx.fillText("人", plate_detection.x - 3, plate_detection.y - 8); // 绘制文本
        });
      } else if (this.aiType == 13) {
        list.crowdDensityDataList.forEach((targets) => {
          let plate_detection = {
            x: 0,
            y: 0,
            h: 0,
            w: 0,
          };
          plate_detection.x =
            (this.canvas.width * targets.bbox[0]) / this.image.width;
          plate_detection.y =
            (this.canvas.height * targets.bbox[1]) / this.image.height;
          plate_detection.h =
            (this.canvas.height * (targets.bbox[3] - targets.bbox[1])) /
            this.image.height;
          plate_detection.w =
            (this.canvas.width * (targets.bbox[2] - targets.bbox[0])) /
            this.image.width;

          this.ctx.strokeRect(
            plate_detection.x,
            plate_detection.y,
            plate_detection.w,
            plate_detection.h
          );
          this.ctx.fillStyle = "rgba(0,0,0,0.5)";
          let text = targets.desc;
          let offX = 0;
          let offY = 0;
          if (plate_detection.x + text.length * 11 > 1000) {
            offX = 1000 - text.length * 11;
          } else {
            offX = plate_detection.x - 5;
          }
          if (plate_detection.y - 20 < 0) {
            offY = plate_detection.y + plate_detection.h;
          } else {
            offY = plate_detection.y - 22;
          }
          this.ctx.fillRect(offX, offY, text.length * 11, 20);
          this.ctx.fillStyle = "white"; // 设置文本颜色
          this.ctx.font = "11px Arial"; // 设置文本字体大小和样式
          this.ctx.fillText(text, offX, offY + 15); // 绘制文本
        });
      }
    },
    closeVideo() {
      this.$message.warning("无人机已离线！");
      this.healthData = {};
      this.uav.control.mounts = [];
      // this.VideoTomapFlag = false
      // this.uav_hide_control(this.uavId)
      this.$emit("healthWaringShow", [], false);
      this.uav_hide_video(this.uavId);
      // this.controlMenuFlag = false
      // this.ControlFlag = false
      // this.uav_list()
    },
    getModeStatus(val) {
      // console.log(val,"ModeStatus");
      this.ModeStatus = val;
    },
    async addMessage() {
      let res = await API.FCKERNEL.exceptionAdd(this.message);
    },
    showLine(val) {
      this.showCenter = val;
    },
    auto() {
      //定点-->航线
      //摇杆手动-->自动
      this.$refs.ControlMenu.changeAuto();
    },
    async getimgUrl(val, aiType, item) {
      this.aiType = aiType;
      this.imgshow = true;
      this.imgshowurl = val;
      //人流
      if (aiType == 3) {
        this.aiTotal = item.detectPersonCount;
        this.getcanvas(val, item);
      }
      //车流
      if (aiType == 13) {
        // this.aiTotal = item.detectPersonCount;
        let data = JSON.parse(item.jsonData).label;
        console.log(data, "datatat");
        let car = "";
        let van = "";
        let truck = "";
        let bus = "";
        for (let t in data) {
          if (t == "car" && data["car"]) {
            car = "小轿车" + data["car"] + "辆";
          } else if (t == "truck" && data["truck"]) {
            truck = "卡车" + data["truck"] + "辆";
          } else if (t == "van" && data["van"]) {
            van = "面包车" + data["van"] + "辆";
          } else if (t == "bus" && data["bus"]) {
            bus = "巴士" + data["bus"] + "辆";
          }
        }
        this.aiTotal = car + truck + van + bus;
        this.getcanvas(val, item);
      }
      //游泳
      if (aiType >= 4) {
        this.getcanvas(val, item);
      }
      //人脸
      if (aiType == 1 || aiType == 2) {
        let data = {
          fileKey: item.visitUrl,
          aiType: aiType,
        };
        let res = await API.FCKERNEL.getFaceResultByFileKey(data);
        if (aiType == 1) {
          this.faceList = res.faceImageInfo?.faceResults;
          this.faceShow = true;
          this.getcanvas(val, res.faceImageInfo);
        } else {
          this.carList = res.aiPlateShiJuResultInfoDtoList;
          this.carShow = true;
          this.getcanvas(val, res);
        }
      }
    },
    async qzjg() {
      let res = await API.DEVICE.forceTakeOver({
        deviceHardId: this.uav.NoticeData.deviceHardId,
      });
      if (res.code == 200) {
        this.$message.success(res.msg);
        this.uav.NoticeFlag = false;
      }
    },
    fly_take_off() {
      // 等待航线上传成功在执行
      this.$refs.TaskListRef.upload_complete();
      // Bus.$emit("take_off");
    },
    getYd() {
      this.controlMenuFlag = !this.controlMenuFlag;
      if (this.collapseFlag == true) {
        // 修改飞控 无人机 左边'任务库'的位置
        Bus.$emit("ydh", false);
      } else {
        Bus.$emit("ydh", true);
      }
    },
    collapseFlagfn() {
      this.collapseFlag = !this.collapseFlag;
      if (this.collapseFlag == true) {
        // 修改飞控 无人机 左边'任务库'的位置
        Bus.$emit("ydh", false);
      } else {
        Bus.$emit("ydh", true);
      }
    },
    Lsdom(item) {
      this.$emit("Lsdom", item);
    },
    clearIdFn() {
      if (this.$refs["player"][0]) {
        this.$refs["player"][0].clearInter();
      }
      if (this.$refs.TaskListRef) {
        this.$refs.TaskListRef.close();
        try {
          let deviceHardId = this.uav.control.device.deviceHardId;
          // this.uav_hide_airway(this.uav.control.device);
          this.uav.online[deviceHardId].positions = [
            this.uav.online[deviceHardId].position,
          ];
        } catch (error) {}
      }
    },
    videoItemFn(index) {
      this.videoItem = index;
      this.$store.commit("mapmanage/SET_MAP_IS_VIDEOITEM", index);
    },
    LoggerFn() {
      this.loggerFlag = !this.loggerFlag;
      // this.collapseFlag = false;
    },
    videoChange() {
      this.videoFlag = !this.videoFlag;
    },
    showTakeOver() {
      this.uav.TakeOverFlag = !this.uav.TakeOverFlag;
      if (this.uav.TakeOverFlag) {
        this.collapseFlag = true;
      }
    },
    // 关闭航线创建列表
    AirwayQuit() {
      this.isAirwayEdit = false;
      // 运行监测关闭
      this.powerFlag = true;
      this.Videoflag = true;
      this.ControlFlag = true;
      this.collapseFlag = false;
    },
    taskTypeFn(item) {
      this.taskType = item;
    },
    // 创建航线
    CraeteRoute() {
      this.isAirwayEdit = true;
      // // 运行监测关闭
      this.powerFlag = false;
      this.ControlFlag = false;
      this.collapseFlag = true;
    },
    createTaskClick() {
      this.CreateTaskFlag = !this.CreateTaskFlag;
      this.controlMenuFlag = false;
    },
    async checkUseOperateFn(device) {
      // 查看是否有控制权限
      let res = await API.FCKERNEL.checkUseOperate({ deviceHardId: device });
      if (res.code == 201) {
        this.$message.warning(res.msg);
        return false;
      } else {
        return true;
      }
    },
    /**
     * 无人机搜索
     */
    onUavSearch() {
      this.uav_list(
        {
          search: this.uavSearchContent,
        },
        false
      );
    },
    //点击任务按钮
    onChangeTask(open) {
      if (open === undefined) {
        this.controlMenuFlag = !this.controlMenuFlag;
      } else {
        this.controlMenuFlag = open;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.player {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
</style>
