<template>
  <div class="control-top">
    <div class="ct-item ct-date">
      <div>{{date}}</div>
      <div>{{week}} {{time}}</div>
    </div>
    <div class="ct-item ct-weather">
      <img class="ctw-icon" :src="weatherIcon" />
      <div class="ctw-wind">
        <div class="ctww-line1">
          <!-- <img :src="weatherIcon" /> -->
          <div>{{weather.windDirection}}</div>
        </div>
        <div>{{weather.windSpeed}}m/s</div>
      </div>
    </div>
    <div class="ct-item ct-take-off">{{weather.flyStatus ? '适宜起飞' : '不宜起飞'}}</div>
    <div class="ct-item ct-info">
      <!-- 避障雷达 -->
      <el-tooltip
        class="item"
        :class="{invalid: !uavRealTimeData.obstacle || !uavRealTimeData.obstacle.enable }"
        effect="dark"
        :content="uavRealTimeData.obstacle && uavRealTimeData.obstacle.enable ? '避障中' : '避障未开启'"
        placement="bottom"
      >
        <img src="./assets/images/radar.svg" />
      </el-tooltip>
      <!-- 网络信号 -->
      <el-tooltip class="item" effect="dark" content="网络信号" placement="bottom">
        <img :src="networkImg" />
      </el-tooltip>
      <!-- 传输方式 -->
      <el-dropdown @command="onNetworkChange">
        <span class="el-dropdown-link">
          {{network}}
          <i class="el-icon-arrow-down el-icon--right"></i>
        </span>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item :command="2">专网</el-dropdown-item>
          <el-dropdown-item :command="3">公网</el-dropdown-item>
          <el-dropdown-item :command="0">自动</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    <div class="ct-item ct-info">
      <!-- 降落伞 -->
      <el-tooltip class="item" effect="dark" :content="parachuteState.content" placement="bottom">
        <img :src="parachuteState.img" />
      </el-tooltip>
      <!-- gps信号 -->
      <el-tooltip class="item" effect="dark" content="gps信号" placement="bottom">
        <img :src="gpsImg" />
      </el-tooltip>
      <!-- 搜星数 -->
      <el-tooltip class="item " effect="dark" content="搜星数" placement="bottom">
        <div>
          <img src="./assets/images/satellite.png" />
          <div class="s-count">{{ satelliteCount }}</div>
        </div>
      </el-tooltip>
    </div>
    <div class="ct-item last ct-info">
      <!-- 接管记录 -->
      <el-tooltip class="item" effect="dark" content="接管记录" placement="bottom">
        <img
          src="./assets/images/record.svg"
          @click="showTakeOverRecords = !showTakeOverRecords"
          v-hover
        />
      </el-tooltip>
      <!-- 遥控器连接状态 -->
      <el-tooltip
        class="item"
        effect="dark"
        :content="`遥控器${uavRealTimeData.isRcConnecting == 1 ? '已连接' : '未连接'}`"
        placement="bottom"
      >
        <img :src="controlImg" />
      </el-tooltip>
      <!-- 内外场权限 -->
      <el-tooltip
        class="item"
        effect="dark"
        :content="uavRealTimeData.rcState == 1 ? '内场权限' : '外场权限' "
        placement="bottom"
      >
        <img :src="outInImg" />
      </el-tooltip>
      <!-- 模式选择 -->
      <el-dropdown trigger="click" @command="onModeChange">
        <el-button style="background: none; color: #fff;" plain type size="small">
          {{ flightMode }}
          <i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>

        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item
            v-for="item in modeList"
            v-show="!item.disabled"
            :key="item.id"
            :command="item.data"
          >{{ item.label }}</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    <TakeOverRecords v-if="showTakeOverRecords" @close="showTakeOverRecords = false"></TakeOverRecords>
  </div>
</template>

<script>
import dayjs from "dayjs";
import { mapState, mapActions } from "vuex";
import TakeOverRecords from "./components/takeOverRecords";
import { System } from "../../../../../../api";


export default {
  name: "ControlTop",
  components: {
    TakeOverRecords,
  },
  props: {
    isHangar: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      date: "",
      week: "",
      time: "",
      timeHandler: null,
      modeList: [
        // 模型列表
        { id: 0, data: "UNKNOWN", label: "离线状态", disabled: true },
        { id: 1, data: "MANUAL", label: "手动模式", disabled: true },
        { id: 2, data: "ALTITUDE", label: "定高模式", disabled: false },
        { id: 3, data: "POSITION", label: "定点模式", disabled: false },
        { id: 4, data: "AUTO_MISSION", label: "航线模式", disabled: false },
        { id: 5, data: "ACRO", label: "特技模式", disabled: true },
        { id: 6, data: "OFF_BOARD", label: "版外模式", disabled: true },
        { id: 7, data: "STABILIZED", label: "自稳模式", disabled: true },
        { id: 8, data: "HOLD", label: "保持模式", disabled: false },
        { id: 9, data: "LAND", label: "降落模式", disabled: true },
        { id: 10, data: "TAKE_OFF", label: "起飞模式", disabled: true },
        { id: 11, data: "AUTO_RTL", label: "返航模式", disabled: false },
        {
          id: 12,
          data: "AUTO_FOLLOW_TARGET",
          label: "跟随模式",
          disabled: false,
        },
      ],
      // 摇杆状态
      rcChannelStateList: {
        0: "摇杆中位",
        "-98": "摇杆外场权限",
        "-99": "摇杆未连接",
        1: "俯仰偏前",
        "-1": "俯仰偏后",
        "-2": "横滚偏左",
        2: "横滚偏右",
        3: "油门偏高",
        "-3": "油门偏低",
        4: "航向偏右",
        "-4": "航向偏左",
      },
      showTakeOverRecords: false, // 显示接管记录
      timeWeather: null,
      weather: {
        windSpeed: 0,
        minTemp: 0,
        maxTemp: 0,
        windDirection: "未知",
        humidity: 0,
        temp: 0,
        windLevel: 0,
        conditionDay: "未知",
      },
      weatherIcon: require(`./assets/images/weather/icon/iconfont/W0.png`)
    };
  },
  computed: {
    ...mapState("MMCFlightControlCenter/uav", ["uavRealTimeData"]),
    ...mapState("MMCFlightControlCenter/hangar", ["hangar"]),
    // 网络判断 公网|专网
    network() {
      let { uavRealTimeData } = this;
      let name = null;
      if (uavRealTimeData && uavRealTimeData.link) {
        for (let i = 0; i < uavRealTimeData.link.length; i++) {
          const k = uavRealTimeData.link[i];
          if (k.priority == 2 && k.using) {
            return "专网";
          } else if (k.priority == 3 && k.using) {
            return "公网";
          } else if (k.priority == 1 && k.using) {
            return "图传";
          }
        }
      }
      return name || "离线";
    },
    /**
     * 网络信号
     */
    networkSignal() {
      let { uavRealTimeData } = this;
      if (this.network === "公网") {
        if (
          uavRealTimeData &&
          uavRealTimeData.signal &&
          uavRealTimeData.signal.sqe45
        ) {
          if (uavRealTimeData.signal.sqe45 === -1) {
            return 0;
          }
          return uavRealTimeData.signal.sqe45;
        }
        return 0;
      } else if (this.network === "专网") {
        if (
          uavRealTimeData &&
          uavRealTimeData.signal &&
          uavRealTimeData.signal.sqe14
        ) {
          if (uavRealTimeData.signal.sqe14 === -1) {
            return 0;
          }
          return uavRealTimeData.signal.sqe14;
        }
        return 0;
      }
    },
    networkImg() {
      let { uavRealTimeData } = this;
      if (this.network === "公网") {
        return require(`./assets/images/5g-${this.networkSignal}.png`);
      } else if (this.network === "专网") {
        return require(`./assets/images/1.4g-${this.networkSignal}.png`);
      } else {
        return require(`./assets/images/5g-0.png`);
      }
    },
    /**
     * gps信号号
     */
    gpsSignalCount() {
      let { uavRealTimeData } = this;
      if (uavRealTimeData && uavRealTimeData.gps.satelliteCount) {
        let count = parseInt(uavRealTimeData.gps.satelliteCount / 6);
        if (count >= 5) {
          count = 5;
        } else {
          count += 1;
        }
        return uavRealTimeData.gps.satelliteCount ? count : 0;
      }
      return 0;
    },
    gpsImg() {
      return require(`./assets/images/GPS-${this.gpsSignalCount}.png`);
    },
    /**
     * 降落伞状态
     */
    parachuteState() {
      let { uavRealTimeData } = this;
      let parachuteState = uavRealTimeData?.parachuteState || 0;
      let parachute = uavRealTimeData?.parachute || 1;
      let content1 = [
        "正常",
        "降落伞未启用",
        "降落伞控制器不在线",
        "降落伞伞包未连接",
        "降落伞故障",
      ];
      let content2 = ["", "降落伞进入警戒", "降落伞退出警戒", "降落伞开伞"];
      if (parachute == 0) {
        return {
          img: require(`./assets/images/parachute-${parachuteState}.png`),
          content: content2[parachuteState],
        };
      } else {
        return {
          img: require(`./assets/images/parachute-0.png`),
          content: content1[parachute],
        };
      }
    },
    /**
     * 搜星数
     */
    satelliteCount() {
      let { uavRealTimeData } = this;
      if (uavRealTimeData) {
        if (
          uavRealTimeData.rtk &&
          uavRealTimeData.rtk.type == 19 &&
          uavRealTimeData.rtk.isMainSensor
        ) {
          return uavRealTimeData?.rtk?.satelliteCount;
        } else {
          return uavRealTimeData?.gps?.satelliteCount || 0;
        }
      }
      return 0;
    },
    /**
     * 飞行模式
     */
    flightMode() {
      let { uavRealTimeData, modeList } = this;
      let flightMode = modeList.find(
        (e) => e.data == uavRealTimeData?.flightMode
      );
      return flightMode?.label || "离线状态";
    },
    controlImg() {
      return this.uavRealTimeData.isRcConnecting == 1
        ? require("./assets/images/control-on.png")
        : require("./assets/images/control-off.png");
    },
    outInImg() {
      return this.uavRealTimeData.rcState == 1
        ? require("./assets/images/in.png")
        : require("./assets/images/out.png");
    },
  },
  created() {
    this.updateTime();
    this.timeHandler = setInterval(this.updateTime, 1000);
    this.getWeather();
    this.timeWeather = setInterval(this.getWeather, 60000);
  },
  beforeDestroy() {
    clearInterval(this.timeHandler);
    clearInterval(this.timeWeather);
  },
  methods: {
    ...mapActions("MMCFlightControlCenter/hangar", ["isTakeOver"]),
    updateTime() {
      this.date = dayjs().format("YYYY/MM/DD");
      this.time = dayjs().format("HH:mm:ss");
      let week = dayjs().day();
      let map = ["日", "一", "二", "三", "四", "五", "六"];
      this.week = "周" + map[week];
    },
    /**
     * 网络切换
     */
    onNetworkChange(id) {
      let { uavRealTimeData } = this;
      if (id == 0) {
        this.$store.dispatch("MMCFlightControlCenter/uav/networkChange", id);
        return this.$message.success("改为自动切换模式");
      } else if (id == 2) {
        // 专网
        if (uavRealTimeData?.link.length > 0) {
          let item = uavRealTimeData?.link.filter((item) => item.priority == 2);
          if (item.length > 0) {
            this.$store.dispatch(
              "MMCFlightControlCenter/uav/networkChange",
              id
            );
          } else {
            return this.$message.warning("暂无专网环境");
          }
        } else {
          return this.$message.warning("暂未链接无人机");
        }
      } else if (id == 3) {
        // 公网
        if (uavRealTimeData?.link.length > 0) {
          let item = uavRealTimeData?.link.filter((item) => item.priority == 3);
          if (item.length > 0) {
            this.$store.dispatch(
              "MMCFlightControlCenter/uav/networkChange",
              id
            );
          } else {
            return this.$message.warning("暂无公网环境");
          }
        } else {
          return this.$message.warning("暂未链接无人机");
        }
      }
    },
    /**
     * 模式切换
     */
    async onModeChange(data, flag) {
      // 查看是否有权限接管无人机
      if (!(await this.isTakeOver())) {
        this.$message.warning("请先接管设备");
        return;
      }
      if (this.flightMode == "离线状态") {
        return this.$message.warning("处于离线状态，不可切换模式！");
      }

      let mode = this.modeList.find((item) => item.data === data);
      if (
        mode.label == "定高模式" ||
        mode.label == "定点模式" ||
        mode.label == "保持模式"
      ) {
        if (this.rcChannelState !== 0 || this.rcChannelState !== "-99") {
          await this.$confirm(
            `请确定是否进行${mode.label}切换,目前无人机处于${
              this.rcChannelStateList[this.uavRealTimeData.rcChannelState]
            }状态`,
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          );
        } else {
        }
      } else {
      }

      if (mode) {
        this.$store.dispatch("MMCFlightControlCenter/uav/modeChange", {
          id: mode.data,
          callback: () => {
            this.$message.success("操作成功");
          },
        });
      }
    },
    /**
     * 获取天气数据
     */
    async getWeather() {
      let lat;
      let lon;
      if (this.isHangar) {
        lat = this.hangar.latitude;
        lon = this.hangar.longitude;
      } else {
        // 无人机需要通过实时数据获取经纬度
        if (this.uavRealTimeData?.locationCoordinate3D?.latitude) {
          lat = this.uavRealTimeData.locationCoordinate3D.latitude;
          lon = this.uavRealTimeData.locationCoordinate3D.longitude;
        }
      }
      if (lat) {
        let res = await System.getCoordinatesWeather({
          lat,
          lon,
        });
        this.weather = res.data[0];
        const date = new Date();
        let time = date.getHours();
        this.weatherIcon = require(`./assets/images/weather/icon/iconfont/W${
          time >= 18 ? this.weather.nightIcon : this.weather.dayIcon
        }.png`);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.control-top {
  position: absolute;
  top: 0;
  left: 50%;
  transform: translate(-50%, 0);
  height: 58px;
  background: #222222;
  border-radius: 0px 0px 2px 2px;
  backdrop-filter: blur(1px);
  display: flex;
  align-items: center;
  font-family: MicrosoftYaHei;
  font-size: 16px;
  z-index: 2;
  color: #ffffff;
  line-height: 21px;
  padding: 0 4px;

  .ct-item {
    position: relative;
    padding: 0 12px;

    &::after {
      content: "";
      position: absolute;
      right: 0;
      top: 50%;
      transform: translate(-50%, -50%);
      width: 1px;
      height: 32px;
      background: linear-gradient(
        180deg,
        rgba(255, 255, 255, 0) 0%,
        #ffffff 47%,
        rgba(255, 255, 255, 0) 100%
      );
    }

    &.last {
      &::after {
        display: none;
      }
    }
  }

  .ct-weather {
    display: flex;
    gap: 12px;

    .ctw-icon {
      width: 36px;
      height: 36px;
    }

    .ctw-wind {
      .ctww-line1 {
        display: flex;
        gap: 18px;
        align-items: center;

        img {
          width: 19px;
          height: 19px;
        }
      }
    }
  }
  .ct-take-off {
    font-family: YouSheBiaoTiHei;
    font-size: 24px;
    color: #6aff64;
    line-height: 32px;
  }

  .ct-info {
    display: flex;
    gap: 12px;
    align-items: center;
    position: relative;

    .item {
      height: 24px;
      width: 24px;
    }

    img {
      width: 100%;
      height: 100%;
    }

    .s-count {
      position: absolute;
      font-size: 10px;
      right: 12px;
      top: -6px;
    }
  }
}

.el-dropdown-link {
  cursor: pointer;
  color: #fff;
}
.el-icon-arrow-down {
  font-size: 12px;
  margin-left: 0;
}

.invalid {
  opacity: 0.7;
}
</style>