<template>
  <div :class="{'full-video': isStatus}" ref="wrap">
    <div class="interact-wrap">
        <div class="cpt_video" :class="big" @click="fn" v-if="flag" ref="video" v-interact>
        <Obstacle v-if="!isStatus"></Obstacle>
        <div class="video">
          <div class="name" v-clipboard:copy="vUrl.vUrl">{{ data.orgName }}-{{ data.deviceName }}</div>
          <div class="type" v-if="networkType">{{ networkType }}</div>
          <div class="types">{{ streamName }}</div>
          <div v-show="!isStatus" class="close" @click="close(data)">{{ $t('common.关闭') }}</div>
        </div>
        <el-tooltip :content="$t('common.模式切换')" placement="bottom" v-if="streamSelect !== 'QingLiu'">
          <div class="cp pa iconfont icon-moshiqiehuan cf modelStyle" @click="change"></div>
        </el-tooltip>
        <components
          :is="playerCom"
          :videoFlag="videoFlag"
          :isStatus="isStatus"
          ref="player"
          :fpvUrl="fpvUrl"
          :data="vUrl"
          :infoflag="infoflag"
          :raw_msg="raw_msg"
          @close="infoflag = false"
        />
        <div class="info" v-if="infoshow && streamSelect == 'QingLiu'">
          <div class="de">
            <div class="title">bitrate:</div>
            <div class="detail">{{ raw_msg ? raw_msg/1000 : "0"}}kbps</div>
          </div>
          <div class="de">
            <div class="title">venc_avg:</div>
            <div class="detail">{{infoData ? infoData.venc_avg/1000 : "0"}}ms</div>
          </div>
          <div class="de">
            <div class="title">venc_last:</div>
            <div class="detail">{{infoData ? infoData.venc_last/1000 : "0"}}ms</div>
          </div>
          <!-- <div class="de">
            <div class="title">push_path:</div>
            <div class="detail"></div>
          </div>
          <div class="de">
            <div class="title">recv_path:</div>
            <div class="detail"></div>
          </div> -->
          <div class="de">
            <div class="title">pushrtt_avg:</div>
            <div class="detail">{{infoData ? infoData.pushrtt_avg[0]/1000 : "0"}}ms</div>
          </div>
          <div class="de">
            <div class="title">pushrtt_last:</div>
            <div class="detail">{{infoData ? infoData.pushrtt_last[0]/1000 : "0"}}ms</div>
          </div>
          <div class="de">
            <div class="title">recvrtt_avg:</div>
            <div class="detail">{{infoData ? infoData.recvrtt_avg[0]/1000 : "0"}}ms</div>
          </div>
          <div class="de">
            <div class="title">recvrtt_last:</div>
            <div class="detail">{{infoData ? infoData.recvrtt_last[0]/1000 : "0"}}ms</div>
          </div>
          <div class="de">
            <div class="title">pushretrans_avg:</div>
            <div class="detail">{{infoData ? (infoData.pushretrans_avg[0]*0.1).toFixed(2) : "0"}}%</div>
          </div>
          <div class="de">
            <div class="title">pushretrans_last:</div>
            <div class="detail">{{infoData ? (infoData.pushretrans_last[0]*0.1).toFixed(2) : "0"}}%</div>
          </div>
          <div class="de">
            <div class="title">recvretrans_avg:</div>
            <div class="detail">{{infoData ? (infoData.recvretrans_avg[0]*0.1).toFixed(2) : "0"}}%</div>
          </div>
          <div class="de">
            <div class="title">recvretrans_last:</div>
            <div class="detail">{{infoData ? (infoData.recvretrans_last[0]*0.1).toFixed(2) : "0"}}%</div>
          </div>
          <!-- <div class="de">
            <div class="title">pzvtdelay:</div>
            <div class="detail">{{infoData ? infoData.pzvtdelay : "0"}}</div>
          </div> -->
          <div class="de">
            <div class="title">vdec:</div>
            <div class="detail">{{infoData ? infoData.vdec/1000 : "0"}}ms</div>
          </div>
          <div class="de">
            <div class="title">vbuffer:</div>
            <div class="detail">{{infoData ? infoData.vbuffer/1000 : "0"}}ms</div>
          </div>
          <!-- <div class="de">
            <div class="title">abuffer:</div>
            <div class="detail"></div>
          </div> -->
        </div>
        <div class="play">
          <el-tooltip v-if="streamSelect == 'QingLiu'" class="left ml24" :content="$t('common.信息')" placement="bottom">
            <div @click="getInfo">
              <img src="~./assets/info.png" alt="">
            </div>
          </el-tooltip>
          <div v-else class="left ml24"></div>
          <div class="right mr14">
            <div class="search mr22">
              <el-select class="video_type mr24" v-model="streamSelect" :placeholder="$t('common.切换源')">
                <el-option
                  v-for="item in streamOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
              <el-select class="big_type" v-model="sizeSelect" :placeholder="$t('common.比例')" @change="changeBig">
                <el-option
                  v-for="item in sizeOptions2"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </div>
            <div class="pointer iconfont icon-gengxin cf f16 mr26" @click="reset"></div>
            <div class="pointer iconfont icon-quanping cf f16" @click="screen"></div>
          </div>
        </div>
        <el-tooltip class="cp pa right10 cf ai" :content="$t('common.AI识别')" placement="bottom">
          <div @click="aiVisible = !aiVisible">
            <img src="~./assets/car.png" />
          </div>
        </el-tooltip>
        <div class="faceAndcar cp pa right70 cf" v-if="aiVisible">
          <el-tooltip :content="$t('common.人脸识别')" placement="bottom">
            <div class="plan" @click="handle('a')">
              <img src="~./assets/faceAI2.png" />
            </div>
          </el-tooltip>
          <el-tooltip :content="$t('common.车辆识别')" placement="bottom">
            <div class="plan" @click="handle('b')">
              <img src="~./assets/carAI2.png" />
            </div>
          </el-tooltip>
        </div>
        <el-tooltip :content="$t('common.拍照')" placement="bottom">
          <div class="cp pa right10 cf plate" @click="photo">
            <img src="~./assets/ai.png" />
          </div>
        </el-tooltip>
      </div>
    </div>
   
    <FaceAI v-if="faceAiShow" :uavId="device.deviceHardId" @closeface="faceAiShow = false" />
    <CarAI
      v-if="carAiShow"
      :uavId="device.deviceHardId"
      :list="carList"
      @closecar="carAiShow = false"
    />
  </div>
</template>

<script>
// import API from "@/api";

import FaceAI from "./components/faceai";
import CarAI from "./components/carai";
import LiveNVRPlayer from "./livenvr/index.vue";
// import QingLiuPlayer from "./flv/index.vue";
import QingLiuPlayer from "./qingliu/index.vue";
import { to_moveMount } from "../../../../../lib/to_moveMount";
import Bus from "mmc/utils/bus.js";
import Obstacle from "./obstacle";

export default {
  name: "Float-Playerfk",
  components: {
    QingLiuPlayer,
    LiveNVRPlayer,
    FaceAI,
    CarAI,
    Obstacle,
  },
  props: {
    device: {
      type: Object,
      default: () => ({}),
    },
    data: {
      type: Object,
      default: () => ({}),
    },
    uavData: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      infoshow: false,//清流视频信息展示
      infoData: null,//清流信息
      raw_msg: 0,
      imgshow: false,//弹出的图片显示
      imgshowurl:"",//弹出的图片路径
      carList: [],        //车牌识别结果
      aiVisible: false,   //打开ai
      faceAiShow: false,
      carAiShow: false,
      flag: true,
      isPlay: true,
      videoFlag: true,
      isStatus: false,
      big: "",
      streamSelect: "", //选择的流
      sizeSelect: 2, //选择的大小
      sizeOptions2: [
        //大小可选项
        {
          value: 1,
          label: "X1",
        },
        {
          value: 2,
          label: "X2",
        },
        {
          value: 3,
          label: "X3",
        },
      ],
      infoflag: false,
      mountData: {},
    };
  },
  computed: {
    /**
     * 播放器组件名
     */
    playerCom() {
      if (this.streamSelect === "QingLiu") {
        return "QingLiuPlayer";
      }
      return "LiveNVRPlayer";
    },
    /**
     * 流类型名
     */
    streamName() {
      let find = this.streamOptions.find((item) => {
        return item.value === this.streamSelect;
      });

      return find?.label || "";
    },

    taskId() {
      return this.$store.state.fckernel.taskId;
    },
    /**
     * 网络类型
     * @returns 专网 | 公网
     */
    networkType() {
      // console.log('网络判断', this.data.videos)
      let name = "";
      try {
        if (this.data.videos.checkOnLine == 1) {
          name = this.$t('common.公网');
        } else {
          if (this.uavData?.link) {
            if (this.uavData?.link[0]?.priority == 2) {
              if (this.uavData?.link[0]?.using) {
                name = this.$t('common.专网');
              } else {
                name = this.$t('common.公网');
              }
            }
            if (this.uavData?.link[0]?.priority == 3) {
              if (this.uavData?.link[0]?.using) {
                name = this.$t('common.公网');
              } else {
                name = this.$t('common.专网');
              }
            }
          }
        }
      } catch (e) {
        console.log(e);
      }

      return name;
    },
    /**
     * 流集合
     */
    streams() {
      let networkKey1 = "";
      let networkKey2 = "";
      if (this.networkType === this.$t('common.专网')) {
        networkKey1 = "private";
        networkKey2 = "public";
      } else {
        networkKey1 = "public";
        networkKey2 = "private";
      }

      let streams = this.data.videos.list[
        networkKey1
      ];
      if(this.networkType == '' && !streams){
        streams = this.data.videos.list[
          networkKey2
        ];
      }
      // console.log('networkKey1', networkKey1, networkKey2, this.data.videos.list[networkKey1], this.data.videos.list[networkKey2])
      return streams;
    },
    /**
     * 流选项
     * @returns [{
          value: "RTC",
          label: "低延迟"
        }]
     */
    streamOptions() {
      let streamOptions = [];
      //清流
      if (this.streams?.qingLiuUrl) {
        window.$Bus.$on("qoeinfo",(e)=>{
          this.infoData = e.data
        })
        window.$Bus.$on("raw_msg",(e)=>{
          this.raw_msg = e.data
        })
        streamOptions.push({
          value: "QingLiu",
          label:this.$t('common.原画'),
        });
      }

      //WS-FLV
      if (this.streams?.socketUrl) {
        streamOptions.push({
          value: "WS-FLV",
          label:  this.$t('common.流畅'),
        });
      }

      //WebRtc
      if (this.streams?.webUrl) {
        streamOptions.push({
          value: "WebRtc",
          label: this.$t('common.低延迟'),
        });
      }

      return streamOptions;
    },
    /**
     * 播放的视频流
     */
    vUrl() {
      let vUrl = "";
      switch (this.streamSelect) {
        case "QingLiu":
          vUrl = this.streams?.qingLiuUrl;
          break;

        case "WS-FLV":
          vUrl = this.streams?.socketUrl;
          break;

        case "WebRtc":
          vUrl = this.streams?.webUrl;
          break;
      }

      return {
        vUrl,
      };
    },
    fpvUrl() {
      return {
        vUrl: this.streams?.fpvUrl || "",
      };
    },
  },
  watch: {
    "$store.state.mapmanage.mapisStatus": function (newVal) {
      if (newVal.type == "wrj") {
        if (this.videoItem == this.index) {
          console.log(
            "$store.state.mapmanage.mapisStatus",
            this.data.videos.list[0]
          );
          this.isStatus = newVal.flag;
          if (this.isStatus) {
            console.log(this.isStatus);
          }
        }
      }
    },
    "$store.state.device.move_data": function (newVal) {
      this.mountData = newVal;
    },
    streamOptions() {
      //当流选项变化时，如果未选择流类型，则自动选择第一个流类型
      if (this.streamSelect == "" && this.streamOptions.length > 0) {
        this.streamSelect = this.streamOptions[0].value;
      }
    },
    networkType() {
      let find = this.streamOptions.find((item) => {
        return item.value == this.streamSelect;
      });
      if (!find) {
        this.streamSelect = ""; //网络类型改变时，未有当前选择的流类型， 则重置
      }
    },
  },
  mounted() {
    window.$uavPlayer = this;
    this.wrapCenter();
    //视屏截图
    Bus.$on("uav_take_photo", ({ callback }) => {
      console.log("uav_take_photo on");
      let blob = this.screenShot();
      callback && callback(blob);
    });
  },
  methods: {
    getInfo(){
      console.log(this.infoData,"infoData");
      this.infoshow = !this.infoshow
    },
    change() {
      this.videoFlag = !this.videoFlag;
    },
    close(data) {
      // if (this.data.videos.list[0].source == "QINGLIU") {
      //   this.$refs.SRSRef.del_player(0)
      // }
      this.$emit("close", data);
    },
    screen() {
      if (this.playerCom === "LiveNVRPlayer") {
        this.$refs.player.$refs["livePlayer"].toggleFullscreen();
      }else{
        this.infoflag = true
        this.$refs.player.fullScreen();
      }
    },
    play() {
      if (this.playerCom === "LiveNVRPlayer") {
        this.$refs.player.$refs["livePlayer"].pause();
        this.isPlay = false;
      }
    },
    pause() {
      if (this.playerCom === "LiveNVRPlayer") {
        this.$refs.player.$refs["livePlayer"].play();
        this.isPlay = true;
      }
    },
    reset() {
      this.flag = false;
      this.$nextTick(() => {
        this.flag = true;
      });
    },
    changeBig(id) {
      this.big = "big_0" + id;
      this.wrapCenter();
    },
    /**
     * 截图
     */
    screenShot() {
      return this.$refs.player.screenShot();
    },
    async photo() {
      if (!this.taskId) {
        this.$message.error(this.$t('common.暂无任务'));
        return;
      }
      let blob = this.screenShot();
      let fd = new FormData();
      fd.append("uploadFile", blob, `${this.$t('common.拍照')}.png`);
      fd.append("taskId", this.taskId);
      fd.append("deviceHardId", this.device.deviceHardId);
      /* let res = await API.FCKERNEL.Upload(fd);
      console.log(res); */
      this.$message.success(this.$t('common.拍照成功'));
      let imgshowurl = process.env.VUE_APP_IMG_URL + '/uploads' +res.fileKey
      this.$emit("imgUrl",imgshowurl)

    },
    handle(command) {
      this.getcanvas(command);
    },
    // 人脸车牌识别
    async getcanvas(command) {
      let blob = this.screenShot();
      let fd = new FormData();
      fd.append("uploadFiles", blob, `${this.$t('common.下载')}.jpeg`);
      /* let res = await API.MAPMANAGE.fileUpload(fd);
      if (command == "a") {
        this.aiuse(res[0].storage);
      } else {
        this.plate(res[0].storage);
      } */
    },
    async aiuse(url) {
      let data = {
        imageUrl: url,
        deviceHardId: this.device.deviceHardId,
      };
      this.$el_message(this.$t('common.正在识别中'), () => {}, "info", 0);
      /* let res = await API.AIUSE.aiphoto(data);
      if (res.code == 200) {
        this.$el_message(this.$t('common.识别成功'), () => {}, "success");
        this.faceAiShow = true;
      } else {
        this.$el_message(res.message, () => {}, "error");
      } */
    },
    async plate(url) {
      let data = {
        imgUrl: url,
        deviceHardId: this.device.deviceHardId,
      };
      this.$el_message(this.$t('common.正在识别中'), () => {}, "info", 0);
      /* let res = await API.AIUSE.palteId(data);
      if (res.code == 200) {
        this.$el_message(this.$t('common.识别完成'), () => {}, "success");
        this.carList = res.data;
        this.carAiShow = true;
      } else {
        this.$el_message(res.message, () => {}, "error");
      } */
    },
    /**
     * 居中
     */
    wrapCenter() {
      this.$nextTick(() => {
        let width = this.$refs.video.clientWidth;
        let height = this.$refs.video.clientHeight;
        let fullWidth = window.innerWidth;
        let fullHeight = window.innerHeight - 100;

        let centerX = fullWidth / 2 - width / 2;
        let centerY = fullHeight / 2 - height / 2;
        this.$refs.wrap.setAttribute("data-x", centerX);
        this.$refs.wrap.setAttribute("data-y", centerY);
        this.$refs.wrap.setAttribute(
          "style",
          `transform: translate(${centerX}px, ${centerY}px)`
        );
      });
    },
    /**
     * 视频指点
     */
    async fn(el) {
      let { mountData, device } = this;
      // if mountStatus =1 代表启用 屏幕指点功能
      if (
        mountData.mountStatus == 1 &&
        device.deviceHardId == mountData.deviceHardId &&
        mountData.moveType == "wrj"
      ) {
        let evt = window.event || el;
        var div = null;
        
        if (this.streamSelect == "QingLiu") {
          // div = document.getElementById("canvas_layer0") ;
          div = document.getElementsByClassName("qingliu")[0]
        } else {
          div = document.getElementsByClassName("vjs-tech")[0];
        }
        let data = {
          x: (evt.offsetX * 1920) / div.offsetWidth - 960,
          y: -((evt.offsetY * 1080) / div.offsetHeight) + 540,
          w: 1920,
          h: 1080,
        };
        let buffer = null;
    
        if (mountData.name == "MMC_Gimbal_Z30Pro") {
          // z30pro
          buffer = await to_moveMount.move_track_focus_ctrl(data.x, data.y);
        } else if (mountData.name == "MMC_Gimbal_Z40S") {
          //z40s
          buffer = await to_moveMount.move_or_focus_ctrl(data);
        } else {
          buffer = await to_moveMount.gcs_click_coordinates(data);
        }
        let mounteList = { data: buffer, ...mountData }
        if (buffer) {
          this.$emit("directiveFn", mounteList);
        }
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.cpt_video {
  cursor: default !important;
  border: 1px solid #fff;
  width: 730px;
  height: 450px;
  background: #333;
  position: fixed;

  .video {
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 99;
    .name {
      position: absolute;
      top: 0;
      left: 0;
      // width: 122px;
      height: 26px;
      background: #000000;
      border-radius: 1px;
      opacity: 0.6;
      line-height: 26px;
      text-align: center;
      font-size: 16px;
      font-family: MicrosoftYaHei-Bold, MicrosoftYaHei;
      font-weight: bold;
      color: #ffffff;
    }
    .type {
      position: absolute;
      top: 0;
      right: 112px;
      width: 56px;
      height: 26px;
      text-align: center;
      line-height: 26px;
      background: #fc8959;
      border-radius: 13px;
      opacity: 0.58;
      backdrop-filter: blur(6.7px);
      font-size: 16px;
      font-family: MicrosoftYaHei-Bold, MicrosoftYaHei;
      font-weight: bold;
      color: #ffffff;
    }
    .types {
      position: absolute;
      top: 0;
      right: 50px;
      width: 56px;
      height: 26px;
      text-align: center;
      line-height: 26px;
      background: #4d9dff;
      border-radius: 13px;
      opacity: 0.58;
      backdrop-filter: blur(6.67px);
      font-size: 16px;
      font-family: MicrosoftYaHei-Bold, MicrosoftYaHei;
      font-weight: bold;
      color: #ffffff;
    }
    .close {
      position: absolute;
      top: 0;
      right: 0;
      height: 26px;
      text-align: center;
      line-height: 26px;
      background: #000000;
      border-radius: 1px;
      opacity: 0.6;
      font-size: 14px;
      font-family: MicrosoftYaHei;
      color: #ffffff;
    }
  }
  .info{
    position: absolute;
    top: 0;
    left: 0;
    z-index: 5;
    padding: 0 10px;
    padding-top: 30px;
    height: calc(100% - 75px);
    background: rgba($color: #000000, $alpha: 0.6);
    .de{
      margin-top: 8px;
      display: flex;
      color: #fff;
      font-size: 14px;
      .detail{
        margin-left: 8px;
      }
    }
  }
  .play {
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 46px;
    background: #000000;
    opacity: 0.7;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .left {
      color: #fff;
      span {
        font-size: 20px;
      }
    }
    .right {
      display: flex;
      align-items: center;
      .search {
        .video_type {
          width: 96px;
          height: 26px;
        }
        .big_type {
          width: 70px;
          height: 26px;
        }
        ::v-deep .el-input--suffix {
          width: 100%;
          height: 100%;
          .el-input__inner {
            width: 100%;
            height: 100%;
          }
        }
        ::v-deep .el-input__suffix {
          display: flex;
          align-items: center;
        }
      }
    }
  }
}
.big_01 {
  width: 416px;
  height: 274px;
}
.big_03 {
  width: 1000px;
  height: 600px;
}
.big_04 {
  top: 0%;
  left: 0;
  width: 100%;
  height: 100%;
}
.ai {
  bottom: 60%;
  z-index: 1;
}
.plate {
  bottom: 45%;
  z-index: 1;
}
.full-video ::v-deep {
  transform: none !important;

  .interact-wrap{
    transform: translate(0px, -100px) !important;
  }

  .cpt_video {
    position: relative;
    left: 0;
    top: 0;
    width: 100vw;
    height: 100vw;
    z-index: 0 !important;

    .ai {
      top: 400px;
      right: 15px;
      height: 36px;
    }

    .faceAndcar {
      top: 407px;
      height: 22px;
    }

    .plate {
      top: 440px;
      right: 15px;
      height: 36px;
    }
  }
}
.modelStyle {
  bottom: 45px;
  right: 12px;
  z-index: 3;
}
  // position: relative;
  .faceAndcar {
    z-index: 1;
    width: 55px;
    bottom: 61%;
    display: flex;
    justify-content: space-between;
      .plan{
        margin-right: 8px;
        display: flex;
        justify-content: center;
        align-items: center;
        width: 30px;
        height: 30px;
        padding: 0 5px;
        background: rgba(9, 32, 87, 0.7);
      }
  }
</style>
