<template>
  <div class="app-container" style="height: 100vh;">
    <!-- v-loading="loading" -->
    <!-- element-loading-text="拼命加载中" -->
    <!-- element-loading-spinner="el-icon-loading" -->
    <!-- element-loading-background="rgba(0, 0, 0, 0.8)" -->
    <div class="ntgs" style="padding: 0;">
      <el-row :gutter="10" class="mb8">
        <div class="iuer" style="margin-bottom:10px;">
        </div>
      </el-row>
      <div>
        <el-row :gutter="20">
          <!-- postList -->
          <el-col :span='4'>
            <div style="background-color: #fff;border-radius: 10px;padding: 20px 20px;height: 95vh;">
              <p
                style="margin: 0;border-left: 6px solid #03BF8A;margin-left: -20px;padding-left: 10px;font-weight: 800;">
                通道管理</p>
              <div :class="ishge == index ? 'anche' : ''"
                style=" height: 36px;;line-height: 36px;margin-top: 10px;padding: 0 10px;"
                v-for="(item,index) in channelNumberList" :key="index">
                <div @click="ishg(item,index)"
                  style="display: flex;align-items: center;justify-content: space-between;">
                 <el-tooltip class="item" effect="dark" :content="item.channelNum == null?'暂无数据' : item.channelNum" placement="top-start">
                                   <div style="font-size: 16px;
                 color: #333333; overflow:hidden;text-overflow:ellipsis;white-space:nowrap;"> {{item.channelNum == null?'暂无数据' : item.channelNum}}</div>
                 </el-tooltip>
                  <img src="../../../assets/images/icon_htgl_zd.png" alt="" style="width: 10px;height: 12px;">
                </div>
              </div>


            </div>
          </el-col>
          <!-- v-if="isshoe" -->
          <el-col :span='14'
            style="padding-left: 30px; background-color: #fff;border-radius: 10px;padding: 20px; height: 95vh;">
            <div style="display: flex;align-items: center;justify-content: space-between;margin-bottom: 18px;">
              <p
                style="margin: 0;border-left: 6px solid #03BF8A;margin-left: -20px;padding-left: 10px;font-weight: 800;">
                坐标点配置
                <!-- <span style="font-size: 12px; color: red;cursor: pointer;" @click="xiazag">下载插件</span> -->
              </p>
              <div>
                <!-- <el-button type="danger" plain>删除</el-button> -->
                <span style="font-size: 12px; color: red;">(点击保存之前，请先确认参数配置和坐标点配置都完成)</span>
                <el-button type="warning"  v-hasPermi="['manage:parameterSet:add']" plain @click="submitForm">保存</el-button>
                <el-button type="success" plain>关闭</el-button>
              </div>
            </div>
              <div>
                <div class="tool-box" style="margin: 0;padding: 0;height: 80px;text-align: left;">

                  <!-- <div>
                    <el-button
                      size="mini"
                      :type="isDrawing ? 'warning' : 'primary'"
                      @click="startDraw"
                      >绘制区域</el-button
                    >

                    <el-button
                      size="mini"
                      type="danger"
                      :disabled="isDrawing"
                      @click="clearAll"
                      >全部清除</el-button
                    >
                    <el-button
                      size="mini"
                      type="success"
                      :disabled="isDrawing"
                      @click="savePoints"
                      >保存</el-button
                    >
                  </div> -->
                  <div class=" ">
                    <div style="display: flex;">
                      <el-button :type="isDrawing ? 'warning' : 'primary'"  @click="startDraw">绘制区域</el-button>
                      <el-button type="primary" :disabled="isDrawing" plain @click="savePoints">保存</el-button>
                      <el-button type="primary" plain @click="clearAll">全部清除</el-button>
                    </div>

                    <!-- <div style="flex: 1;"></div> -->
                    <!-- <el-button type="primary" plain @click="clickCapturePic">抓图</el-button> -->
                  </div>
                  <div style="margin-top: 5px;">
                    <p style="text-align: left; margin: 0;font-size: 13px;color: #FF6969;">每次绘制前,点击绘制按钮开始绘制，单击鼠标左键即是当前点绘制完成可绘制下一个点， 双击鼠标左键即本次绘制完成。</p>
                  </div>
                </div>
                <div class="canvas-wrap">
                  <canvas id="imgCanvas" ref="canvaxbox"></canvas>
                  <!--用来和鼠标进行交互操作的canvas-->
                  <canvas
                    id="drawCanvas"
                    ref="canvas"
                    :style="{ cursor: isDrawing ? 'crosshair' : 'default' }"
                  >
                  </canvas>
                  <!--存储已生成的点线，避免被清空-->
                  <canvas id="saveCanvas" ref="canvasSave"></canvas>
                </div>
              </div>
            <!-- <div style="width: 100%; height: 70vh;">
              <div v-if="isfse" id="divPlugin" style="width: 100%; height: 69vh;"></div>

            </div> -->


            <!-- <img src="../../../assets/images/pic_ssyl_lt.png" alt="" style="width: 100%; margin-top: 20px;"> -->
            <!-- 344 -->
            <!-- <video id="video" controls autoplay muted width="100%" height="480px"style="margin-top: 20px;"></video> -->
            <!-- <video
        						      class="videosmall"
        						      ref="videosmallone"
        						      preload="auto"
        						      muted
        						      autoplay
        							  width="95%"
        						      type="rtmp/flv"
        						    >
        						      <source src="" />
        						    </video> -->
          </el-col>
          <el-col :span="6">
            <div style="background-color: #fff;border-radius: 10px;padding: 20px 20px;height: 95vh;">
              <p
                style="margin: 0;border-left: 6px solid #03BF8A;margin-left: -20px;padding-left: 10px;font-weight: 800;">
                参数配置</p>
              <div>
                <el-form ref="form" :model="form" :rules="rules" label-width="60px">
                  <p style="margin: 0; margin-top: 10px; color:#03BF8A ; margin-bottom: 10px;">时间配置(分钟 <span
                      style="font-size: 12px;color: #FEA71B;">只能输入正数</span>)</p>
                  <el-form-item label="离岗" prop="leaveTime">
                    <el-input :min="0" type="number" v-model="form.leaveTime" placeholder="请输入离岗时间设置 默认：10 分钟" />
                  </el-form-item>
                  <el-form-item label="玩手机" prop="playTime">
                    <el-input :min="0" type="number" v-model="form.playTime" placeholder="请输入玩手机时间设置 默认：10 分钟" />
                  </el-form-item>
                  <p style="margin: 0; margin-top: 10px; color:#03BF8A ; margin-bottom: 10px;">相似度配置<span
                      style="font-size: 12px;color: #FEA71B;">(只能输入正数)</span></p>
                  <el-form-item label="离岗" prop="leaveRate">
                    <el-input :min="0" :max="1" type="number" v-model="form.leaveRate"
                      placeholder="请输入离岗时间相似度设置 默认：0.5" />
                  </el-form-item>

                  <el-form-item label="玩手机" prop="playRate">
                    <el-input :min="0" :max="1" type="number" v-model="form.playRate"
                      placeholder="请输入玩手机相似度设置 默认：0.5" />
                  </el-form-item>
                </el-form>
              </div>
              <p
                style="margin: 0;border-left: 6px solid #03BF8A;margin-left: -20px;padding-left: 10px;font-weight: 800;">
                绘制区域</p>
              <div class="drawings-list">
                <div class="tflex" v-for="(shape, index) in shapes" :key="index">
                  <!-- :class="{ selected: selectedIndex === index }" -->
                  <div class="txt">
                    <el-popover placement="top-start" width="200" trigger="hover">
                      <div v-for="(ite,idx) in shape.points">
                        {{ite.x}},{{ite.y}}
                      </div>
                      <div slot="reference" class="snhseinu">
                        <el-input v-model="shape.name" placeholder="请输入内容"></el-input>
                      </div>
                    </el-popover>
                  </div>
                <img class="delimg" src="../../../assets/images/del.png"
                    @click.stop="clickDelSnapPolygon(shape.id,index)" />
                </div>
              </div>
            </div>
          </el-col>

          <!-- <el-col :span="24">
				<div class="ihgswq wrapper"  ref="wrapper" style=" overflow: hidden;">
						  <div class="fijge content nhgwesvq" ref="content" style="width:1610px;">
									<div class='shotw '   v-for="(item,index) in postList" :key="index" @click="isfgw(item)" >
											  <img src="../../../assets/images/fengm.png" alt="">
												<img src="../../../assets/images/icon_spjk_play.png" alt="" class="iges">
											  <p style="font-size: 14px;">{{item.name}}</p>
									</div>
						  </div>
				</div>
			</el-col> -->
        </el-row>


        <!-- <pagination
	     v-show="total>0"
	     :total="total"
	     :page.sync="queryParams.pageNo"
	     :limit.sync="queryParams.pageSize"
	     @pagination="getList"
	   /> -->
      </div>


    </div>

    <!-- 添加或修改岗位对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>

    </el-dialog>

    <el-dialog :title="titles" :visible.sync="opens" width="1000px" append-to-body>
    </el-dialog>

    <el-dialog title="页面二维码" :visible.sync="opent" width="200px" style="padding: 0;" class="nhgrls" append-to-body>
      <div v-show="opent" style="display: flex;justify-content: center;align-items: center;">
        <!-- <span>{{'https://qszdh.qs163.cn/pages/index/index?id=' + this.bg}}</span> -->
        <!-- <vue-qr   :text="'https://qszdh.qs163.cn/pages/index/index?id=' + this.bg" :size="200"></vue-qr> -->
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listChannelNumber,
    listChannelNumbernopa,
    getChannelNumber,
    delChannelNumber,
    addChannelNumber,
    updateChannelNumber
  } from "@/api/system/channelNumber"
  import {
    listWarnManage,
    getWarnManage,
    delWarnManage,
    addWarnManage,
    updateWarnManage
  } from "@/api/manage/warnManage"
  import {
    listParameterSet,
    getParameterSet,
    delParameterSet,
    addParameterSet,
    updateParameterSet
  } from "@/api/manage/parameterSet"
  // import { listReservat,camera,cameraIndexCode, listReservatd, getReservat, delReservat, addReservat, updateReservat,setPass,delReservathx,openDz,closeDz } from "@/api/tonggi/houtai";
  // import vueQr from "vue-qr";
  // import videojs from 'video.js'
  // import 'video.js/dist/video-js.css'
  // import {videoPlayer} from 'vue-video-player'
  // import 'videojs-flash'
  // import flvjs from 'flv.js/dist/flv.min.js'
  // import flvjs from "flv.js";
  import Bscroll from "better-scroll";
  import logoImg from '@/assets/images/ceshi.png'
  const defaultSettings = require("@/settings.js");
  export default {
    name: "Post",
    dicts: ['sys_normal_disable', 'sys_yes_no', 'youke', 'tjzh', 'youkes', 'lafafen', 'fange', 'jluly'],
    // components: {
    //     vueQr,
    //  videoPlayer
    //   },
    data() {
      return {
        // 遮罩层
        loading: true,
        opent: false,
        bg: null,
        titles: '',
        editableTabsValue: '6',
        opens: false,
        // 通道管理表格数据
        channelNumberList: [],
        imageUrl: '@/assets/logo/logo.png',
        printObj: {
          id: "nhgrew", // 这里是要打印元素的ID
          popTitle: "", // 打印的标题
        },
        pickerOptions: {
          disabledDate(time) {
            //disabledDate 文档上：设置禁用状态，参数为当前日期，要求返回 Boolean
            // return time.getTime() > Date.now()//选当前时间之前的时间
            return time.getTime() < Date.now() - 8.64e7; //选当前时间之后的时间
          }
        },
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        checkedScoreDataDetails: [],
        scoreDataDetailsList: [],
        tabPosition: 'left',
        // 非多个禁用
        multiple: true,
        defaultSettings:defaultSettings,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 岗位表格数据
        postList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNo: 1,
          pageSize: 500,
          name: null,
          postCode: undefined,
          postName: undefined,
          status: undefined,
          reservatType: undefined
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          receptionId: [{
            required: true,
            message: "不能为空",
            trigger: "blur"
          }],
        },
        ruless: {
          visitName: [{
            required: true,
            message: "不能为空",
            trigger: "blur"
          }],
          visitPhone: [{
            required: true,
            message: "不能为空",
            trigger: "blur"
          }],
          visitNum: [{
            required: true,
            message: "不能为空",
            trigger: "blur"
          }],
          visitDate: [{
            required: true,
            message: "不能为空",
            trigger: "blur"
          }],
          visitTime: [{
            required: true,
            message: "不能为空",
            trigger: "blur"
          }],

        },
        forms: {
          parameterId: null,
          channelId: null,
          equipmentId: null,
          equipmentNum: null,
          equipmentName: null,
          channelNum: null,
          channelRange: null,
          leaveTime: 10,
          playTime: 10,
          leaveRate: 0.5,
          playRate: 0.5,
          delFlag: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null
        },
        tableMaxHeight: '200',
        kje: 0,
        ksjegsg: [],
        Scroll: null,
        videoShow: false,
        flvPlayer: null,
        player: null,
        name: null,
        isshiwa: false,
        isjfwe: {},
        isshoe: false,
        webRtcServer: null,
        camera_ip: '127.0.0.1:8000',
        g_iWndIndex: 0,
        iRtspPort: '', //预览中的ip
        szDeviceIdentify: '', //ip_port,
        isfse: false,

        g_bEnableDraw: false,
        // 所有绘制的图形
        shapes: [],
        // 禁用
        isdisflag: false,
        connectionStatus: '',
        isConnected: false,
        connecting: false,
        messages: [{
          type: 'sent',
          content: '',
          timestamp: ''
        }],
        messageToSend: [],
        mqttConfig: {
          url: 'ws://13.229.167.76:1884/mqtt',
          topic: 'detection/rect'
        },
        mqttThemeName: {
          url: 'ws://13.229.167.76:1884/mqtt',
          topic: 'detection/rect'
        },
        ishge: 0,
        ips: '',
        isdesl: false,
        imgUrl: "../../../assets/images/fengm.png",
        isDrawing: false, // 是否正在绘制
        ratio: 1,
        imgWidth: 3020,
        imgHeight: 1080,
        wrapWidth: 600,
        wrapHeight: 300,
        canvasWidth: 600,
        canvasHeight: 300,
        drawingPoints: [],
        drawedPoints: [],
        imgCanvas: null,
        imgCtx: null,
        drawCanvas: null,
        drawCtx: null,
        saveCanvas: null,
        saveCtx: null,
        srt:logoImg,
        submitData: [
        ],
        connectionStatus:'',
        isConnected:false,
        connecting:false,
        messages:[{ type: 'sent' , content: '', timestamp: '' }],
        messageToSend:[],
      };
    },
    created() {
      this.isfse = false
      // this.getList();
      this.getListtd()
      window.onresize = () => {
        this.changeTableMaxHeight()
      }
      this.changeTableMaxHeight()

    },
    mounted() {
      // this.toggleConnection()
      // this.webRtcServer = new WebRtcStreamer('video', location.protocol + '//' + this.camera_ip)
      //      //需要查看的rtsp地址,根据自己的摄像头传入对应的rtsp地址即可。注意：视频编码格式必须是H264的，否则无法正常显示，编码格式可在摄像头的后台更改
      //      this.webRtcServer.connect('rtsp://admin:zxy123456@192.168.101.64:554/h264/ch1/main/av_stream')
      window.onresize = () => {
        this.changeTableMaxHeight()
        this.initCanvas();
        this.getImage();
      }
      this.changeTableMaxHeight()
      this.$nextTick(() => {
        this.initScroll()
      })

    },

    beforeDestroy() {

    },
    methods: {
      /** 查询通道管理列表 */
      getListtd() {
        this.loading = true
        let queryParams = {}
        listChannelNumbernopa().then(response => {
          this.channelNumberList = response.rows
          if (this.channelNumberList.length != 0) {
            getChannelNumber(this.channelNumberList[0].channelId).then(response => {
              if (response.data.isChannel != 'N') {
                this.shapes = JSON.parse(response.data.parameterSet.channelRange)
                this.form = response.data.parameterSet
                let result = (this.form.leaveTime / 60).toFixed(1);
                let resultl = (this.form.playTime / 60).toFixed(1);
                this.form.channelId = response.data.channelId
                this.form.isChannel = response.data.isChannel
                this.form.equipmentNum = response.data.equipmentNum
                this.form.equipmentId = response.data.equipmentId
                this.form.equipmentName = response.data.equipmentName
                this.form.channelNum = response.data.channelNum
                this.ips = response.data.equipmentIp
                this.form.leaveTime = result
                this.form.playTime = resultl
                this.nshgehuixw()
              } else {
                this.form = {
                  parameterId: null,
                  channelId: response.data.channelId,
                  equipmentId: response.data.equipmentId,
                  equipmentNum: response.data.equipmentNum,
                  equipmentName: response.data.equipmentName,
                  channelNum: response.data.channelNum,
                  channelRange: null,
                  isChannel: response.data.isChannel,
                  leaveTime: 10,
                  playTime: 10,
                  leaveRate: 0.5,
                  playRate: 0.5,
                  delFlag: null,
                  createBy: null,
                  createTime: null,
                  updateBy: null,
                  updateTime: null,
                  remark: null
                }
                this.ips = response.data.equipmentIp
              }
              this.form.photoAddress = response.data.photoAddress
              this.initCanvas();
              this.getImage(this.form.photoAddress);
            })
          }
          this.loading = false
          // getWarnManage(this.$route.query.id).then(response => {
          // this.form = response.data
          this.loading = false
        })
      },
      // 回显
      nshgehuixw(){
        let sngseju = []
        this.shapes.filter(rou=>{
          let sngsejutoe = []
          for(var i=0; i< rou.points.length;i++ ){
            let sngsejq = []
            sngsejq.push(rou.points[i].x,rou.points[i].y)
            sngsejutoe.push(sngsejq)
          }
          console.log(sngsejutoe)
          sngseju.push(sngsejutoe)
        })

        this.drawedPoints =  sngseju
        let objectPoints = [];
        // "object": [{"polygon": {"x1":700,"y1":273,"x2":975,"y2":278,"x3":1107,"y3":368,"x4":718,"y4":354} }]
        objectPoints = this.drawedPoints.map((area) => {
          console.log(area)
          let polygon = {};
          area.forEach((point, i) => {
            console.log(point)
            polygon[`x${i + 1}`] = (point[0] * this.drawCanvas.width).toFixed(1);
            polygon[`y${i + 1}`] = (point[1] * this.drawCanvas.height).toFixed(1);
          });
          // console.log(polygon)
          return {
            polygon: polygon,
          };
        });
        this.submitData = objectPoints;
        // console.log("最终提交数据", objectPoints);
        this.messageToSend = this.submitData
        console.log(this.drawedPoints,this.submitData)
        this.renderDatas()
      },
      // 画图
      initCanvas() {
        // 初始化canvas画布

        let canvasWrap = document.getElementsByClassName("canvas-wrap");
        this.wrapWidth = canvasWrap[0].clientWidth;
        this.wrapHeight = canvasWrap[0].clientHeight;

        this.imgCanvas = document.getElementById("imgCanvas");
        this.imgCtx = this.imgCanvas.getContext("2d");

        // 绘制canvas
        this.drawCanvas = document.getElementById("drawCanvas");
        this.drawCtx = this.drawCanvas.getContext("2d");

        // 保存绘制区域 saveCanvas
        this.saveCanvas = document.getElementById("saveCanvas");
        this.saveCtx = this.saveCanvas.getContext("2d");
        // this.initImgCanvas()
      },
      initImgCanvas() {
        // 计算宽高比
        let ww = this.wrapWidth; // 画布宽度
        let wh = this.wrapHeight; // 画布高度
        let iw = this.imgWidth; // 图片宽度
        let ih = this.imgHeight; // 图片高度

        if (iw / ih < ww / wh) {
          // 以高为主
          this.ratio = ih / wh;
          this.canvasHeight = wh;
          this.canvasWidth = (wh * iw) / ih;
        } else {
          // 以宽为主
          this.ratio = iw / ww;
          this.canvasWidth = ww;
          this.canvasHeight = (ww * ih) / iw;
        }
        // 初始化画布大小
        this.imgCanvas.width = this.canvasWidth;
        this.imgCanvas.height = this.canvasHeight;
        this.drawCanvas.width = this.canvasWidth;
        this.drawCanvas.height = this.canvasHeight;
        this.saveCanvas.width = this.canvasWidth;
        this.saveCanvas.height = this.canvasHeight;

        // 图片加载绘制
        let img = document.createElement("img");
        img.src = this.imgUrl;
        console.log(this.imgUrl)
        img.onload = () => {
          console.log("图片已加载");
          this.imgCtx.drawImage(img, 0, 0, this.canvasWidth, this.canvasHeight);
          this.renderDatas(); // 渲染原有数据
        };
      },
      startDraw() {
        // 绘制区域
        if (this.isDrawing) return;
        this.isDrawing = true;
        // 绘制逻辑
        this.drawCanvas.addEventListener("click", this.drawImageClickFn);
        this.drawCanvas.addEventListener("dblclick", this.drawImageDblClickFn);
        this.drawCanvas.addEventListener("mousemove", this.drawImageMoveFn);
      },
      clearAll() {
        // 清空所有绘制区域
        this.saveCtx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
        this.drawedPoints = [];
        this.shapes = []
      },
      getImage(row) {
        // 这里请求接口 ...
        // this.srt = row
        this.imgUrl =  this.defaultSettings.urls +  process.env.VUE_APP_BASE_API + row ;
        // this.imgUrl = this.srt
        // this.imgWidth = 1920;
        // this.imgHeight = 1080;
        // this.imgUrl =JSON.parse(this.$route.query.src)
        this.imgWidth = 660;
        this.imgHeight = 380;
        console.log(this.imgUrl,98)
        this.imgUrl && this.initImgCanvas();
      },
      drawImageClickFn(e) {
        let drawCtx = this.drawCtx;
        if (e.offsetX || e.layerX) {
          let pointX = e.offsetX == undefined ? e.layerX : e.offsetX;
          let pointY = e.offsetY == undefined ? e.layerY : e.offsetY;
          let lastPoint = this.drawingPoints[this.drawingPoints.length - 1] || [];
          if (lastPoint[0] !== pointX || lastPoint[1] !== pointY) {
            this.drawingPoints.push([pointX, pointY]);
          }


        }
      },
      drawImageMoveFn(e) {
        let drawCtx = this.drawCtx;
        if (e.offsetX || e.layerX) {
          let pointX = e.offsetX == undefined ? e.layerX : e.offsetX;
          let pointY = e.offsetY == undefined ? e.layerY : e.offsetY;
          // 绘制
          drawCtx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
          // 绘制点
          drawCtx.fillStyle = "blue";
          this.drawingPoints.forEach((item, i) => {
            drawCtx.beginPath();
            drawCtx.arc(...item, 6, 0, 180);
            drawCtx.fill(); //填充
            // console.log(item)
          });

          // 绘制动态区域
          drawCtx.save();
          drawCtx.beginPath();
          this.drawingPoints.forEach((item, i) => {
            drawCtx.lineTo(...item);
          });
          drawCtx.lineTo(pointX, pointY);
          drawCtx.lineWidth = "3";
          drawCtx.strokeStyle = "blue";
          drawCtx.fillStyle = "rgba(255, 0, 0, 0.3)";
          drawCtx.stroke();
          drawCtx.fill(); //填充
          drawCtx.restore();
        }
      },
      drawImageDblClickFn(e) {
        let drawCtx = this.drawCtx;
        let saveCtx = this.saveCtx;
        if (e.offsetX || e.layerX) {
          let pointX = e.offsetX == undefined ? e.layerX : e.offsetX;
          let pointY = e.offsetY == undefined ? e.layerY : e.offsetY;
          let lastPoint = this.drawingPoints[this.drawingPoints.length - 1] || [];
          if (lastPoint[0] !== pointX || lastPoint[1] !== pointY) {
            this.drawingPoints.push([pointX, pointY]);
          }
        }
        // 清空绘制图层
        drawCtx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
        // 绘制区域至保存图层
        this.drawSaveArea(this.drawingPoints);
        this.drawedPoints.push(this.drawingPoints);
        this.drawingPoints = [];
        this.isDrawing = false;
        // 绘制结束逻辑
        this.drawCanvas.removeEventListener("click", this.drawImageClickFn);
        this.drawCanvas.removeEventListener("dblclick", this.drawImageDblClickFn);
        this.drawCanvas.removeEventListener("mousemove", this.drawImageMoveFn);
      },
      drawSaveArea(points) {
        console.log(points, "points");
        if (points.length === 0) return;
        this.saveCtx.save();
        this.saveCtx.beginPath();
        points.forEach((item, i) => {
          this.saveCtx.lineTo(...item);
        });
        this.saveCtx.closePath();
        this.saveCtx.lineWidth = "2";
        this.saveCtx.fillStyle = "rgba(255,0, 255, 0.3)";
        this.saveCtx.strokeStyle = "red";
        this.saveCtx.stroke();
        this.saveCtx.fill(); //填充
        this.saveCtx.restore();
      },

      savePoints() {
        // 将画布坐标数据转换成提交数据
        let objectPoints = [];
        // "object": [{"polygon": {"x1":700,"y1":273,"x2":975,"y2":278,"x3":1107,"y3":368,"x4":718,"y4":354} }]
       console.log(this.drawedPoints,)
        objectPoints = this.drawedPoints.map((area,t) => {
          console.log(t)
          let polygon = [];
          let name = '绘制区域' + (t+1)
          area.forEach((point, i) => {
            let nsdfs = {x:null,y:null}
            console.log(point,93)
            nsdfs.x =  point[0] ;
            nsdfs.y = point[1] ;
            nsdfs.x  = ( nsdfs.x / this.drawCanvas.width ).toFixed(6)
            nsdfs.y  = ( nsdfs.y / this.drawCanvas.height).toFixed(6)
            polygon.push(nsdfs)
            this.shapes.filter(rou=>{
              if(rou.points[0].x == nsdfs.x ){
                if(rou.points[0].y == nsdfs.y ){
                  name = rou.name
                }
              }

            })
          });
          console.log(polygon,this.shapes,9123)
          return {
            points: polygon,
            id:t+1,
            name:name,
            ip:this.ips
          };
        });
        this.submitData = objectPoints;
        this.shapes = objectPoints
        console.log("最终提交数据", objectPoints,this.shapes);
        this.messageToSend = this.submitData
        // this.sendMessage()
        // this.$router.go(-1)
      },
      renderDatas() {
        // 将提交数据数据转换成画布坐标
        this.drawedPoints = this.submitData.map((item) => {
          // console.log(item.polygon,item,19)
          let polygon = item.polygon;
          let points = [];
          for (let i = 1; i < Object.keys(polygon).length / 2 + 1; i++) {
            if (!isNaN(polygon[`x${i}`]) && !isNaN(polygon[`y${i}`])) {
              points.push([
                polygon[`x${i}`] ,
                polygon[`y${i}`] ,
              ]);
            }
          }
          // console.log(points)
          this.drawSaveArea(points);
          return points;
        });
      },
      //删除图形
      clickDelSnapPolygon(szId, idx) {
        console.log(3)
        this.shapes.splice(idx, 1)
        // this.shapes.splice(idx,1)
        let shzou = []
        // "object": [{"polygon": {"x1":700,"y1":273,"x2":975,"y2":278,"x3":1107,"y3":368,"x4":718,"y4":354} }]
        for(var i = 0 ; i <this.shapes.length; i++){
          this.shapes[i].id= i+ 1
        }
        this.saveCtx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
        this.nshgehuixw()
        // this.submitData = this.shapes
        // this.drawedPoints = this.shapes

        // this.renderDatas()
        console.log(this.shapes,shzou)

      },

      // 通道点击
      ishg(val, row) {
        this.isfse = false
        this.ishge = row
        getChannelNumber(val.channelId).then(response => {
          if (response.data.isChannel == 'Y') {
            this.form = response.data.parameterSet
            let result = (this.form.leaveTime / 60).toFixed(1);
            let resultl = (this.form.playTime / 60).toFixed(1);
            this.shapes = JSON.parse(this.form.channelRange)
            this.form.channelId = response.data.channelId
            this.form.isChannel = response.data.isChannel
            this.form.equipmentNum = response.data.equipmentNum
            this.form.equipmentId = response.data.equipmentId
            this.form.equipmentName = response.data.equipmentName
            this.form.channelNum = response.data.channelNum
            this.ips = response.data.equipmentIp
            this.form.leaveTime = result
            this.form.playTime = resultl
            this.form.photoAddress = response.data.photoAddress
            this.initCanvas();
            this.getImage(this.form.photoAddress);
            this.saveCtx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
            this.nshgehuixw()
          } else {
            this.form = {
              parameterId: null,
              channelId: response.data.channelId,
              equipmentId: response.data.equipmentId,
              equipmentNum: response.data.equipmentNum,
              equipmentName: response.data.equipmentName,
              channelNum: response.data.channelNum,
              channelRange: null,
              isChannel: response.data.isChannel,
              leaveTime: 10,
              playTime: 10,
              leaveRate: 0.5,
              playRate: 0.5,
              delFlag: null,
              createBy: null,
              createTime: null,
              updateBy: null,
              updateTime: null,
              remark: null
            }
            this.shapes = []
            // this.drawSaveArea = []
             this.submitData = []
            this.ips = response.data.equipmentIp
            this.form.photoAddress = response.data.photoAddress
            this.initCanvas();
            this.getImage(this.form.photoAddress);
            this.saveCtx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
            // this.ips = snghst[0]
          }
        })
        // this.clickStartRealPlay('192.168.101.64', '80',1, 0, 1);

      },
      initScroll() {
        // 给内层盒子设置宽度，不设置宽度的话无法滚动
        // let width = this.goods.length * 60
        // // 如果有外边距，可以这样写。需要去掉最后一个元素的外边距，在后面减一下
        // let width = this.goodslength * (60 + 10) - 10
        let width = 6 * (200 + 10) - 10
        // this.$refs.content.style.width = width + 'px'
        this.$nextTick(() => {
          if (!this.Scroll) {
            this.Scroll = new Bscroll(this.$refs.wrapper, {
              click: true, // 配置允许点击事件
              scrollX: true, // 开启横向滚动
              eventPassthrough: 'vertical', // 当设置 eventPassthrough 为 'vertical' 的时候，scrollY 无效
              mouseWheel: true,
              scrollbar: { // 滚动条, 要加相对位置
                fade: true
              }
            })
          } else {
            this.Scroll.refresh() // 重新计算 better-scroll，当 DOM 结构发生变化的时确保滚动效果正常
          }
        })
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.opens = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          receptionId: undefined,
          receptionPhone: undefined,
          // postSort: 0,
          // status: "0",
          receptionName: undefined
        };
        this.resetForm("form");
      },

      iszheg(event) {
        console.log(event);


        // 校验身份证：
        console.log(reg.test(this.form.idCard), 23741)
        if (reg.test(this.form.idCard) || _IDre15.test(this.form.idCard)) {
          // this.idea();
          this.go(this.form.idCard);
          // callback()
        } else {
          if (ncjsle.test(this.form.idCard) || nhyeli.test(this.form.idCard)) {
            console.log(3)
          } else {
            if (gnse.test(this.form.idCard)) {
              console.log(4)
            } else {
              if (tw.test(this.form.idCard) || twe.test(this.form.idCard)) {
                console.log(5)
              } else {
                this.$message.error('证件格式不正确');
              }
            }

          }
        }
      },
      erw(row) {
        this.$router.push({
          path: '/reny/ewm',
          query: {
            'tenantId': row.investigateTableId
          }
        })
      },

      /** 成绩_子序号 */
      rowScoreDataDetailsIndex({
        row,
        rowIndex
      }) {
        row.index = rowIndex + 1;
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const postIds = row.recordId || this.ids;
        delReservat(postIds).then(response => {
          this.$modal.msgSuccess("操作成功");
          this.getList();
        });

        // this.$modal.confirm('是否确认删除数据项？').then(function() {
        //   return delPost(postIds);
        // }).then(() => {
        //   this.getList();
        //   this.$modal.msgSuccess("删除成功");
        // }).catch(() => {});
      },
      handleDeletehx(row) {
        const postIds = row.reservatId || this.ids;
        let nhg = {}
        nhg.reservatId = postIds
        delReservathx(nhg).then(response => {
          this.$modal.msgSuccess("操作成功");
          this.getList();
        });

        // this.$modal.confirm('是否确认删除数据项？').then(function() {
        //   return delPost(postIds);
        // }).then(() => {
        //   this.getList();
        //   this.$modal.msgSuccess("删除成功");
        // }).catch(() => {});
      },
      // 发送短信
      handleUpdatefas(row) {
        updateFs(row).then(response => {
          this.$modal.msgSuccess("发送成功");
          // this.getList();
        });
      },
      handleDeletegx(row) {
        updateGx(row).then(response => {
          this.$modal.msgSuccess("发送成功");
          // this.getList();
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('system/reservat/export', {
          ...this.queryParams
        }, `预约人员.xlsx`)
      },
      // 获取屏幕高度
      showFilterForm() {
        this.filterActive = !this.filterActive
        this.changeTableMaxHeight()
      },
      changeTableMaxHeight() {
        let height = document.body.offsetHeight // 网页可视区域高度
        // if (this.filterActive) {
        //   this.tableMaxHeight = height - 320
        // } else {
        this.tableMaxHeight = height - 350
        // }
        console.log(height)
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            // console.log(this.form)
            // return
            this.form.leaveTime = (this.form.leaveTime - 0) * 60
            this.form.playTime = (this.form.playTime - 0) * 60
            this.form.channelRange = JSON.stringify(this.shapes)
            if (this.form.isChannel != 'N') {
              updateParameterSet(this.form).then(response => {
                this.$modal.msgSuccess("修改成功")
                this.open = false
                let result = (this.form.leaveTime / 60).toFixed(1);
                let resultl = (this.form.playTime / 60).toFixed(1);
                this.form.leaveTime = result
                this.form.playTime = resultl
                // this.$router.go(-1)
              })
            } else {
              addParameterSet(this.form).then(response => {
                this.$modal.msgSuccess("新增成功")
                this.open = false
                // this.$router.go(-1)
                let result = (this.form.leaveTime / 60).toFixed(1);
                let resultl = (this.form.playTime / 60).toFixed(1);
                this.form.leaveTime = result
                this.form.playTime = resultl
              })
            }
          }
        })
      },
      xiazag() {
        var loadUrl = 'http://172.28.195.154:15010/prod-api/profile/HCWebSDKPluginsUserSetup.exe'
        window.open(loadUrl, );
       // const x = new XMLHttpRequest()
       //   x.open('GET', 'http://192.168.9.240:5010/profile/HCWebSDKPluginsUserSetup.zip', true)
       //   x.responseType = 'blob'
       //   x.onload = function() {
       //     const url = window.URL.createObjectURL(x.response)
       //     const a = document.createElement('a')
       //     a.href = 'http://192.168.9.240:5010/profile/HCWebSDKPluginsUserSetup.zip'
       //     a.download = ''
       //     a.click()
       //   }
       //   x.send()
      }
    }
  };
</script>

<style lang="scss">
  .snhseinu {
    .el-input--medium .el-input__inner {
      border: none;
    }
  }

  .isjses {
    .el-tabs--left .el-tabs__nav-wrap.is-left::after {
      width: 6px;
    }

    .el-tabs--left .el-tabs__active-bar.is-left,
    {
    width: 6px;
  }
  }

  .ingaqe {
    .el-input--medium {
      width: 100%;
    }
  }

  .nhgrls {
    .el-dialog__body {
      padding: 0;
    }
  }

  .hyr {
    span {
      text-decoration: underline;
    }
  }
</style>
<style scoped lang="scss">
  .tool-box {
    width: 98%;
    height: 40px;
    padding: 5px 30px;
    margin: 20px auto 0;
    box-sizing: border-box;
    text-align: right;
  }
  .canvas-wrap {
    // width: 80vw;
    // height: 45vw;
    width:100%;
    height: 69vh;
    margin: 0px auto;
    background-color: #fff; //#fff;
    border: 3px;
    border-color: #333;
    position: relative;
  }
  #imgCanvas,
  #drawCanvas,
  #saveCanvas {
    background: rgba(255, 0, 255, 0);
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
  #drawCanvas {
    z-index: 2;
  }
  .nghwgq {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin-top: 90px;

    div {
      color: #aaa;
    }
  }

  .ihgswq {
    // width:100%;
    // overflow-x: hidden;
    // margin-top: 30px;
  }

  .fijge {
    // width: 110%;
    display: flex;
    display: -webkit-flex;
    justify-content: space-between;

    .shotw {
      position: relative;
      // width:32%;
      width: 238px;
      height: 140px;
      margin-left: 0;
      margin-right: 20px;
      margin-bottom: 15px;

      img {
        height: 100%;
        cursor: pointer;
      }

      p {
        // bottom:-10px;
        margin: 0;
        font-weight: bold;
        font-size: 16px;
        padding: 5px 10px;
        cursor: pointer;
      }

      .iges {
        position: absolute;
        top: 50%;
        left: 50%;
        width: 30px;
        height: 30px;
        transform: translate(-50%, -50%);
        cursor: pointer;
      }
    }
  }

  .nhgwesvq {
    width: 1610px !important;
  }

  .shotw {
    position: relative;
    margin-left: -20px;
    margin-right: -20px;

    img {
      width: 100%;
      height: 80vh;
    }

    p {
      position: absolute;
      bottom: 0;
      left: 0;
      background-color: rgba(0, 0, 0, .5);
      width: 100%;
      padding: 13px 5px;
      color: #fff;
      font-weight: bold;
      font-size: 18px;
    }

    .p {
      top: 0px;
      height: 60px;
      margin: 0;
      padding-left: 20px;
    }
  }


  .ksfpo {
    background-color: #3464EB;
    padding: 6px 12px;
    border-radius: 4px;
    color: #fff;
    cursor: pointer;
  }

  .ksfpok {
    background-color: #FFFFFF;
    padding: 5px 11px;
    border-radius: 4px;
    color: #3464EB;
    border: 1px solid #3464EB;
    margin-left: 10px;
    cursor: pointer;
  }

  .ksfpofg {
    background-color: #75DB75;
    padding: 5px 11px;
    border-radius: 4px;
    color: #FFFFFF;
    border: 1px solid #75DB75;
    margin-left: 10px;
    cursor: pointer;
  }

  .iuer {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .ite {
      display: flex;
      justify-content: space-between;
      align-items: center;

      p {
        cursor: pointer;
        margin: 0;
        font-size: 15px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #666666;
        padding: 4px 12px;
        background: #Fff;
        border-radius: 4px;
        margin-right: 20px;
        position: relative;
      }

      .actt {
        background: #fff;
        // border-bottom: 3px solid #5974E0;
        // border-radius: 0;
        // border-bottom-right-radius: 4px;
        color: #5974E0;
      }

      .actt {
        &::after {
          content: "";
          width: 40%;
          height: 5px;
          border-radius: 3px;
          transform: translate(-50%);
          background-color: #5974E0;
          position: absolute;
          left: 50%;
          bottom: -3px;
        }

      }

    }
  }

  .lqw {
    padding: 0 10px;
    margin: 0;
    margin-bottom: 20px;
  }

  .nhgel {
    height: 170px;
    background-color: #313b61;
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 0;
  }

  .app-container {
    background-color: #f3f4f6;
    padding-top: 10px;
    height: 180vh;

  }

  .ntgs {
    position: relative;
    // background-color: #fff;
    padding: 5px;
    // border-radius: 5px;
    padding-top: 10px;
    padding: 10px 20px;

    .pagination-container {
      height: 50px;
    }
  }

  .nghfs {
    position: relative;
    background-color: #fff;
    padding-top: 18px !important;
    padding: 5px;
    // border-radius: 5px;
    // margin-bottom: 20px;
  }

  .ksf {
    img {
      width: 100%;
      height: 100%;
    }
  }

  .ingwfaq {
    font-weight: bold;
    font-size: 16px;
  }

  .dflex {
    display: flex;
  }

  .dflext {
    display: flex;
    align-items: flex-start;
  }

  .drawings-list {
    width: 100%;
    flex: 0 0 auto;
    padding-left: 10px;
    line-height: 36px;

    .delimg {
      width: 15px;
      height: 15px;
      margin-left: 5px;
    }

    .txt {
      font-size: 12px;
      padding-left: 5px;
      flex: 1;
    }

    .tflex {
      display: flex;
      align-items: center;
    }
  }

  .disbtn {
    display: flex;
    align-items: center;
    flex: 0 0 auto;
    min-height: 34px;
    cursor: pointer;

    img {
      width: 14px;
      height: 14px;
      margin-right: 10px;
    }

    font-weight: 500;
    font-size: 14px;
    color: #444444;
  }

  .anche {
    background: #E7F1EE !important;
    border-radius: 4px !important;
    font-weight: 400;

    div {
      color: #03BF8A !important;
    }
  }
</style>
