<template>
  <div class="home">
    <HomeHeader @updataSetting="updataSetting"></HomeHeader>
    <div class="content">
          <div class="content_show">
            <div class="content_show_canvas">
              <canvas ref="myCanvas" id="canvas" width="800" height="600"></canvas>
            </div>
          </div>
          
          <div class="content_operate">
            <ImageVue 
              :confidenceValue="confidenceValue" 
              :IOUValue="IOUValue"
              @openImage="openImage"
              @imageFrame="imageFrame"
              @uploadeImage="uploadeImage"
              @endImage="endImage"
              >
            </ImageVue>
            <hr/>
            <VideoVue
              :confidenceValue="confidenceValue" 
              :IOUValue="IOUValue"
              @oepnVideo="oepnVideo"
              @videoFrame="videoFrame"
              @endVideo="endVideo"
            ></VideoVue>
          </div>
    </div>
    <div style="display: none;">
      <image width="800" height="600" ref="img" :src="imageUrl"></image>
    </div>
    <div style="display: none;">
      <video width="800" height="600" ref="vdo" controls :src="videoUrl"></video>
    </div>
  </div>
</template>

<script>
import HomeHeader from '@/components/header.vue'
import ImageVue from '@/components/image.vue'
import VideoVue from '@/components/video.vue'
export default {
  name: "HomeVue",
  components:{
    HomeHeader,
    ImageVue,
    VideoVue
  },
  data() {
    return {
      confidenceValue:0.7,
      IOUValue:0.45,
      imageUrl:null,
      imageInfo:{
        width:0,
        height:0,
        name:null,
      },

      videoUrl:null,
      videoInfo:{
        width:0,
        height:0,
        name:null,
      },

      ctxBackground:null,

      ctxImage:null,
      ctxImageLabel:null,

      ctxVideo:null,
      
      labelsColor:{
        car:"#0CFF00",//车
        pedestrian:"#00D2FF",//人
        freighter:"#FFEA00",//货船
        houses:"#FF5FF6",//房子
        bridge:"#A200FF",//桥
        boat:"#00FFE4",//船
      }
    }
  },
  created() {

  },
  mounted() {
    this.canvasInit()
  },
  methods: {
    updataSetting(confidenceValue,IOUValue){
      this.confidenceValue = confidenceValue
      this.IOUValue = IOUValue
    },

    canvasInit(){
      let myCanvas = this.$refs.myCanvas
      let ctx = myCanvas.getContext('2d')
      ctx.clearRect(0, 0, w, h);
      var w = myCanvas.width;
      var h = myCanvas.height;
      let img = new Image();
      img.src = require("@/assets/image/showView.png");
      img.onload=()=>{
        ctx.fillStyle = ctx.createPattern(img, 'repeat') // 性质相当于css中的background-image
			  ctx.fillRect(0, 0, w, h) // 最终渲染的位置
      }
    },

    canvasImg() {
      // 获取Canvas 画图
      let myCanvas = this.$refs.myCanvas
      var ctx = myCanvas.getContext('2d')
      var w = myCanvas.width;
      var h = myCanvas.height;
      ctx.clearRect(0, 0, w, h);
      // 在Canvas画布 添加图片
      let img = new Image()
      img.src = this.imageUrl
      img.onload =()=>{
        this.imageInfo.width = img.width
        this.imageInfo.height = img.height

        let w = img.width*800/img.width;
        let h = img.height*600/img.height;
        myCanvas.width = w
        myCanvas.height = h
        ctx.drawImage(img, 0, 0,w,h)
      }
    },

    openImage(url){
      new Promise((resolve, reject) => {
        this.imageUrl = url
        resolve()
      }).then(res=>{
        this.canvasImg()
      })
    },

    //图像检测画框
    imageFrame(res,loadingInstance){
      let myCanvas = this.$refs.myCanvas
      var ctx = myCanvas.getContext('2d')
      var w = myCanvas.width;
      var h = myCanvas.height;
      ctx.clearRect(0, 0, w, h);
      // 在Canvas画布 添加图片
      let img = new Image()
      img.src = this.imageUrl
      img.onload =()=>{
        let rectList = res.results
        let labelList = res.labels
        this.imageInfo.width = img.width
        this.imageInfo.height = img.height

        let w = img.width*800/img.width;
        let h = img.height*600/img.height;
        myCanvas.width = w
        myCanvas.height = h
        ctx.drawImage(img, 0, 0,w,h);
        //位置框框
        ctx.beginPath();
        ctx.lineWidth = 1;
        ctx.font = "20px serif";
        for(let i=0;i<rectList.length;i++){
          switch(labelList[i]){
            case "car":
              ctx.strokeStyle = this.labelsColor.car
              break
            case "pedestrian":
              ctx.strokeStyle = this.labelsColor.pedestrian
              break
            case "freighter":
              ctx.strokeStyle = this.labelsColor.freighter
              break
            case "houses":
              ctx.strokeStyle = this.labelsColor.houses
              break
            case "bridge":
              ctx.strokeStyle = this.labelsColor.bridge
              break
            case "boat":
              ctx.strokeStyle = this.labelsColor.boat
              break
            default:
              ctx.strokeStyle = 'red';

          }
          let x = (800/this.imageInfo.width)*rectList[i][0]
          let y = (600/this.imageInfo.height)*rectList[i][1]
          let width = (800/this.imageInfo.width)*rectList[i][2] - x;
          let height = (600/this.imageInfo.height)*rectList[i][3] - y;
          ctx.strokeRect(x, y, width, height);
          ctx.strokeText(labelList[i],x,y);
        }
      }

      loadingInstance.close();
    },

    uploadeImage(name){
      console.log(name)
      var link = document.createElement("a");
      var imgData =canvas.toDataURL({format: 'jpg',});
      // var strDataURI = imgData.substr(22, imgData.length);
      var blob = this.dataURLtoBlob(imgData);
      var objurl = URL.createObjectURL(blob);
      link.download = name;
      link.href = objurl;
      link.click();
    },
    dataURLtoBlob(dataurl) {
      var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
      while(n--){
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], {type:mime});
    },

    endImage(){
      this.canvasInit();
      this.imageUrl = null;
    },


    canvasVideo(){
      let myCanvas = this.$refs.myCanvas
      var ctx = myCanvas.getContext('2d')
      var w = myCanvas.width;
      var h = myCanvas.height;
      ctx.clearRect(0, 0, w, h);

      const videoEl = document.createElement("video");
      videoEl.src = this.videoUrl;
      
      videoEl.muted = "muted"; 
      videoEl.autoplay = "autoplay";
      videoEl.loop = "loop";
      videoEl.play();

      videoEl.addEventListener("loadedmetadata", (event) => {
        console.log(
          "Yay! readyState just increased to  " +
            "HAVE_CURRENT_DATA or greater for first time.",
        );
      });
      console.log(videoEl.width,videoEl.height)
      const videoRender = () => {
        window.requestAnimationFrame(videoRender);
        ctx.clearRect(0, 0, w, h);
        ctx.drawImage(videoEl, 0, 0, w, h);
      };
      videoRender();
    },

    oepnVideo(url){
      new Promise((resolve, reject) => {
        this.videoUrl = url
        resolve()
      }).then(res=>{
        this.canvasVideo()
      })
    },

    videoFrame(res,loadingInstance){
      this.$message.success ("检测成功，请耐心等待视频加载")
      let myCanvas = this.$refs.myCanvas
      var ctx = myCanvas.getContext('2d')
      var w = myCanvas.width;
      var h = myCanvas.height;
      ctx.clearRect(0, 0, w, h);
      const videoEl = document.createElement("video");
      videoEl.src = this.baseUrl +"/" + res.url;
      this.videoUrl = this.baseUrl +"/" + res.url;
      videoEl.muted = "muted"; 
      videoEl.autoplay = "autoplay";
      videoEl.loop = "loop";
      videoEl.play();
      videoEl.addEventListener("loadeddata", (event) => {
        console.log(
          "Yay! readyState just increased to  " +
            "HAVE_CURRENT_DATA or greater for first time.",
        );
      });
      const videoRender = () => {
        window.requestAnimationFrame(videoRender);
        ctx.clearRect(0, 0, w, h);
        ctx.drawImage(videoEl, 0, 0, w, h);
        loadingInstance.close();
      };
      videoRender();
      
    },
    endVideo(){
      this.canvasInit();
      this.videoUrl = null;
    }

  },
}
</script>

<style scoped lang="scss">
.home {
  width: 100%;
  height: 100%;
  padding: 5px;
  box-sizing: border-box;
}


.content {
  width: 100%;
  .content_show{
    width:100%;
    height: 600px;
    margin-bottom: 20px;
    .content_show_canvas{
      width: 800px;
      height: 600px;
      margin: auto;
    }
  }

  .content_operate{
    width: 100%;


    
  }

}

</style>