<template>
  <div class="img_bg_camera">
    <el-row :gutter="10" style="padding: 10px; opacity: 0.9;">
      <el-col :span="8">
        <el-card style="margin-top: 10px;">
          <video style="height: 400px; padding: 10px;" id="videoCamera" autoplay></video>
        </el-card>
        <el-card style="margin-top: 10px; height: 165px;">
          <el-row>
            <el-col :span="6">
              <Alarm backgroudColor="#67c23a" :size="60">!</Alarm>
            </el-col>
            <el-col :span="18">
              <div style="display: flex; justify-content: center; align-items: center;">
                <p>数据采集间隔：</p>
                <el-select v-model="time" placeholder="时间" style="width: 90px;">
                  <el-option label="5秒钟" :value="5000"></el-option>
                  <el-option label="15秒钟" :value="15000"></el-option>
                  <el-option label="30秒钟" :value="30000"></el-option>
                </el-select>
                <el-button style="margin-left: 10px;" type="primary" @click="timeChange()">确定</el-button>
              </div>
              <el-button style="margin-top: 10px;" type="danger" @click="Medicalalarm()">医疗报警</el-button>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
      <el-col :span="16">
        <el-card style="margin-top: 10px;">
          <canvas style="display:none; " id="canvasCamera" width="250" height="250"></canvas>
          <div style="display: flex; justify-content: center; align-items: center; height: 85vh;">
            <el-card class="contain" style="display: flex; justify-content: center; align-items: center;">
              <p>标题</p>
              <div style="width: 850px; height: 570px;">
                <!-- 返回的内容展示 -->
                <div style="display: flex; align-items: flex-start; justify-content: flex-start; padding-bottom: 10px;">
                  <el-tag style="font-size: 14px; font-weight: bold;">分析结果：</el-tag>
                </div>
                <div style="height: 450px; overflow-y: auto; ">
                  <div v-for="apiMessage in AiMessage" :key="apiMessage">
                    <el-card style="margin: 10px;">
                      <div style="display: flex; align-items: center;">
                        <el-row>
                          <el-col :span="4">
                            <img :src="apiMessage.imgUrl" alt="图片" v-if="imgif"
                              style="width: 100px; height: 100px; margin-right: 10px;">
                            <el-tag>{{ apiMessage.time }}</el-tag>
                          </el-col>
                          <el-col :span="20">
                            <p>{{ apiMessage.content }}</p>
                          </el-col>
                        </el-row>
                      </div>
                    </el-card>
                  </div>
                </div>
              </div>
            </el-card>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-button style="margin-top: 10px;" type="success" @click="setImage()">开启识别</el-button>
    <el-button style="margin-top: 10px;" type="warning" @click="stopImageCapture()">停止识别</el-button>

  </div>
</template>

<script>
import axios from 'axios';
import Alarm from '@/element/Alarm.vue';

export default {
  components: {
    Alarm
  },
  data() {
    return {
      imgif: false,
      videoWidth: 250,
      videoHeight: 250,
      imgSrc: '',
      thisCancas: null,
      thisContext: null,
      thisVideo: null,
      imga: '',
      intervalId: null,//
      AiMessage: [
      ],
      time: "5000",//拍照时间间隔
    }
  },
  methods: {
    getCompetence() {
      this.thisCancas = document.getElementById('canvasCamera');
      this.thisContext = this.thisCancas.getContext('2d');
      this.thisVideo = document.getElementById('videoCamera');

      // 简化对 navigator.mediaDevices 的支持检查
      if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
        console.error('浏览器不支持 mediaDevices API');
        return;
      }

      // 获取所有视频输入设备
      navigator.mediaDevices.enumerateDevices().then(devices => {
        const videoDevices = devices.filter(device => device.kind === 'videoinput');

        if (videoDevices.length === 0) {
          console.error('没有找到视频输入设备');
          return;
        }

        // 假设你想使用第一个外设摄像头
        const externalCamera = videoDevices[0].deviceId;

        const constraints = {
          audio: false,
          video: {
            deviceId: { exact: externalCamera },
            width: this.videoWidth,
            height: this.videoHeight,
            transform: 'scaleX(-1)'
          }
        };

        navigator.mediaDevices.getUserMedia(constraints).then(stream => {
          // 使用现代方式设置视频流
          this.thisVideo.srcObject = stream;
          this.thisVideo.onloadedmetadata = () => {
            this.thisVideo.play();
          };
          console.log("打开摄像头");
        }).catch(err => {
          console.error('获取媒体输入失败', err);
        });
      }).catch(err => {
        console.error('获取设备列表失败', err);
      });
    },
    // 将时间戳转换为日期格式
    convertTimestampToDate(timestamp) {
      const date = new Date(timestamp * 1000);
      const formattedDate = date.toLocaleString();
      return formattedDate;
    },
    //  绘制图片（拍照功能）
    sendImageToServer(imgData) {
      this.$message({
        message: '已完成一次数据采集，正在分析...',
        type: 'info'
      });
      axios.post('http://49.233.248.140:8081/apiSend', {
        image: imgData
      }).then(response => {
        if (response.data.msg === "ok") {
          this.$message({
            message: '图像数据分析成功！',
            type: 'success'
          });
          console.log(response.data, "返回的数据");
          let Recievecontent = response.data.choices[0].message.content;
          let RecieveImgUrl = "http://49.233.248.140:8081/images/" + response.data.imgUrl;
          let RecieveTime = this.convertTimestampToDate(response.data.created);
          this.AiMessage.push({ content: Recievecontent, imgUrl: RecieveImgUrl, time: RecieveTime })
          console.log(this.AiMessage);
        }
      }).catch(error => {
        console.error('发送图片时出错', error);
      });
    },
    setImage() {
      console.log("开始拍照")
      this.imgif = true;
      var _this = this;
      // 如果已经有一个定时器在运行，先清除它
      if (this.intervalId) {
        clearInterval(this.intervalId);
      }
      // 立即拍照一次
      this.captureImage();
      // 设置定时器，每隔time秒拍照一次
      this.intervalId = setInterval(function () {
        _this.captureImage();
      }, this.time); // 根据用户选择的时间间隔
    },
    captureImage() {
      // 点击，canvas画图
      this.thisContext.drawImage(this.thisVideo, 0, 0, 250, 250);
      console.log(this.thisContext);

      // 获取图片base64链接
      var image = this.thisCancas.toDataURL('image/png');
      this.imgSrc = image;
      window.sessionStorage.setItem("img", this.imgSrc);
      this.sendImageToServer(this.imgSrc);
      console.log(this.imgSrc, "图片显示");
    },
    // 创建一个新方法来停止拍照
    stopImageCapture() {
      if (this.intervalId) {
        this.$message({
          message: '停止采集',
          type: 'warning'
        });
        clearInterval(this.intervalId);
        console.log("停止拍照");
      }
    },
    //关闭摄像头并上传数据
    openFullScreen1() {
      this.thisVideo.srcObject.getTracks()[0].stop(),//关闭摄像头

        setTimeout(() => {
          // var file = this.imga.substr(22)
          this.imga = window.sessionStorage.getItem("img")
          var file = this.imga
          console.log(file);
          //base64数据放formData里面
          var formData = new FormData(); //*
          formData.append("multipartFile", file); //*
          // formData.append("password", this.ruleForm.password); //*
          // formData.append("username", this.ruleForm.name); //*
          console.log(formData, 'formData');
          //自己配置axios。
          // this.$http.post('url接口', formData).then(res => {
          //   console.log(res);

          // })
        }, 2000);
    },
    timeGet() {
      axios.get('http://49.233.248.140:8081/timeGet').then(response => {
        if (response.data.msg === "ok") {
          this.time = response.data.time;
        }
      }).catch(error => {
        console.error('获取时间间隔时出错', error);
      });
    },
    timeChange() {
      console.log(this.time);
      axios.get('http://49.233.248.140:8081/timeChange', {
        params: {
          time: this.time
        }
      }).then(response => {
        if (response.data.msg === "ok") {
          this.$message({
            message: '时间间隔修改成功！',
            type: 'success'
          });
        }
      })
    },
    Medicalalarm() {
      this.$notify({
        title: '成功',
        message: '医疗报警已发送！',
        type: 'success'
      });
    }
  },
  mounted() {
    this.getCompetence();
    this.timeGet();
  },

}
</script>
<style lang="less" scoped>
// 设置背景图片
.img_bg_camera {
  background-image: url(../image/back.png);
  background-size: 100% 100%;
  height: 750px;
  width: 100%;
  margin: 0 auto;
  text-align: center;
}

.contain {
  height: 90%;
  width: 95%;
  opacity: 0.9;
}
</style>