<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-show="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" crossorigin="anonymous" :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%" crossorigin="anonymous" :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: [],
      deAiIdentifyList: [
        {
          typeId: 1,
          type: "kbtAi",

          img: "https://mmc-crm.oss-cn-shenzhen.aliyuncs.com/prod/tmj-icon/ai/person_car.png",
          title: "人车识别",
        },
        {
          typeId: 2,
          type: "kbtAi",

          img: "https://mmc-crm.oss-cn-shenzhen.aliyuncs.com/prod/tmj-icon/ai/fire.png",
          title: "烟火识别",
        },
        {
          typeId: 4,
          type: "kbtAi",

          img: "https://mmc-crm.oss-cn-shenzhen.aliyuncs.com/prod/tmj-icon/ai/person.png",
          title: "行人识别",
        },
        {
          typeId: 5,
          type: "kbtAi",

          img: "https://mmc-crm.oss-cn-shenzhen.aliyuncs.com/prod/tmj-icon/ai/car.png",
          title: "机动车识别",
        },
        {
          typeId: 6,
          type: "kbtAi",
          img: "https://mmc-crm.oss-cn-shenzhen.aliyuncs.com/prod/tmj-icon/ai/motor_bicycle.png",
          title: "两轮车识别",
        },
        {
          typeId: 7,
          type: "kbtAi",

          img: "https://mmc-crm.oss-cn-shenzhen.aliyuncs.com/prod/tmj-icon/ai/tricycle.png",
          title: "三轮车识别",
        },
        {
          typeId: 8,
          type: "kbtAi",

          img: "https://mmc-crm.oss-cn-shenzhen.aliyuncs.com/prod/tmj-icon/ai/excavator.png",
          title: "挖掘机识别",
        },
        {
          typeId: 9,
          type: "kbtAi",

          img: "https://mmc-crm.oss-cn-shenzhen.aliyuncs.com/prod/tmj-icon/ai/plate.png",
          title: "车牌识别",
          type: "plate",
        },
        {
          typeId: 10,

          type: "face",
          img: "https://mmc-crm.oss-cn-shenzhen.aliyuncs.com/prod/tmj-icon/ai/face.png",
          title: "人脸识别",
        },
        {
          typeId: 11,
          type: "kbtAi",

          img: "https://mmc-crm.oss-cn-shenzhen.aliyuncs.com/prod/tmj-icon/ai/mask.png",
          title: "口罩识别",
        },
        {
          typeId: 14,
          type: "smoke",
          img: "https://mmc-crm.oss-cn-shenzhen.aliyuncs.com/prod/tmj-icon/ai/smoke.png",
          title: "烟雾识别",
        },
        {
          typeId: 15,
          type: "kbtAi",

          img: "https://mmc-crm.oss-cn-shenzhen.aliyuncs.com/prod/tmj-icon/ai/fire.png",
          title: "火焰识别",
        },
        {
          typeId: 17,
          type: "kbtAi",

          img: "https://mmc-crm.oss-cn-shenzhen.aliyuncs.com/prod/tmj-icon/ai/zhandao.png",
          title: "占道经营",
        },
        {
          type: "kbtAi",

          typeId: 22,
          img: "https://mmc-crm.oss-cn-shenzhen.aliyuncs.com/prod/tmj-icon/ai/boat.png",
          title: "船舶识别",
        },
        {
          typeId: 23,
          type: "oilLeak",
          img: "https://mmc-crm.oss-cn-shenzhen.aliyuncs.com/prod/tmj-icon/ai/oilspill.png",
          title: "漏油识别",
        },
        {
          typeId: 24,
          type: "kbtAi",

          img: "https://mmc-crm.oss-cn-shenzhen.aliyuncs.com/prod/tmj-icon/ai/helmet.png",
          title: "头盔识别",
        },
        {
          typeId: 25,
          type: "kbtAi",

          img: "https://mmc-crm.oss-cn-shenzhen.aliyuncs.com/prod/tmj-icon/ai/guanxian.png",
          title: "管线识别",
        },
        {
          typeId: 26,
          type: "kbtAi",

          img: "https://mmc-crm.oss-cn-shenzhen.aliyuncs.com/prod/tmj-icon/ai/lumianliefeng.png",
          title: "路面裂缝",
        },
        {
          typeId: 27,
          type: "kbtAi",

          img: "https://mmc-crm.oss-cn-shenzhen.aliyuncs.com/prod/tmj-icon/ai/dingpeng.png",
          title: "顶棚违建",
        },
        {
          typeId: 28,
          type: "kbtAi",

          img: "https://mmc-crm.oss-cn-shenzhen.aliyuncs.com/prod/tmj-icon/ai/guanggaopai.png",
          title: "门牌广告",
        },
        {
          typeId: 29,
          type: "kbtAi",

          img: "https://mmc-crm.oss-cn-shenzhen.aliyuncs.com/prod/tmj-icon/ai/jinggai.png",
          title: "井盖识别",
        },
        {
          typeId: 30,
          type: "kbtAi",

          img: "https://mmc-crm.oss-cn-shenzhen.aliyuncs.com/prod/tmj-icon/ai/jiaobanche.png",
          title: "搅拌车识别",
        },
        {
          typeId: 31,
          type: "kbtAi",

          img: "https://mmc-crm.oss-cn-shenzhen.aliyuncs.com/prod/tmj-icon/ai/youguanche.png",
          title: "油罐车识别",
        },
        {
          typeId: 32,
          type: "kbtAi",

          img: "https://mmc-crm.oss-cn-shenzhen.aliyuncs.com/prod/tmj-icon/ai/zhatuche.png",
          title: "渣土车识别",
        },
        {
          typeId: 33,
          type: "kbtAi",

          img: "https://mmc-crm.oss-cn-shenzhen.aliyuncs.com/prod/tmj-icon/ai/paiwukou.png",
          title: "排气口识别",

          type: "kbtAi",
        },
        {
          typeId: 34,
          img: require("./assets/images/人流识别.svg"),
          title: "人流识别",
          type: "kbtAi",
        },
        {
          title: "裸土识别",
          type: "bareSoil",
          typeId: 35,
          img: require("./assets/images/裸土识别.svg"),
        },
      ],
      // aiIdentifyList: [
      //   {
      //     title: "人脸识别",
      //     type: "face",
      //     typeId: 1,
      //     img: require("./assets/images/人脸识别.svg"),
      //   },
      //   {
      //     title: "车牌识别",
      //     type: "plate",
      //     typeId: 8,
      //     img: require("./assets/images/车牌识别.svg"),
      //   },
      //   {
      //     title: "人流识别",
      //     type: "crowd",
      //     typeId: 3,
      //     img: require("./assets/images/人流识别.svg"),
      //   },
      //   {
      //     title: "烟雾识别",
      //     type: "smoke",
      //     typeId: 7,
      //     img: require("./assets/images/烟雾识别.svg"),
      //   },
      //   {
      //     title: "漏油识别",
      //     type: "oilLeak",
      //     typeId: 5,
      //     img: require("./assets/images/漏油识别.svg"),
      //   },
      //   {
      //     title: "裸土识别",
      //     type: "bareSoil",
      //     typeId: 6,
      //     img: require("./assets/images/裸土识别.svg"),
      //   },
      // ],
      aiResultShow: false, //ai识别结果展示
      aiTitle: "",
      aiResultImg: "", //ai结果图
    };
  },
  computed: {
    ...mapState("MMCFlightControlCenter", ["cesiumViewer", "baseUrl"]),
    ...mapState("MMCFlightControlCenter/uav", ["uav", "userInfo"]),
  },
  mounted() {
    this.getAiconfig();
  },
  methods: {
    async getAiconfig() {
      let formData = new FormData();
      console.log(this.$store.state.MMCFlightControlCenter, "userInfo");
      let { TenantId, projectId } = this.$store.state.MMCFlightControlCenter;
      // formData.append("projectId", projectId);
      // formData.append("tenantId", TenantId);
      let res = await AI_API["getAiconfig"]({
        tenantId: TenantId,
        projectId: projectId,
      });
      if (res.data.configInfo) {
        const configInfo = Object.entries(res.data.configInfo).map(
          ([key, value]) => ({
            key,
            ...value,
          })
        );
        let configInfoData = configInfo.filter((item) => item.status == 0);
        // 使用 Set 存储数据1中的所有 title，提高查找效率
        const titleSet = new Set(
          configInfoData.map((item) => item.detectorType)
        );
        console.log(titleSet, "titleSet");
        // 遍历数据2，检查每个 name 是否在 titleSet 中存在
        const matchedData = this.deAiIdentifyList.filter((dataItem) =>
          titleSet.has(dataItem.typeId)
        );
        this.aiIdentifyList = matchedData;
      }
    },

    /**
     * ai识别事件
     */
    onAiIdentify(type) {
      this.aiIdentify(type, (img) => {
        if (img) {
          // 展示识别结果
          this.$message.success("识别成功");
          this.aiResultImg = img;
          this.aiResultShow = true;
        } else {
          this.$message.error("识别失败");
        }
      });
    },
    /**
     * ai处理, 父组件也调用
     */
    aiIdentify(type, callback) {
      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;
            case "kbtAi":
              {
                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);

            // 将识别结果绘制到图片上
            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);

              callback(canvas.toDataURL("image/svg"));

              // 识别结果上传到视图库
              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;
          } else {
            callback(false);
          }
        },
      });
    },
    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: 123px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  overflow-y: auto;
  max-height: 142px;
  gap: 4px;
  .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>