<template>
  <div class="mmc-filght-control-center mmc">
    <!-- cesium地图层 -->
    <CesiumLayout v-if="!cesiumViewer" :latitude="parseFloat(userInfo.latitude)" :longitude="parseFloat(userInfo.longitude)"></CesiumLayout>
    <!-- 地图切换组件 -->
    <MapImageSwitch></MapImageSwitch>
    <MapSearch class="map-search"></MapSearch>
    <!-- 无人机应用 -->
    <UavApplications v-if="scene == 1"></UavApplications>
    <!-- 机库 -->
    <Hangar v-else-if="scene == 2"></Hangar>
  </div>
</template>

<script>
import CesiumLayout from "./components/cesiumLayer";
import crashMonitor from "./components/cesiumLayer/crashMonitor";
import MapImageSwitch from "./components/mapImageSwitch";
import UavApplications from "./components/uavApplications";
import Hangar from "./components/hangar";
import Vue from "vue";
import SymbolIcon from "../symbol-icon";
import MapSearch from "./components/mapSearch";
import { Control_API } from "./api/index";

export default {
  name: "MMCFlightControlCenter",
  components: {
    CesiumLayout,
    MapImageSwitch,
    UavApplications,
    Hangar,
    MapSearch,
  },
  props: {
    url: {
      // api地址前缀
      type: Object,
      default: () => {
        return {
          baseUrl: "/",
          wsUrl: "wss://tmj.mmcuav.cn/websocket",
          mqttUrl: "wss://fkzx.mmcuav.cn:8884/mqtt",
        };
      },
    },
    // 天目将登录用户信息
    userInfo: {
      type: Object,
      default: null,
    },
    // 场景 1: 无人机 2: 机库
    scene: {
      type: Number,
      default: 0,
    },
    // 外部cesium.viewer对象
    cesiumViewer: {
      type: Object,
      default: null,
    },
    // 使用标准航线库
    useSTLAirway: {
      type: Boolean,
      default: true,
    },
    // 使用定时任务
    useTimedTask: {
      type: Boolean,
      default: false,
    },
    // useAirway
    // 使用任务
    useTask: {
      type: Boolean,
      default: false,
    },

    userInfo: {
      type: Object,
      default() {
        return {
          token: "",
          id: -1,
          avatar: "../../assets/avatar.png",
          nickname: "无",
          username: "无",
        };
      },
    },
  },
  data() {
    return {
      time: null,
      bus: new Vue(),
      ws: null,
      uavWs: null,
    };
  },
  provide() {
    return {
      rootNode: this, //根节点实例
      bus: this.bus, //bus总线
    };
  },
  watch: {
    userInfo: {
      immediate: true,
      handler(value) {
          console.log(value.latitude, value.longitude,'xxx');
        this.$store.commit("MMCFlightControlCenter/setState", {
          key: "token",
          value: this.userInfo.token,
        });
        this.$store.commit("MMCFlightControlCenter/setState", {
          key: "TenantId",
          value: this.userInfo.TenantId,
        });
        this.$store.commit("MMCFlightControlCenter/setState", {
          key: "projectId",
          value: this.userInfo.projectId,
        });
        this.$store.commit("MMCFlightControlCenter/setState", {
          key: "deptId",
          value: this.userInfo.deptId,
        });
        this.$store.commit("MMCFlightControlCenter/setState", {
          key: "userInfo",
          value: this.userInfo,
        });
      },
    },
    url: {
      immediate: true,
      handler(newVal) {
        this.$store.commit("MMCFlightControlCenter/setState", {
          key: "baseUrl",
          value: newVal.baseUrl,
        });
        this.$store.commit("MMCFlightControlCenter/setState", {
          key: "wsUrl",
          value: newVal.wsUrl,
        });
        this.$store.commit("MMCFlightControlCenter/setState", {
          key: "mqttUrl",
          value: newVal.mqttUrl,
        });
        this.$store.commit("MMCFlightControlCenter/setState", {
          key: "mqttUrlHangar",
          value: newVal.mqttUrlHangar,
        });
        this.$store.commit("MMCFlightControlCenter/setState", {
          key: "mqttUrlHangar",
          value: newVal.mqttUrlHangar,
        });
        this.$store.commit("MMCFlightControlCenter/setState", {
          key: "mqttToken",
          value: newVal.mqttToken,
        });
        this.$store.commit("MMCFlightControlCenter/setState", {
          key: "mqttIP",
          value: newVal.mqttIP,
        });
      },
    },
    useSTLAirway: {
      immediate: true,
      handler(newVal) {
        this.$store.commit("MMCFlightControlCenter/setState", {
          key: "useSTLAirway",
          value: newVal,
        });
      },
    },
    useTimedTask: {
      immediate: true,
      handler(newVal) {
        this.$store.commit("MMCFlightControlCenter/setState", {
          key: "useTimedTask",
          value: newVal,
        });
      },
    },
    useTask: {
      immediate: true,
      handler(newVal) {
        this.$store.commit("MMCFlightControlCenter/setState", {
          key: "useTask",
          value: newVal,
        });
      },
    },
  },
  beforeCreate() {
    clearInterval(this.time);
    crashMonitor({
      alert: this.$alert,
    });
    Vue.component("SymbolIcon", SymbolIcon);
    if (!window.$mmc_stl) {
      window.$mmc_stl = {};
    }
    window.$mmc_stl.app = this;
    window.$mmc_stl.$store = this.$store;
    window.$mmc_stl.state = () => {
      return this.$store.state;
    };
    window.$debug = localStorage.getItem("$debug") == 1 ? true : false; //全局调试信息展示开关
    window.$log = function (...args) {
      if (window.$debug) {
        console.info(...args);
      }
    };
  },
  created() {
    if (this.cesiumViewer) {
      this.$store.commit("MMCFlightControlCenter/setState", {
        key: "cesiumViewer",
        value: this.cesiumViewer,
      });
      window.$mmc_stl.viewer = this.cesiumViewer;
    }

    // 连接ws监听接管请求数据
    let url = this.url.wsUrl;
    let token = this.$store.state.MMCFlightControlCenter.token;
    const socket = new WebSocket(`${url}/infra/ws?token=${token}`);
    const uavSocket = new WebSocket(`${url}/uas/ws?token=${token}`);
    this.ws = socket;
    this.uavWs = uavSocket;
    socket.onopen = function () {};
    socket.onmessage = (event) => {
      let data = JSON.parse(event.data || "{}");
      const type = data.type;
      const content = JSON.parse(data.content || "{}");
      const msg = content.message;
      switch (type) {
        // 接管申请
        case "uas-device-take-message":
          //接管消息
          this.$confirm(msg, "提示", {
            confirmButtonText: "同意",
            cancelButtonText: "拒绝",
            type: "warning",
            closeOnClickModal: false,
            closeOnPressEscape: false,
            showClose: false,
          })
            .then(async () => {
              try {
                let res = await Control_API.updateControlUav({
                  deviceId: content.deviceId,
                  applicantId: content.applicantId,
                  isAgree: 1,
                });
                if (res.code == 0) {
                  this.$message.success("已同意接管");
                } else {
                  this.$message.warning("操作失败");
                }
              } catch (e) {}
            })
            .catch(async () => {
              await Control_API.updateControlUav({
                deviceId: content.deviceId,
                applicantId: content.applicantId,
                isAgree: 2,
              });
              this.$message.success("已拒绝接管");
            });
          // 5秒后自动关闭弹框
          setTimeout(() => {
            this.$confirm.close(); // 关闭弹框
          }, 5000);
          break;

        // 接管申请同意
        case "uas-device-take-agree-message":
          console.log("同意接管");
          break;

        // 接管申请拒绝
        case "uas-device-take-refuse-message":
          this.bus.$emit("uas-device-take-refuse-message", {
            type,
            content,
            msg,
          });
          break;

        // 退出接管消息
        case "uas-device-take-quit-message":
          this.$notify.info({
            title: "接管消息",
            message: msg,
            duration: 30000,
            offset: 40,
          });
          break;

        // 被强制接管
        case "uas-device-force-take-message":
          this.$notify.warning({
            title: "接管消息",
            message: msg,
            duration: 30000,
            offset: 40,
          });
          break;
      }
    };

    uavSocket.onopen = () => {
      let user = JSON.parse(localStorage.getItem("tmj"));
      let { projectId } = this.$store.state.MMCFlightControlCenter;
      if (user) {
        clearInterval(this.time);
        this.time = setInterval(() => {
          const scene = this.getQueryParam("scene");
          uavSocket.send(
            JSON.stringify({
              type: "uas-device-getTree-message",
              content: JSON.stringify({
                text: JSON.stringify({
                  deviceType: scene,
                  projectId: projectId,
                  serchKey: this.getCurrentSearchKey(),
                }),
                toUserId: user.user.userId,
              }),
            })
          );
        }, 6000);
      }
    };
    let { projectId } = this.$store.state.MMCFlightControlCenter;

    uavSocket.onmessage = (event) => {
      let data = JSON.parse(event.data || "{}");
      const type = data.type;
      const content = JSON.parse(data.content || "{}");
      const msg = content.message;
      switch (type) {
        case "uas-device-take-message":
          break;
        // 刷新无人机列表
        case "uas-device-getTree-message":
          let res = JSON.parse(data.content);
          if (projectId == res.projectId) {
            const scene = this.getQueryParam("scene");
            // 根据scene值决定更新哪个组件的数据
            if (scene == 1) {
              // scene为1时，更新uavList组件的数据
              this.bus.$emit("update-uav-list", res.text);
            } else if (scene == 2) {
              // scene为2时，更新hangar list组件的数据
              this.bus.$emit("update-hangar-list", res.text);
            }

            break;
          }
      }
    };
  },
  beforeDestroy() {
    this.ws.close();
    this.uavWs.close();
  },
  methods: {
    // 获取当前搜索关键字
    getCurrentSearchKey() {
      const scene = this.getQueryParam("scene");
      if (scene == 1) {
        // 无人机场景，获取 uavList 组件的搜索内容
        const uavListComponent = this.$children.find(
          (child) => child.$options.name === "UavApplications"
        );
        if (uavListComponent) {
          const uavList = uavListComponent.$children.find(
            (child) =>
              child.$options.name === "UavList" ||
              child.uavSearchContent !== undefined
          );
          return uavList ? uavList.uavSearchContent || "" : "";
        }
      } else if (scene == 2) {
        // 机库场景，获取 hangar 组件的搜索内容
        const hangarComponent = this.$children.find(
          (child) => child.$options.name === "Hangar"
        );
        if (hangarComponent) {
          const hangarList = hangarComponent.$children.find(
            (child) =>
              child.$options.name === "List" ||
              child.searchContent !== undefined
          );
          return hangarList ? hangarList.searchContent || "" : "";
        }
      }

      return "";
    },
    // 处理搜索变化事件

    getQueryParam(paramName) {
      // 获取当前页面的完整 URL
      const url = window.location.href;

      // 检查 URL 中是否包含 hash 部分
      const hashIndex = url.indexOf("#");
      if (hashIndex !== -1) {
        // 如果有 hash 部分，提取 hash 部分
        const hash = url.substring(hashIndex + 1); // 去掉 '#' 符号
        const hashParams = new URLSearchParams(hash.split("?")[1]); // 提取 hash 中的查询参数部分
        const value = hashParams.get(paramName);
        if (value !== null) {
          return value; // 如果在 hash 中找到参数，直接返回
        }
      }

      // 如果在 hash 中没有找到，检查普通的查询参数
      const searchParams = new URLSearchParams(window.location.search);
      return searchParams.get(paramName); // 返回普通查询参数中的值
    },
    reset() {
      let cesiumEl = document.querySelector(".cesium-viewer");

      // 判断cesium的父元素是否是layer-container来确定当前是否已经切换, 未切换就退出
      if (cesiumEl.parentElement.id === "layer-container") {
        return;
      }
      let cesiumParentEl = document.querySelector("#layer-container");
      let uavParentEl = document.querySelector("#playerUavParent");
      let uavEl = document.querySelector("#playerUav");
      let innerParentEl = document.querySelector("#playInnerParent");
      let innerEl = document.querySelector("#playInner");
      let outParentEl = document.querySelector("#playOutParent");
      let outEl = document.querySelector("#playerOuter");

      cesiumParentEl.innerHTML = "";
      uavParentEl.innerHTML = "";
      innerParentEl.innerHTML = "";
      outParentEl.innerHTML = "";

      cesiumParentEl.append(cesiumEl);
      uavParentEl.append(uavEl);
      innerParentEl.append(innerEl);
      outParentEl.append(outEl);
    },
  },
};
</script>

<style lang="scss" scoped>
.mmc-filght-control-center {
  overflow: hidden;
  position: relative;
  height: 100%;
  width: 100%;
}

.map-search {
  position: absolute;
  top: 10px;
  right: 20px;
}
</style>

<style lang="scss">
.mmc-filght-control-center {
  overflow: hidden;
  position: relative;
  height: 100%;
  width: 100%;

  .el-input__inner {
    background-color: #191919 !important;
    color: #fff;
    border: 1px solid #4b4b4b !important;
  }

  .el-range-input {
    background-color: transparent;
    color: #fff !important;
  }

  .el-range-separator {
    color: #fff !important;
  }

  .el-dialog {
    background: #222222;
    border: none;
    border-radius: 1px;

    .el-dialog__header {
      background: #3c3c3c;

      .el-dialog__title {
        color: #fff;
      }
    }

    .el-dialog__body {
      color: #fff;
    }
  }

  * {
    /* 滚动条整体样式 */
    &::-webkit-scrollbar {
      width: 4px;
      /* 滚动条宽度 */
    }

    //滚动条轨道
    &::-webkit-scrollbar-track {
      background: none;
    }

    //滚动条滑块
    &::-webkit-scrollbar-thumb {
      background: #fff;
    }
  }

  div[class*="cpt-MMC_Gimbal"] {
    background: #222222;
    border-radius: 10px 10px 0px 0px;
    border: 0;

    .hd {
      box-sizing: border-box;
      padding-left: 0px;
      padding-right: 16px;
      background-position: 12px 4px;
      height: 32px;
      width: 100%;
      background: #3c3c3c;
      border-radius: 10px 10px 0px 0px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      position: relative;
      box-shadow: none;
    }
  }

  .dialog1027 {
    z-index: 1;
    background: #222222;
    border-radius: 10px 10px 10px 10px;

    .dialog-header {
      box-sizing: border-box;
      padding-left: 32px;
      padding-right: 16px;
      background-position: 12px 4px;
      height: 32px;
      width: 100%;
      background: #3c3c3c;
      border-radius: 10px 10px 0px 0px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      position: relative;

      .dialog-header__icon {
        position: absolute;
        left: 12px;
        top: 50%;
        transform: translate(0, -50%);
        background-image: url("./assets/images/jinye.png");
        background-size: 100% 100%;
        width: 19px;
        height: 25px;
      }

      .dialog-header__title {
        display: flex;
        align-items: center;
        font-size: 20px;
        font-family: YouSheBiaoTiHei;
        background-image: -webkit-linear-gradient(
          right,
          #e3aa77,
          #f5cda9,
          #f9ecd3,
          #fcdbb1,
          #edb07a
        );
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        letter-spacing: 0;
        font-weight: 700;
      }

      .dialog-header__close {
        font-size: 14px;
        font-family: MicrosoftYaHei;
        color: #acacac;
        line-height: 19px;
        cursor: pointer;
      }
    }

    .dialog-content {
      background: #222222;
      box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.1);
      border-bottom-left-radius: 10px;
      border-bottom-right-radius: 10px;
      padding: 12px 12px 16px;
      width: 100%;
      font-size: 14px;
      font-family: SourceHanSansCN-Regular, SourceHanSansCN;
      font-weight: 400;
      color: #ffffff;
      box-sizing: border-box;
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;

      .dialog-content-item {
        margin-bottom: 16px;
        display: flex;

        .dialog-content__label {
          padding-top: 7px;
          font-size: 14px;
          font-family: SourceHanSansCN-Regular, SourceHanSansCN;
          font-weight: 400;
          color: #ffffff;
          width: 110px;
          text-align: right;
        }

        .dialog-content__text {
          padding: 6px 12px;
          width: 228px;
          background: rgba(2, 23, 61, 1);
          border-radius: 2px;
          border: 1px solid #315ec7;
          font-size: 14px;
          font-family: MicrosoftYaHei;
          color: #00dfff;
          line-height: 19px;
        }
      }

      .el-input__inner {
        border-radius: 2px;
        font-size: 14px;
        font-family: MicrosoftYaHei;
        color: #ffffff;
      }

      .el-input-group__append {
        font-size: 20px;
      }

      .el-autocomplete {
        width: 100%;
      }

      .el-radio {
        color: #fff;
      }

      .el-scrollbar {
        background: #02173d;
        border: 1px solid #315ec7;
      }

      .el-textarea {
        border: none;
      }

      .el-textarea__inner {
        background: #02173d;
        border: 1px solid #315ec7;
      }

      .btn-box1027 {
        padding: 16px 16px;
        width: 100%;
      }
    }
  }

  .el-input-number {
    .el-input-number__decrease,
    .el-input-number__increase {
      bottom: 1px;
      background: #606266;
      color: #f5f7fa;
      border-radius: 0;
      border: none;
    }

    .el-input-number__decrease {
      left: 1px;
    }

    .el-input-number__increase {
      right: -1px;
    }
  }

  .el-form-item__label {
    color: #fff;
  }
}

.mmc {
  .popper__arrow::after {
    border-bottom-color: #161d2d;
  }

  // 所有下拉选择框样式
  &.el-select-dropdown {
    border: none;

    //item选项的hover样式
    .el-select-dropdown__item.hover,
    .el-select-dropdown__item:hover {
      background: #4b4b4b;
    }

    .option.hover,
    .option:hover {
      background-image: linear-gradient(
        90deg,
        rgba(44, 135, 176, 0.7) 0%,
        rgba(26, 100, 139, 0.37) 51%,
        rgba(7, 61, 98, 0.7) 100%
      );
      font-family: MicrosoftYaHei;
      font-size: 12px;
      color: #00f5ff;
      letter-spacing: 0;
      font-weight: 400;
    }

    .el-select-dropdown__item {
      color: #fff;

      .selected {
        background-color: #606266;
      }
    }

    .option {
      font-family: MicrosoftYaHei;
      font-size: 12px;
      color: rgba(146, 217, 255, 0.7);
      letter-spacing: 0;
      font-weight: 400;
    }

    .el-scrollbar {
      overflow: hidden;
      position: relative;
      background: #191919;

      border: 1px solid #4b4b4b;
    }

    &.is-multiple {
      .el-select-dropdown__item.selected {
        background-color: #34466e;
      }
    }

    .el-select-dropdown__empty {
      background: #02173d;
      border: 1px solid #4b4b4b;
    }
  }

  &.el-cascader__dropdown {
    border: 1px solid #4b4b4b;

    .el-cascader-menu__list {
      background-color: #191919;

      max-height: 300px;
      max-width: 327px;
    }

    .el-cascader-node {
      background-color: #191919;
      color: #fff;

      &:not(.is-disabled):hover {
        background: #4b4b4b;
      }

      &:not(.is-disabled):focus {
        background: #4b4b4b;
      }
    }
  }

  &.el-dialog {
    background: transparent;

    .el-dialog__header {
      padding: 0;
    }

    .el-dialog__body {
      padding: 0;
    }
  }

  .el-popper {
    background: #222222;
  }

  // 日期选择器组件
  &.el-time-range-picker,
  &.el-date-range-picker,
  &.el-date-picker {
    border: none;

    .el-picker-panel__body-wrapper,
    .el-time-range-picker__content {
      background: #191919;
      color: #fff;

      .el-month-table td.current:not(.disabled) .cell {
        color: #00aeff;
      }

      .el-input__inner {
        color: #fff;
      }

      .el-date-table td.disabled div {
        background-color: transparent;
      }

      .el-date-table th {
        // border-bottom: solid 1px #00aeff;
        color: #fff;
      }

      .el-date-table td.in-range div {
        background-color: #00aeff;
      }

      .el-date-picker__header-label {
        color: #fff;
      }

      .el-input--small .el-input__inner {
        background-color: #191919;
      }

      .el-picker-panel__icon-btn {
        color: #fff;
      }
    }

    .el-picker-panel__footer,
    .el-time-panel__footer {
      background-color: #191919;
    }

    .popper__arrow {
      border-bottom-color: #fff;
      border-top-color: #fff;
    }

    .popper__arrow::after {
      border-top-color: #191919;
      border-bottom-color: #191919;
    }

    .el-button.el-button--mini.is-plain,
    .el-button.is-disabled.is-plain {
      background-color: transparent;
      border: none;
      color: #00aeff;
    }

    .el-time-spinner__item {
      color: #fff;
    }

    .el-time-panel__btn {
      color: #fff;

      &.confirm {
        color: #409eff;
      }
    }

    .el-time-spinner__item:hover:not(.disabled):not(.active) {
      background-color: #4472d5;
    }
  }

  .el-pagination {
    text-align: center;

    .el-pager li {
      background: transparent !important;
    }

    button {
      background: transparent !important;
    }
  }

  .cesium-viewer-bottom {
    display: none;
  }

  .cesium-viewer-zoomIndicatorContainer {
    display: none;
  }

  .cesium-viewer-navigationContainer {
    display: none;
  }

  .cesium-credit-logoContainer {
    display: none;
  }
}
</style>
