<!--  -->
<template>
  <div id="app" ref="wrap">
    <div class="left" :style="`width:${imgWidth}px`">
      <img
        v-if="isShibie"
        class="img1"
        :src="img2"
        :style="`height:${imgHeight}px;width:${imgWidth}px`"
      />
      <img
        v-else
        class="img"
        :src="img"
        :style="`height:${imgHeight}px;width:${imgWidth}px`"
      />

      <canvas
        id="myCanvas"
        ref="myCanvas"
        @click="findRect"
        @mousedown="mousedown"
        @mouseup="mouseup"
        @mousemove="mousemove"
      ></canvas>
    </div>

    <div class="right" :style="`left:${imgWidth}px;`">
      <!-- width:calc(100% - ${imgWidth}px) -->
      <i
        class="el-icon-close close"
        style="font-size: 24px; color: #777; cursor: pointer"
        @click="goBackPage"
      ></i>
      <div class="tabs" style="position: absolute; top: 50px">
        <el-radio-group
          v-model="showType"
          size="small"
          @change="changeShowType"
        >
          <el-radio-button :label="1">机器识别</el-radio-button>
          <el-radio-button :label="2">人工修正</el-radio-button>
        </el-radio-group>
        <div class="shugang"></div>
      </div>
      <div v-if="showType == 1">
        <p class="title">基础操作</p>
        <el-button type="primary" size="mini" @click="resetShiBie"
          >重新识别</el-button
        >
      </div>
      <div v-if="showType == 2">
        <p class="title" style="display: flex; align-items: center">
          <span>害虫名称</span>
          <el-tooltip
            style="margin-left: 4px; color: #646464"
            class="item"
            effect="dark"
            content="自定义识别备注信息(例:XX虫)"
            placement="right-end"
          >
            <i class="el-icon-question"></i>
          </el-tooltip>
        </p>
        <div class="inputText">
          <!-- maxlength="10" -->
          <el-input
            class="btn"
            type="text"
            size="mini"
            @input="aaa = aaa.replace(/\s+/g, '')"
            v-model.trim="aaa"
            placeholder="点击左侧框内再输入标注信息"
          ></el-input>
          <el-button  type="primary" size="mini" @click="sure">确定</el-button>
        </div>
      </div>
      <div class="shiBieInfo">
        <p class="title">识别信息：</p>
        <template v-if="showLabelList.length">
          <div v-for="(v, i) in showLabelList" :key="i">
            <span
              >{{ v.label }}
              <span v-show="v.No" style="color: red">({{ v.No }})</span></span
            ><span>{{ v.value }}个</span>
          </div>
        </template>
        <div v-else>
          <img
            style="height: 196px; margin: 0 auto"
            src="../../../static/images/quexingye.png"
            alt=""
          />
        </div>
      </div>
      <div class="sub">
        <el-button
          v-if="showType == 2"
          size="mini"
          @click="qingkong"
          class="pagebtn"
          >重置</el-button
        >
        <el-button
          v-if="showType == 2"
          :disabled="isDisabled"
          @click="sub"
          size="mini"
          >提交</el-button
        >
      </div>
      <div
        style="
          margin: 100px auto 0;
          display: flex;
          justify-content: space-around;
        "
      >
        <el-button
          size="mini"
          :disabled="imgIdsIndex === 0"
          style="margin-left: 0"
          @click="cut('上')"
          class="pagebtn"
          >上一页</el-button
        >
        <el-button
          size="mini"
          :disabled="imgIdsIndex === this.equipStatusObj.ids_list.length - 1"
          style="margin-left: 0"
          @click="cut('下')"
          class="pagebtn"
          >下一页</el-button
        >
      </div>
    </div>
  </div>
</template>

<script>
import { color } from "highcharts";
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import { jsonp } from "vue-jsonp";
import insect_dict from "../../../static/js/cbd_pest_library";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    return {
      imgBL: 0.4,
      imgWidth: 1240,
      imgHeight: 930,
      aaa: "", //标识框
      downX: 0, //鼠标点击图片落下时的位置（X）
      downY: 0, //鼠标点击图片落下时的位置（Y）
      ctx: "", //dom节点
      rectWidth: 0, //矩形框的宽
      rectHeight: 0, //矩形框的高
      showType: 1, //默认机器？
      canvas: null,
      atime: null,
      wrap: null, //创建元素的父元素
      rectTag: false,
      flag: false,
      isNullLabel: false, //机器识别是否有数据
      isShibieimg: false, //识别图是否存在
      isShibie: false, //控制显示原图还是识别图
      delIndex: "",
      img: "", //原图
      img2: "", //识别图
      totalRect: [], //画的所有的矩形坐标长度数据存储在数组中
      titleList: [],
      initDataList: [],
      indentify_result: [],
      labelList: [], //机器识别后的数组
      // 虫子标签
      showLabelList: [],
      // 点击人工修正之前保存上次数据
      rgxzBeforeList: [],
      // 虫子key 以及 value
      bearListLabel: Object.keys(insect_dict),
      bearListValue: Object.values(insect_dict),
      // 接收图片id，index
      equipStatusObj: {
        ids: this.$route.query.data.ids,
        identify_model: this.$route.query.identify_model,
        ids_list: this.$route.query.ids_list,
        ids_index: this.$route.query.index,
      },
      imgIdsIndex: 0, //图片id下标

      // 存储颜色列表
      colorList: [],
      // ffff00 是 没有名字的颜色  red高亮

      // 控制并发
      isDisabled: false,
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    aaa(val) {
      console.log("val.length", val.length);
      if (val.length > 10) {
        this.$message.error("长度不可超过10个");
        this.aaa = val.slice(0, 10);
        console.log(this.aaa);
      }
    },
    isShibie(val) {
      console.log("isShibie", val);
      console.log("isNullLabel", this.isNullLabel);
      console.log("isShibieimg", this.isShibieimg);
    },
  },
  //方法集合
  methods: {
    // 获取随机颜色
    setColors() {
      // return "#" + Math.floor(Math.random() * 0xffffff).toString(16);
      var str = "0123456789abcdef";
      //用另一个字符串来存储#
      var colorStr = "#";
      for (var i = 1; i <= 6; i++) {
        colorStr += str[parseInt(Math.random() * str.length)];
      }
      return colorStr;
    },
    clearData() {
      console.log("清空清空");
      this.showType = 1;
      this.isNullLabel = false;
      this.isShibieimg = false;
      this.isShibie = false;
      this.delIndex = "";
      this.img = "";
      this.img2 = "";
      this.totalRect = [];
      this.titleList = [];
      this.initDataList = [];
      this.indentify_result = [];
      this.labelList = [];
      this.showLabelList = [];
      this.rgxzBeforeList = [];
      this.colorList = [];
    },
    cut(e) {
      this.clearAll(1);
      this.clearAll(2);
      this.clearData();
      if (e === "上") {
        this.imgIdsIndex--;
        console.log(
          "上上上",
          this.imgIdsIndex,
          this.equipStatusObj.ids_list[this.imgIdsIndex]
        );
      } else if (e === "下") {
        this.imgIdsIndex++;
        console.log(
          "下下下",
          this.imgIdsIndex,
          this.equipStatusObj.ids_list[this.imgIdsIndex]
        );
      }
      this.getDataList();
    },
    // 放下鼠标
    mousedown(e) {
      if (this.showType === 1) return;
      this.atime = new Date().getTime();
      this.flag = true;
      this.downX = e.offsetX; // 鼠标落下时的X
      this.downY = e.offsetY; // 鼠标落下时的Y
      this.mousemove(e);
    },
    // 移动鼠标
    mousemove(e) {
      if (this.showType === 1) return;
      if (this.flag) {
        //判断如果重右下往左上画，这种画法直接return
        if (this.downX - e.offsetX > 0 || this.downY - e.offsetY > 0) {
          return;
        } else {
          //如果重左上往右下画，计算出鼠标移动的距离，也就是矩形框的宽和高
          this.rectWidth = Math.abs(this.downX - e.offsetX);
          this.rectHeight = Math.abs(this.downY - e.offsetY);
          //判断这个宽高的长度，如果小于10，直接return，因为鼠标移动距离过于短
          //防止点击页面时,会画成一个点，没有意义
          if (this.rectWidth < 10 || this.rectHeight < 10) {
            this.rectWidth = 0;
            this.rectHeight = 0;
            return;
          }
          this.clear(); //清空画布

          this.redrawAll();
          this.drawRect(
            this.downX,
            this.downY,
            this.rectWidth,
            this.rectHeight,
            "red"
          );
        }
      }
    },
    // 抬起鼠标
    mouseup() {
      if (this.showType === 1) return;
      this.flag = false;
      let a = new Date().getTime();
      if (a - this.atime > 150) {
        this.rectTag = false;
      } else {
        this.rectTag = true;
      }
      if (this.rectWidth || this.rectHeight) {
        //将画出的数据保存在totalRect中
        this.totalRect.push({
          beforex: this.downX,
          beforey: this.downY,
          rectW: this.rectWidth,
          rectH: this.rectHeight,
          j_id: `${this.downX}${this.downY}${this.rectWidth}${this.rectHeight}`,
          flag_id: "2",
          color: "red",
        });
        this.createdDom(
          this.rectWidth,
          this.downX,
          this.downY,
          `${this.downX}${this.downY}${this.rectWidth}${this.rectHeight}`,
          "",
          "2",
          "red"
        );
        this.delIndex = `${this.downX}${this.downY}${this.rectWidth}${this.rectHeight}`;

        // document.getElementById(`span${this.delIndex}`).style.color = "yellow";
        // document.getElementById(`i${this.delIndex}`).style.color = "yellow";
      }
    },
    createdDom(rectW, beforex, beforey, domJid, text, flag_id, color) {
      const span = document.createElement("span");
      span.innerText = text || "";
      span.className = "innerSpan";
      span.id = `span${domJid}`;
      span.setAttribute("key", `span${domJid}`);
      // span.style.cssText = `font-size: 14px;width:${
      //   rectW + 10
      // }px;left:${beforex}px;top:${beforey - 20}px`;
      span.style.cssText = `font-size: 14px;width:90px;left:${beforex}px;top:${
        beforey - 20
      }px;color:${color};`;
      if (flag_id !== "1") {
        span.className = "innerSpan";
        span.appendChild(this.createdDomI(domJid, color));
      } else {
        span.className = "innerSpanJiQi";
      }
      this.wrap.appendChild(span);
    },

    createdDomI(domJid, color) {
      const i = document.createElement("i");
      i.innerText = "✖";
      i.className = "innerSpanI";
      i.id = `i${domJid}`;
      i.setAttribute("data-idx", domJid);
      i.setAttribute("key", `i${domJid}`);
      i.style.color = color;
      i.onclick = (e) => {
        const iDom = e.target;

        this.delIndex = iDom.dataset.idx;
        this.del();
      };
      return i;
    },

    // 高亮
    // hightColor(j_id) {
    //   this.clear();
    //   const showList = this.totalRect.map((v) => {
    //     const data = this.colorList.find((vv) => vv.tag === v.text);
    //     const color = data ? data.color : "#ffff00";
    //     document.getElementById(`span${v.j_id}`).style.color = color;
    //     document.getElementById(`i${v.j_id}`).style.color = color;
    //     return { ...v, color };
    //   });
    //   showList.forEach((e) => {
    //     this.drawRect(e.beforex, e.beforey, e.rectW, e.rectH, e.color);
    //   });

    //   const idx = this.totalRect.findIndex((v) => v.j_id === j_id);
    //   if (idx >= 0) {
    //     const data = this.totalRect[idx];
    //     document.getElementById(`span${j_id}`).style.color = "red";
    //     document.getElementById(`i${j_id}`).style.color = "red";
    //     this.ctx.clearRect(data.beforex, data.beforey, data.rectW, data.rectH);
    //     this.drawRect(
    //       data.beforex,
    //       data.beforey,
    //       data.rectW,
    //       data.rectH,
    //       "red"
    //     );
    //   }
    // },
    hightColor(j_id) {
      this.clear();
      if (j_id) {
        const idx = this.totalRect.findIndex((v) => v.j_id === j_id);
        if (idx >= 0) {
          // const data = this.totalRect[idx];
          this.totalRect[idx].isHigh = true;
          document.getElementById(`span${j_id}`).style.color = "red";
          document.getElementById(`i${j_id}`).style.color = "red";
          // this.ctx.clearRect(data.beforex, data.beforey, data.rectW, data.rectH);
          // this.drawRect(
          //   data.beforex,
          //   data.beforey,
          //   data.rectW,
          //   data.rectH,
          //   "red"
          // );
        }
      }

      const showList = this.totalRect.map((v) => {
        const data = this.colorList.find((vv) => vv.tag === v.text);
        let color = data ? data.color : "#ffff00";
        if (v.isHigh) {
          color = "red";
        }
        v.isHigh = false;
        document.getElementById(`span${v.j_id}`).style.color = color;
        document.getElementById(`i${v.j_id}`).style.color = color;
        return { ...v, color };
      });
      showList.forEach((e) => {
        this.drawRect(e.beforex, e.beforey, e.rectW, e.rectH, e.color);
      });
    },
    //点击画布
    findRect(e) {
      if (this.rectTag) {
        //当点击画布的时候，计算有没有点再矩形框内、哪个矩形框内
        this.totalRect.map((item) => {
          if (
            e.offsetX - item.beforex > item.rectW ||
            e.offsetX < item.beforex ||
            e.offsetY - item.beforey > item.rectH ||
            e.offsetY < item.beforey
          ) {
            return;
          } else {
            //找到之后，设置下标
            // this.delIndex = index;
            this.delIndex = item.j_id;
            this.hightColor(item.j_id);
          }
        });
      }
    },
    redrawAll() {
      const showList = this.totalRect.map((v) => {
        const data = this.colorList.find((vv) => vv.tag === v.text);
        const color = data ? data.color : "#ffff00";
        document.getElementById(`span${v.j_id}`).style.color = color;
        document.getElementById(`i${v.j_id}`).style.color = color;
        return { ...v, color };
      });
      if (showList.length > 0) {
        showList.forEach((e) => {
          this.drawRect(e.beforex, e.beforey, e.rectW, e.rectH, e.color);
        });
      }
    },
    drawRect(x, y, lineW, lineY, color) {
      //   开始绘制;
      this.ctx.beginPath();
      //   //设置线条颜色，必须放在绘制之前
      this.ctx.strokeStyle = color || "#850a1e";
      //   // 线宽设置，必须放在绘制之前
      this.ctx.lineWidth = 2;
      // strokeRect参数：（左上角x坐标，y:左上角y坐标，绘画矩形的宽度，绘画矩形的高度）
      this.ctx.strokeRect(x, y, lineW, lineY);
    },
    //清除画布
    clear() {
      this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
    },
    //点击删除按钮
    del() {
      if (this.totalRect.length != 0 && this.delIndex) {
        const idx = this.totalRect.findIndex((e) => e.j_id === this.delIndex);
        this.ctx.clearRect(
          this.totalRect[idx].beforex - 2,
          this.totalRect[idx].beforey - 2,
          this.totalRect[idx].rectW + 4,
          this.totalRect[idx].rectH + 4
        );
        //删掉totalRect的数据，真正的项目中需要调用后台接口，删掉数据库中存储的数据
        this.totalRect.splice(idx, 1);

        const delSpan = document.getElementById(`span${this.delIndex}`);
        const deli = document.getElementById(`i${this.delIndex}`);
        deli && delSpan.removeChild(deli);
        delSpan && this.wrap.removeChild(delSpan);

        //删掉之后，再画一次，刷新页面
        this.redrawAll();
      } else {
        // this.$message.error('没有要删除的线框');
      }
    },
    sure() {
      if (this.totalRect.length != 0 && this.delIndex) {
        const idx = this.totalRect.findIndex((e) => e.j_id === this.delIndex);
        this.totalRect[idx]["text"] = this.aaa;
        const span = document.getElementById(
          `span${this.totalRect[idx]["j_id"]}`
        );
        span.innerText = this.aaa;
        span.appendChild(this.createdDomI(this.totalRect[idx]["j_id"]));
        var j_id = this.totalRect[idx]["j_id"];

        const { colorList } = this;
        if (colorList && colorList.length) {
          if (colorList.findIndex((v) => v.tag === this.aaa) < 0) {
            this.colorList.push({
              tag: this.aaa,
              color: this.setColors(),
            });
          }
        } else {
          this.colorList.push({
            tag: this.aaa,
            color: this.setColors(),
          });
        }
        this.hightColor();
      }
      this.aaa = "";
      this.delIndex = "";
    },
    sub() {
      var isText = this.totalRect.every((v) => v.text);
      if (isText == false) {
        this.$message("请点选绘制框内部，在右侧输入标记名称");
      } else {
        const data = this.totalRect.filter((v) => v.flag_id === "2");
        this.isDisabled = true;
        this.$axios({
          method: "post",
          url: "/api/api_gateway?method=forecast.forecast_system.cbdphoto_receive",
          data: this.qs.stringify({
            // img_id: sessionStorage.getItem("img_id"),
            img_id: this.equipStatusObj.ids_list[this.imgIdsIndex],
            mark: JSON.stringify(data),
            device_type: "cbd",
            identify_model: this.equipStatusObj.identify_model,
          }),
        })
          .then((res) => {
            this.$message.success("提交完成");
            this.clearAll(2);
            this.getDataList();
            this.$nextTick(() => {
              setTimeout(() => {
                this.isDisabled = false;
              }, 700);
            });
          })
          .catch((_) => {
            this.$nextTick(() => {
              setTimeout(() => {
                this.isDisabled = false;
              }, 700);
            });
          });
      }
      this.delIndex = "";
    },
    clearAll(type) {
      this.clearDom(1);
      this.clearDom(2);
      if (type === 2) {
        this.totalRect.splice(0, this.totalRect.length);
        this.initDataList.splice(0, this.initDataList.length);
      }
      this.labelList.splice(0, this.labelList.length);
    },
    bidui(arr1, arr2) {
      if (arr1.length !== arr2.length) return false;
      const arr1Ids = arr1.map((v) => v.j_id);
      const arr2Ids = arr2.map((v) => v.j_id);
      const result = arr1Ids.filter((v) => {
        return arr2Ids.includes(v);
      });
      if (result.length !== arr1.length) return false;
      return true;
    },
    //返回上一页
    goBackPage() {
      if (this.bidui(this.initDataList, this.totalRect)) {
        this.$router.go(-1);
      } else {
        this.$confirm(
          "关闭此页面将不保留操作记录,如已提交则可忽略,是否继续?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(() => {
            this.$message({
              type: "success",
              message: "已关闭",
            });
            this.$router.go(-1);
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消",
            });
          });
      }
    },
    // 组装机器标注数据
    getJqData(arr, flag_id) {
      const jqData = [];
      if (arr && arr.length) {
        arr.forEach((v) => {
          const key = Object.keys(v)[0];
          const value = Object.values(v)[0];
          const text = insect_dict[key];
          const beforex = value[0] * this.imgBL;
          const beforey = value[1] * this.imgBL;
          const rectW = (value[2] - value[0]) * this.imgBL;
          const rectH = (value[3] - value[1]) * this.imgBL;
          const j_id = `${beforex}${beforey}${rectW}${rectH}`;
          const obj = {
            beforex,
            beforey,
            rectW,
            rectH,
            j_id,
            text,
            flag_id,
          };
          jqData.push(obj);
        });
      }
      return jqData;
    },
    getCZNum(data) {
      const obj = {};
      data.forEach((v) => {
        if (Object.keys(obj).includes(v.text)) {
          obj[`${v.text}`]++;
        } else {
          obj[`${v.text}`] = 1;
        }
      });
      const keys = Object.keys(obj);
      const values = Object.values(obj);

      const arr = keys.map((v, i) => {
        let No = "";
        const idx = this.bearListValue.findIndex((item) => item === v);
        if (idx >= 0) {
          No = this.bearListLabel[idx];
        }
        return { label: v, value: values[i] };
      });
      return arr;
    },
    huixian() {
      const { showLabelList, colorList } = this;
      if (colorList && colorList.length) {
        for (let i = 0; i < showLabelList.length; i++) {
          const { label } = showLabelList[i];
          if (colorList.findIndex((v) => v.tag === label) < 0) {
            this.colorList.push({
              tag: label,
              color: this.setColors(),
            });
          }
        }
      } else {
        this.colorList = showLabelList.map((v) => {
          return {
            tag: v.label,
            color: this.setColors(),
          };
        });
      }

      let showList = [];
      if (this.showType === 1) {
        showList = this.labelList.map((v) => {
          const data = this.colorList.find((vv) => vv.tag === v.text);
          const color = data ? data.color : "#ffff00";
          return { ...v, color };
        });
      } else {
        showList = this.totalRect.map((v) => {
          const data = this.colorList.find((vv) => vv.tag === v.text);
          const color = data ? data.color : "#ffff00";
          return { ...v, color };
        });
      }
      if (showList && showList.length) {
        showList.forEach((e) => {
          this.drawRect(e.beforex, e.beforey, e.rectW, e.rectH, e.color);
          console.log(e.text, e.color);

          this.createdDom(
            e.rectW,
            e.beforex,
            e.beforey,
            e.j_id,
            e.text,
            e.flag_id,
            e.color
          );
        });
      }
    },
    resetShiBie() {
      //生成密钥
      var encrypt = new JSEncrypt();
      // console.log(encrypt);
      var str = `-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC6m92fXUrccS4SoLg4W4jPRNua
4BcRk4ldLcqPuQpD2Mds2+hw+Gi+0MUnshF/r/DTcCJgkt7rtoY9EB6/XJ6MFw14
whhESFie/lZUWRsk8M89Rkr8m5rwmBl+uLAd5LopyshFqKTBXeT2ytHP1JCQLPBO
34Fy4/yEz4qEzkzBuwIDAQAB
-----END PUBLIC KEY-----`;
      encrypt.setPublicKey(str);
      var time = +new Date();
      var str2 = 'YuNfEi'+time+'YuNfEi'
      var encrypted = encrypt.encrypt(str2);
      // console.log(encrypted)
      // return;

      const loading = this.$loading({
        lock: true,
        text: "拼命加载中，请耐心等待",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      let postData = this.qs.stringify({
        // img_id: sessionStorage.getItem("img_id"),
        img_id: this.equipStatusObj.ids_list[this.imgIdsIndex],
        ret: "again",
        device_type: "cbd",
        identify_model: this.equipStatusObj.identify_model,
        sign:encrypted
      });
      this.$axios({
        method: "post",
        url: "/api/api_gateway?method=forecast.forecast_system.equip_photo_discern",
        data: postData,
      }).then((res) => {
        this.clearAll(1);
        this.$nextTick(() => {
          loading.close();
        });
        this.$message.success("重新识别成功");
        if (res.data.data && res.data.data.label) {
          let labelListTag = [];
          if (res.data.data.label) {
            labelListTag = eval("(" + res.data.data.label + ")");
          }
          this.labelList.push(...this.getJqData(labelListTag, "1"));
          console.log(res.data.data.mark);
          // if (res.data.data.mark !== "" && res.data.data.mark.length > 0) {
          //   const mark = res.data.data.mark;
          //   console.log(mark);
          //   this.totalRect.push(...mark);
          //   this.initDataList.push(...mark);
          //   this.getText(this.totalRect);
          //   this.showLabelList = this.getData2();
          // } else {}
          this.showType = 1;
          if (this.totalRect.length == 0) {
            this.totalRect.push(...this.getJqData(labelListTag, "2"));
            this.initDataList.push(...this.getJqData(labelListTag, "2"));
          }
          this.showLabelList = this.getCZNum(this.labelList);
          // this.rgxzBeforeList.push(...this.totalRect);
          this.huixian();
          if (res.data.data.label != "") {
            this.isNullLabel = false;
          }
          this.isShibie = false;
        } else {
          // const mark = this.rgxzBeforeList;
          // this.totalRect.push(...mark);
          // this.initDataList.push(...mark);
          // this.getText(this.totalRect);
          // this.showLabelList = this.getData2();
          this.$message.error(res.data.message);
          if (this.isShibieimg == true) {
            this.isShibie = true;
          }
        }
      });
    },
    getDataList() {
      var postData = this.qs.stringify({
        // img_id: sessionStorage.getItem("img_id"),
        img_id: this.equipStatusObj.ids_list[this.imgIdsIndex],
        cmd: "cbd",
        identify_model: this.equipStatusObj.identify_model,
      });
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=forecast.forecast_system.device_photo_details",
        data: postData,
      }).then((res) => {
        if (res.data.data.addr !== "") {
          // console.log(res.data.data.addr);
          this.img = res.data.data.addr; //未识别图

          var currentImg = new Image(); //获取图片大小
          currentImg.src = this.img;
          currentImg.onload = () => {
            if (currentImg.width >= 5000) {
              this.imgBL = 0.25;
            } else if (currentImg.width >= 4000) {
              this.imgBL = 0.31;
            } else if (currentImg.width < 4000) {
              this.imgBL = 0.4;
            }
            // this.imgBL = currentImg.width <= 4000 ? 0.3 : 0.4;
            this.imgWidth = currentImg.width * this.imgBL;
            this.imgHeight = currentImg.height * this.imgBL;
            this.canvas.width = this.imgWidth;
            this.canvas.height = this.imgHeight;

            if (res.data.data) {
              let labelListTag = [];
              if (res.data.data.label) {
                labelListTag = eval("(" + res.data.data.label + ")");
              }
              this.labelList.push(...this.getJqData(labelListTag, "1"));
              console.log("res.data.data.mark", res.data.data.mark.length);
              if (res.data.data.mark !== "" && res.data.data.mark.length > 0) {
                this.showType = 2;
                if (res.data.data.indentify_photo !== "") {
                  this.img2 = res.data.data.indentify_photo;
                  this.isShibieimg = true; //有识别图
                  if (res.data.data.label == "") {
                    //label为空时人工展示原图机器展示原图
                    this.indentify_result = res.data.data.indentify_result;
                    if (this.showType == 2) {
                      this.isShibie = false;
                    } else {
                      this.isShibie = true;
                    }
                    this.isNullLabel = true;
                  } else {
                    this.isNullLabel = false;
                    this.isShibie = false;
                  }
                } else {
                  this.isShibieimg = false;
                  this.isShibie = false;
                }
                // const mark = eval("(" + res.data.data.mark + ")");
                const mark = res.data.data.mark;
                this.totalRect.push(...mark);
                this.initDataList.push(...mark);
                this.getText(this.totalRect);
                this.showLabelList = this.getData2();
              } else {
                this.showType = 1;
                if (res.data.data.indentify_photo !== "") {
                  this.img2 = res.data.data.indentify_photo;
                  this.isShibieimg = true; //有识别图
                  if (res.data.data.label == "") {
                    //label为空时人工展示原图机器展示原图
                    this.indentify_result = res.data.data.indentify_result;

                    if (this.showType == 2) {
                      this.isShibie = false;
                    } else {
                      this.isShibie = true;
                    }
                    this.isNullLabel = true;
                  } else {
                    this.isNullLabel = false;
                    this.isShibie = false;
                  }
                } else {
                  this.isShibieimg = false;
                  this.isShibie = false;
                }
                this.totalRect.push(...this.getJqData(labelListTag, "2"));
                this.initDataList.push(...this.getJqData(labelListTag, "2"));
                if (this.isShibie == true) {
                  var sum = [];
                  let No = "";
                  var items = this.indentify_result.split("#");
                  for (let j in items) {
                    var dat = items[j].split(",");
                    sum.push({
                      label: insect_dict[dat[0]],
                      value: dat[1],
                      No: [dat[0]].toString(),
                    });
                  }
                  this.showLabelList = sum;
                  console.log("识别------------", this.showLabelList, sum);
                } else {
                  this.showLabelList = this.getCZNum(this.labelList);
                }
              }

              this.rgxzBeforeList.push(...this.totalRect);
              // console.log("showLabelListshowLabelList", this.showLabelList);
              // console.log("totalRect", this.showLabelList);
              console.log("totalRect", this.totalRect);
              console.log("showLabelList", this.showLabelList);
              console.log("colors", this.colorList);
              this.huixian();
            } else {
              if (res.data.data) {
                this.getData(res.data.data.indentify_result);
              }
              // this.$message.error("暂无信息");
            }
          };
        } else {
          this.$message.error("暂无图片");
        }
      });
    },
    getData(arr) {
      const arrNum = arr.split("#");
      this.showLabelList = arrNum.map((v) => {
        const [label, value] = v.split(",");
        return { label: insect_dict[label], value };
      });
    },
    getText(arr) {
      this.titleList = arr.map((v) => {
        return v.text;
      });
    },
    getNum() {
      return this.titleList.reduce((prev, next) => {
        prev[next] = prev[next] + 1 || 1;
        return prev;
      }, {});
    },
    getData2() {
      let myObj = this.getNum(this.titleList);
      let winningList = [];
      for (let i in myObj) {
        let obj = {
          label: i,
          value: myObj[i],
        };
        winningList.push(obj);
      }
      return winningList;
    },
    changeShowType(val) {
      if (val == 1) {
        if (this.isNullLabel) {
          //label为空并且图片为空
          this.isShibie = true;
        }
        if (this.isShibie) {
          var sum = [];
          var items = this.indentify_result.split("#");
          for (let j in items) {
            var dat = items[j].split(",");
            sum.push({
              label: insect_dict[dat[0]],
              value: dat[1],
              No: [dat[0]].toString(),
            });
          }
          this.showLabelList = sum;
        } else {
          this.showLabelList = this.getCZNum(this.labelList);
        }
      } else {
        this.rgxzBeforeList.splice(0, this.rgxzBeforeList.length);
        this.rgxzBeforeList.push(...this.totalRect);
        this.getText(this.totalRect);
        this.showLabelList = this.getData2();

        if (this.isNullLabel) {
          this.isShibie = false;
        }
      }
      this.clearDom(val);
      this.huixian();

      this.delIndex = "";
    },
    // 清除上次显示
    clearDom(val) {
      this.clear();
      if (val === 2) {
        this.labelList.forEach((e) => {
          if (e.flag_id === "1") {
            this.delIndex = e.j_id;
            const delSpan = document.getElementById(`span${this.delIndex}`);
            const deli = document.getElementById(`i${this.delIndex}`);
            deli && delSpan.removeChild(deli);
            delSpan && this.wrap.removeChild(delSpan);
          }
        });
      } else if (val === 1) {
        this.totalRect.forEach((e) => {
          if (e.flag_id === "2") {
            this.delIndex = e.j_id;
            const delSpan = document.getElementById(`span${this.delIndex}`);
            const deli = document.getElementById(`i${this.delIndex}`);
            deli && delSpan.removeChild(deli);
            delSpan && this.wrap.removeChild(delSpan);
          }
        });
      }
      this.delIndex = "";
    },
    qingkong() {
      this.$confirm("将重置为机器识别结果，确定执行？", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        type: "warning",
      })
        .then(() => {
          this.clearDom(1);
          this.totalRect.splice(0, this.totalRect.length);
          const initList = this.labelList.map((v) => {
            const flag_id = "2";
            return { ...v, flag_id };
          });
          console.log("initList", initList);
          this.clear();
          this.totalRect.push(...initList);
          this.redrawAll();
          this.huixian();
          this.delIndex = "";
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.imgIdsIndex = Number(this.equipStatusObj.ids_index);
    console.log("接index", this.imgIdsIndex, typeof this.imgIdsIndex);
    this.canvas = this.$refs.myCanvas;
    this.ctx = this.canvas.getContext("2d");
    this.wrap = this.$refs.wrap;
    this.getDataList();
  },
};
</script>
<style>
.innerSpan {
  display: inline-block;
  position: absolute !important;
  padding-left: 20px;
  height: 20px;
  box-sizing: border-box;
  text-align: left;
  z-index: 999;
  /* color: #ff2e2e; */
}
.innerSpanJiQi {
  display: inline-block;
  position: absolute !important;
  padding-left: 0;
  height: 20px;
  box-sizing: border-box;
  text-align: left;
  z-index: 999;
  /* color: #54ff6d; */
}
.innerSpanI {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  left: 2px;
  font-weight: bold;
  font-size: 10px;
  cursor: pointer;
  /* color: red; */
}
</style>
<style  scoped>
#app {
  width: 100%;
  height: 100vh;
  position: absolute;
  left: 0px;
  top: 0px;
  z-index: 99;
  display: flex;
  background: #ffffff;
  align-content: space-between;
}

.el-input {
  width: 220px !important;
}
.left {
  /* width: 1536px; */
  height: 100vh;
  /* background-color: hsl(0deg 0% 6%) !important; */
}
.img {
  /* width: 1536px;
  height: 864px; */
  position: absolute;
  left: 0px;
  top: 0px;
}
#myCanvas {
  /* width: 1536px;
  height: 864px; */
  position: absolute;
  left: 0px;
  top: 0px;
  /* border: 1px solid pink; */
}

.right {
  /* width: calc(100% - 1536px); */
  /* left: 1536px; */
  width: 378px;
  min-width: 250px;
  height: 100vh;
  position: absolute;
  padding: 100px 30px 100px 50px;
  box-sizing: border-box;
  background-color: #fff;
}
.right .close {
  position: absolute;
  right: 28px;
  top: 15px;
}
.right input {
  width: 120px;
  margin-right: 10px;
}
.right .btn {
  width: 70px;
  /* height: 40px; */
  display: block;
}
.inputText {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
.shiBieInfo {
  font-size: 20px;
  margin: 20px 0 20px;
  height: 300px;
  overflow-y: auto;
}
.shiBieInfo div {
  color: #777;
  font-size: 16px;
  padding-bottom: 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.sub {
  margin: 60px auto 0;
  display: flex;
  justify-content: space-around;
}
.title {
  font-size: 18px;
  color: #272a2e;
  font-weight: 500;
  margin: 50px 0 20px;
}
::-webkit-scrollbar {
  display: none;
}
.shugang {
  background: #fff;
  width: 2px;
  height: 32px;
  position: absolute;
  top: 0;
  left: 77px;
}
.el-button{
  color: #fff;
}
.pagebtn{
  background-color: #fff;
  color: #4f71ff;
}
.pagebtn:hover{
  background-color: #4f71ff;
  color: #fff;
}
</style>
<style lang="less" scoped>
.tabs /deep/.el-radio-button:first-child .el-radio-button__inner {
  border-left: none !important;
}
.tabs /deep/.el-radio-button__inner {
  border: none !important;
}
/deep/.el-radio-button__inner {
  border: none !important;
  border-radius: 0 !important;
}
.tabs /deep/ .el-radio-button__orig-radio:checked + .el-radio-button__inner {
  background-color: #fff !important;
  color: #4f71ff !important;
  // border-left: none !important;
  border: none !important;
  border-bottom: 2px solid #4f71ff !important;
  // border-left-color:transparent !important;
}
.tabs {
  width: 295px;
  border-bottom: 1px solid #ebeef5;
}
.tabs /deep/ .el-radio-button {
  background: transparent;
  color: #9ea7b5 !important;
  border-radius: none !important;
}
</style>

