<template>
  <div>
    <el-tooltip content="AI识别" placement="bottom">
      <div class="menu-item">
        <img src="./assets/images/car1.png" @click="aiVisible = !aiVisible" />
        <div class="ai-list" v-if="aiVisible">
          <el-tooltip
            v-for="(item,index) in aiIdentifyList"
            :key="index"
            :content="item.title"
            placement="bottom"
          >
            <div class="ai-item" @click="onAiIdentify(item.type)">
              <img class="img_src" :src="item.img" />
            </div>
          </el-tooltip>
        </div>
      </div>
    </el-tooltip>
    <el-dialog :title="`${aiTitle}结果`" :visible.sync="aiResultShow" append-to-body width="700px">
      <div style="text-align: center;">
        <img style="width: 100%;" :src="aiResultImg" />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from "vuex";
import axios from "axios";
import { Control_API, AI_API, ViewLibrary } from "../../../../../../api";
import testImg from "./img";

function blobToBase64(blob) {
  return new Promise((resolve, reject) => {
    let reader = new FileReader();
    reader.onload = () => {
      resolve(reader.result);
    };
    reader.readAsDataURL(blob);
  });
}

export default {
  name: "AIList",
  data() {
    return {
      aiVisible: false,
      aiIdentifyList: [
        {
          title: "人脸识别",
          type: "face",
          typeId: 0,
          img: require("./assets/images/人脸识别.svg"),
        },
        {
          title: "车牌识别",
          type: "plate",
          typeId: 0,
          img: require("./assets/images/车牌识别.svg"),
        },
        {
          title: "人流识别",
          type: "crowd",
          typeId: 0,
          img: require("./assets/images/人流识别.svg"),
        },
        {
          title: "火焰烟雾",
          type: "smoke",
          typeId: 0,
          img: require("./assets/images/烟雾识别.svg"),
        },
        {
          title: "漏油识别",
          type: "oilLeak",
          typeId: 0,
          img: require("./assets/images/漏油识别.svg"),
        },
        {
          title: "裸土识别",
          type: "bareSoil",
          typeId: 0,
          img: require("./assets/images/裸土识别.svg"),
        },
      ],
      aiResultShow: false, //ai识别结果展示
      aiTitle: "",
      aiResultImg: "", //ai结果图
    };
  },
  computed: {
    ...mapState("MMCFlightControlCenter", ["cesiumViewer", "baseUrl"]),
    ...mapState("MMCFlightControlCenter/uav", ["uav"]),
  },
  methods: {
    /**
     * ai识别事件
     */
    onAiIdentify(type) {
      let find = this.aiIdentifyList.find((item) => item.type === type);
      this.aiTitle = find.title;
      let isSuccess = false;
      // 截图做ai识别
      this.$emit("screenShot", {
        callback: async (blob) => {
          let base64 = await blobToBase64(blob);
          let results = [
            /* {
              x: 0,
              y: 0,
              width: 0,
              height: 0,
              label: "",
              prob: 1,
            }, */
          ];
          switch (type) {
            // 车牌识别
            case "plate": {
              let formData = new FormData();
              formData.append("image", blob, `下载.jpeg`);
              formData.append("iscount", 1);
              let res = await AI_API[type](formData);

              results =
                res?.data?.data?.map((item) => {
                  return {
                    x: item.ocRbox.x1,
                    y: item.ocRbox.y1,
                    width: item.ocRbox.x2 - item.ocRbox.x1,
                    height: item.ocRbox.y2 - item.ocRbox.y1,
                    label: item.label,
                    prob: 0,
                  };
                }) || [];

              if (results.length > 0) {
                isSuccess = true;
              }
              break;
            }
            case "face":
            /* {
                // 用的百度
                let formData = new FormData();
                formData.append("image", blob, `下载.jpeg`);
                let res = await AI_API[type](formData);
                results = res?.data?.data?.map((item) => {
                  return {
                    x: item.left,
                    y: item.top,
                    width: item.width,
                    height: item.height,
                    label: "",
                    prob: "",
                  };
                }) || [];
                if (results.length > 0) {
                  isSuccess = true;
                }
              }
              break; */

            // 漏油识别结果
            case "oilLeak":
              {
                let formData = new FormData();
                formData.append("image", blob, `下载.jpeg`);
                formData.append("iscount", 1);
                let res = await AI_API[type](formData);
                results =
                  res?.data?.data?.data?.map((item) => {
                    return {
                      x: item.bbox[0],
                      y: item.bbox[1],
                      width: item.bbox[2] - item.bbox[0],
                      height: item.bbox[3] - item.bbox[1],
                      label: item.label_cn,
                      prob: item.bbox.conf,
                    };
                  }) || [];
                if (results.length > 0) {
                  isSuccess = true;
                }
              }
              break;

            // 共达地通用数据结构
            default:
              {
                let res = await AI_API[type]({
                  image: base64,
                });
                let targets = [
                  {
                    bbox: {
                      box: {
                        left_top_x: 860.5,
                        left_top_y: 1192,
                        right_bottom_x: 1276.5,
                        right_bottom_y: 1304,
                      },
                      color: [0, 0, 255, 255],
                      label: "鲁A99Q90",
                      prob: 1,
                    },
                    region_label: "",
                  },
                  {
                    bbox: {
                      box: {
                        left_top_x: 0,
                        left_top_y: 338,
                        right_bottom_x: 176,
                        right_bottom_y: 562,
                      },
                      color: [0, 0, 255, 255],
                      label: "皖A0",
                      prob: 1,
                    },
                    region_label: "",
                  },
                  {
                    bbox: {
                      box: {
                        left_top_x: 294.5,
                        left_top_y: 1128,
                        right_bottom_x: 374.5,
                        right_bottom_y: 1160,
                      },
                      color: [0, 0, 255, 255],
                      label: "0",
                      prob: 1,
                    },
                    region_label: "",
                  },
                ];

                results =
                  res?.data?.data?.targets?./* targets .*/ map((item) => {
                    return {
                      x: item.bbox.box.left_top_x,
                      y: item.bbox.box.left_top_y,
                      width:
                        item.bbox.box.right_bottom_x - item.bbox.box.left_top_x,
                      height:
                        item.bbox.box.right_bottom_y - item.bbox.box.left_top_y,
                      label: item.bbox.label,
                      prob: item.bbox.prob,
                    };
                  }) || [];

                if (results.length > 0) {
                  isSuccess = true;
                }
              }
              break;
          }

          if (isSuccess) {
            console.log("识别结果", results);
            this.$message.success("识别成功");
            // 将识别结果绘制到图片上
            let img = new Image();
            img.onload = async () => {
              let width = img.width;
              let height = img.height;
              console.log("图片宽度:", width, "高度:", height);

              // 现在可以在Canvas上绘制图片和矩形框
              let canvas = this.drawOnCanvas(img, width, height, results);

              // 展示识别结果
              this.aiResultImg = canvas.toDataURL("image/svg");
              this.aiResultShow = true;
              // 识别结果上传到视图库

              canvas.toBlob(async (blob1) => {
                console.log("识别结果", blob1);
                let formData = new FormData();
                formData.append("file", blob1, `ai识别.jpeg`);
                let uploadRes = await ViewLibrary.uploadFile(formData);

                if (uploadRes.code === 0) {
                  let formData1 = new FormData();
                  formData1.append("file", blob, `原图.jpeg`);
                  let uploadRes1 = await ViewLibrary.uploadFile(formData1);

                  if (uploadRes1.code === 0) {
                    let img = uploadRes.data;
                    let img1 = uploadRes1.data;
                    ViewLibrary.create({
                      fileUrl: img1,
                      fileType: 0,
                      detectorType: find.typeId,
                      deviceId: this.uav.deviceId,
                      aiData: JSON.stringify(results),
                      aiImageUrl: img,
                    });
                  }
                }
              });
            };
            img.src = base64;
            // img.src = testImg;
          } else {
            this.$message.error("识别失败");
          }
        },
      });
    },
    drawOnCanvas(img, width, height, aiResults) {
      let canvas = document.createElement("canvas");
      let ctx = canvas.getContext("2d");

      // 设置Canvas大小与图片相同
      canvas.width = width;
      canvas.height = height;

      // 绘制图片
      ctx.drawImage(img, 0, 0, width, height);

      // 绘制矩形框
      aiResults.forEach((item) => {
        ctx.beginPath();
        ctx.rect(item.x, item.y, item.width, 100); // 你可以调整这些值来改变矩形框的位置和大小
        ctx.strokeStyle = "red"; // 矩形框的颜色
        ctx.lineWidth = 1; // 矩形框的边框宽度
        ctx.stroke();

        if (item.label) {
          // 绘制文字背景
          ctx.fillStyle = "rgba(0, 0, 0, 0.6)"; // 背景颜色
          ctx.fillRect(item.x, item.y - 40, 250, 40); // 背景的位置和大小

          ctx.font = "20px Arial";
          ctx.fillStyle = "white"; // 文字颜色
          ctx.textAlign = "left";
          // 绘制文字
          ctx.fillText(
            `${item.label}${item.prob ? ": " + item.prob + "(相似度)" : ""}`,
            item.x,
            item.y - 20,
            250
          ); // 文字内容和位置
        }
      });

      return canvas;
    },
  },
};
</script>

<style scoped lang="scss">
.ai-list ::v-deep {
  z-index: 1;
  position: absolute;
  left: -124px;
  top: 0;
  width: 111px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;

  .ai-item {
    cursor: pointer;
    width: 35px;
    height: 44px;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #02173d;
    color: #00aacb;
    border: 1px solid #2b56b7;
  }
}
</style>