<template>
  <div class="left-sidebar" :class="{ contracted: isContracted }">
    <div class="stats">
      <div class="stat-item" v-for="(item, index) in warningDay" :key="index">
        <div class="stat-name">{{ item.name }}</div>
        <div class="stat-name">{{ item.value }} 次</div>
      </div>
    </div>
    <div class="drone-list">
      <div class="title">
        <img src="@/assets/img/uavTitle.png" alt="" />
      </div>
      <ul>
        <li
          v-for="(drone, index) in drones"
          :key="index"
          @click="handleDroneClick(drone)"
        >
          <div class="top">
            <div class="left">
              {{ index < 9 ? "0" + (index + 1) : index + 1 }}
            </div>
            <div class="text">{{ drone.serial_number }}</div>
          </div>
          <div class="main">
            <div class="top_main">
              <div class="text">时间：{{ drone.times }}</div>
              <div class="text">来源：{{ drone.DeviceName }}</div>
            </div>
            <div class="top_main">
              <div class="text">频段：{{ drone.freq }}</div>
              <div class="text">型号：{{ drone.device_type }}</div>
            </div>
          </div>
        </li>
      </ul>
    </div>
    <div class="left-contract" @click="handleContractClick">
      <img :src="isContracted ? rightContract : leftContract" alt="" />
    </div>
    <audio
      controls
      loop
      ref="uavAudio"
      v-show="iswarning"
      style="display: none"
    >
      <source src="@/assets/img/wargin.mp3" type="audio/mpeg" />
    </audio>
    <div class="audio-prompt" v-if="showAudioPrompt" @click="enableAudio">
      <div class="prompt-content">
        <p>因浏览器限制，点击打开声音</p>
      </div>
    </div>
  </div>
</template>

<script>
import moment from "moment";
import { mapUavFiex } from "../index.js";
export default {
  name: "LeftSidebar",
  props: {
    homeData: {
      type: Object,
      default: () => ({})
    },
    signaData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      leftContract: require("@/assets/img/left-contract.png"),
      rightContract: require("@/assets/img/right-contract.png"),
      warningDay: [
        {
          id: "1",
          name: "今日预警",
          value: 20
        },
        {
          id: "2",
          name: "累计预警",
          value: 20
        },
        {
          id: "3",
          name: "今日反制",
          value: 0
        },
        {
          id: "4",
          name: "累计反制",
          value: 0
        }
      ],
      drones: [],
      isContracted: false,
      homeView: {},
      droneTimers: new Map(),
      iswarning: false,
      showAudioPrompt: false
    };
  },
  mounted() {},
  watch: {
    homeData: {
      handler(newVal) {
        this.homeView = newVal;
        this.warningDay[0].value = newVal.alarmCount.todaywaring;
        this.warningDay[1].value = newVal.alarmCount.totalcount;
        this.warningDay[2].value = newVal.alarmCount.todayhandle;
        this.warningDay[3].value = newVal.alarmCount.totalhandle;
      },
      deep: true
    },
    signaData: {
      handler(newVal) {
        if (newVal) {
          newVal.forEach((newItem) => {
            // 如果已经存在相同BatchId的数据，重置计时器
            if (newItem.BatchId) {
              const existingTimer = this.droneTimers.get(newItem.BatchId);
              if (existingTimer) {
                clearInterval(existingTimer); // 清除旧计时器
              }

              // 设置15秒初始时间
              newItem.currTime = 15;
              // 创建新计时器
              const timer = this.startTimer(newItem);
              this.droneTimers.set(newItem.BatchId, timer);

              // 更新无人机列表
              const existingIndex = this.drones.findIndex(
                (d) => d.BatchId === newItem.BatchId
              );
              newItem.times = moment(newItem.CreateTime).format("HH:mm:ss");
              if (existingIndex !== -1) {
                this.$set(this.drones, existingIndex, { ...newItem });
              } else {
                this.drones.push({ ...newItem });
              }
            }
          });
          if (newVal.length === 0) {
            this.iswarning = false;
          }

          if (this.drones) {
            mapUavFiex(this.drones);
          }
          let alarm = this.drones.find((d) => d.alarmLevel === 1);
          const media = this.$refs.uavAudio; // 修正 ref 名称为 "uavAudio"
          if (alarm) {
            this.iswarning = true;
            this.$nextTick(() => {
              if (media) {
                media.muted = true; // 初始静音
                media
                  .play()
                  .then(() => {
                    console.log("播放成功，取消静音");
                    media.muted = false; // 播放成功后取消静音
                  })
                  .catch((error) => {
                    console.log("播放失败:", error);
                    this.showAudioPrompt = true; // 播放失败时显示提示框
                  });
              }
            });
          } else {
            console.log("无告警");
            this.iswarning = false;
            if (media) {
              media.pause(); // 无告警时停止播放
              media.currentTime = 0; // 重置到开始
            }
          }
        }
      },
      deep: true
    }
  },
  methods: {
    enableAudio() {
      this.iswarning = true;
      const media = this.$refs.uavAudio;
      let time = setInterval(() => {
        console.log("用户手动启用音频", media);
        if (media !== undefined) {
          clearInterval(time);
          media.muted = false; // 取消静音
          media
            .play()
            .then(() => {
              console.log("用户手动启用音频成功");
              this.showAudioPrompt = false; // 关闭提示框
            })
            .catch((error) => {
              console.error("手动播放失败:", error);
            });
        }
      }, 500);
    },
    startTimer(item) {
      return setInterval(() => {
        if (item.currTime > 0) {
          item.currTime--;
          // 更新显示时间（可选）
          const index = this.drones.findIndex(
            (d) => d.BatchId === item.BatchId
          );
          if (index !== -1) {
            this.$set(this.drones, index, { ...item });
          }
        } else {
          clearInterval(this.droneTimers.get(item.BatchId));
          this.droneTimers.delete(item.BatchId);
          this.handleTimerExpiration(item);
          this.showAudioPrompt = false; // 关闭提示框
          this.iswarning = false;
          const media = this.$refs.uavAudio;
          media.muted = true; // 静音
        }
      }, 1000);
    },

    handleTimerExpiration(item) {
      // 从drones数组中移除

      // 如果drones也需要同步更新
      if (this.drones.length === 1) {
        this.drones = [];
      } else {
        this.drones = this.drones.filter((d) => d.BatchId !== item.BatchId);
      }

      // 清理地图上的图形
      let graphicLayer = window.marsMap.getLayerById("uavFiex");
      if (graphicLayer) {
        let graphic = graphicLayer.getGraphicById(item.BatchId);
        let startPoint = graphicLayer.getGraphicById(item.BatchId + "start");

        if (graphic) {
          graphic.destroy();
          graphicLayer.removeGraphic(graphic);
        }
        if (startPoint) {
          graphicLayer.removeGraphic(startPoint);
        }
        if (this.drones.length === 0) {
          window.marsMap.removeLayer(graphicLayer);
        }
      }
    },
    handleContractClick() {
      this.isContracted = !this.isContracted; // 切换状态
    },
    handleDroneClick(value) {
      console.log(value, "value");
      window.marsMap.setCameraView({
        lat: value.drone_lat,
        lng: value.drone_lon,
        alt: value.height + 800,
        pitch: -90
      });
      if (value.drone_lon == 0 || value.drone_lat == 0) {
        console.log("经纬度为0");
      } else {
        let graphicLayer = window.marsMap.getLayerById("uavFiex");
        // let startPoint = graphicLayer.getGraphicById(value.BatchId + "start");
        if (graphicLayer) {
          graphicLayer.eachGraphic((car) => {
            // 取出对应无人机的轨迹列表
            //打击之前
            if (value.BatchId === car.id) {
              // car.openPopup();
              console.log(car, "car.polyline");
              car.polyline.show = !car.polyline.show; // 轨迹线
              // if (car.polyline.show) {
              //   car.setOptions({
              //     polyline: {
              //       width: 2,
              //       opacity: 1,
              //     }
              //   });
              // } else {
              //   car.setOptions({
              //     polyline: {
              //       width: 2,
              //       opacity: 0,
              //     }
              //   });
              // }
            }
          });
        }
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.left-sidebar {
  transition: transform 0.5s;
}

.left-sidebar.contracted {
  transform: translateX(-90%);
}
.audio-prompt {
  position: fixed;
  top: 0;
  left: 50%;
  width: 15%;
  height: 10%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  color: #fff;
  border-radius: 5px;
  transform: translateX(-50%);
}
</style>
