<template>
  <div>
    <div class="nset_control_box dialog1027" v-if="show">
      <div class="dialog-header">
        <img class="dialog-header__icon" src="../../assets/images/mount_head.png" />
        <div class="dialog-header__title">操作区域</div>
        <div class="dialog-header__close" @click="$emit('exit')">关闭</div>
      </div>
      <div class="nset_control_box_area">
        <div class="wrj">
          <!-- <div class="w48 h48 item mb3  cf  tc cp" @click="$emit('uav-location')">
                    <SymbolIcon icon="dingwei" />
                    <span class="txt">定位</span>
          </div>-->
          <div class="item" @click="onSwitchAirline">
            <SymbolIcon icon="guiji" />
            <span class="txt">轨迹</span>
          </div>
          <div class="item" @click="onContinueFly">
            <SymbolIcon icon="jixufeihang1" />
            <span class="txt">继续飞行</span>
          </div>
          <div class="item" @click="onPauseFly">
            <SymbolIcon icon="zantingfeihang1" />
            <span class="txt">暂停飞行</span>
          </div>
          <div class="item" @click="safetyNotice = !safetyNotice">
            <SymbolIcon icon="anquanjiangla1" />
            <span class="txt">紧急迫降</span>
          </div>
          <div class="item" @click="showLogger = !showLogger">
            <SymbolIcon icon="yunhangrizhi2" />
            <span class="txt">运行日志</span>
          </div>
          <div class="item" @click="guideFlight" v-if="uav && uav.network === 2">
            <SymbolIcon icon="tiaozhuandaozuobiao" />
            <span class="txt">指点飞行</span>
          </div>
          <div class="item" @click="onInfieldControl" v-if="uav && uav.network === 2">
            <img class="dib mt3" src="./assets/images/1.svg" alt />
            <span class="txt">内场控制</span>
          </div>
        </div>
      </div>
      <!-- 飞控 无人机 安全降落 -->
      <el-dialog
        :visible.sync="safetyNotice"
        width="30%"
        :append-to-body="true"
        style="margin-top: 20vh"
        custom-class="mmc"
      >
        <div class="endrenwu">
          <div class="tishiyu">紧急迫降</div>
          <div class="queding">无人机即将原地降落，请确认无人机下方是否安全！</div>
          <div class="btn_kuang">
            <div class="btn btn_lan" @click="safetyNotice = false">取消</div>
            <div style="width: 20px"></div>
            <div class="btn btn_lv" @click="onLand">确定</div>
          </div>
        </div>
      </el-dialog>
      <!-- 强制切换外场权限 -->
      <el-dialog
        title
        :visible.sync="showInfieldControlDialog"
        width="30%"
        :append-to-body="true"
        style="margin-top: 20vh"
      >
        <div class="endrenwu">
          <div class="tishiyu">温馨提示</div>
          <div class="queding" v-if="!isAcceleratorMedian">
            当前油门值为
            <span style="color:red">{{uavRealTimeData.rcChannelState.toFixed(2)||0}}</span>,请调到中位(470-530)
          </div>
          <div class="queding" v-if="isAcceleratorMedian">摇杆已处于中位，即将切换内场权限</div>
        </div>
      </el-dialog>
      <el-dialog
        title
        :visible.sync="guideFlightShow"
        width="30%"
        :append-to-body="true"
        :show-close="false"
        :close-on-click-modal="false"
        style="margin-top: 20vh"
        custom-class="mmc"
      >
        <div class="endrenwu guideFlight">
          <div class="tishiyu">引导飞行确认</div>
          <div class="queding">位置获取成功，请确认是否进行指点模式飞行</div>
          <div class="fleSpeed">
            指点飞行速度：
            <el-input oninput="value=value.replace(/[^0-9.]/g,'')" v-model="flySpeed"></el-input>
            <span style="opacity: 0;">1</span>(米/秒)
          </div>
          <div class="red" v-if="maxSpeed">指点飞行最大速度为8米/秒</div>
          <div class="btn_kuang">
            <div class="btn btn_lan" @click="onGuideFlightCancel">取消</div>
            <div style="width: 20px"></div>
            <div class="btn btn_lv" @click="onGuideFlightConfirm">确定</div>
          </div>
        </div>
      </el-dialog>
    </div>
    <Logger v-if="showLogger" @close="showLogger = false"></Logger>
  </div>
</template>
<script>
let Point = null;
import { Control_API } from "../../../../../../../../api";
import SymbolIcon from "../../../../../../../../../symbol-icon";
let handler = null;
import { mapGetters, mapState, mapActions } from "vuex";
import Logger from "./components/logger";

// 引用bus
import Vue from "vue";
import dayjs from "dayjs";

const Bus = new Vue();

export default {
  components: { SymbolIcon, Logger },
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    ModeStatus: {
      type: String,
      default: () => "",
    },
    isHangar: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      isAcceleratorMedian: false, //油门是否在中位
      YGPermissionsSend: false, //摇杆权限更改中
      safetyNotice: false, //安全降落弹框
      chargerPower: true,
      showInfieldControlDialog: false, //强制切换状态为内场权限 提示框
      flySpeed: 6, //指点飞行设置
      maxSpeed: false,
      showLogger: false, //显示日志
      guideFlightShow: false, //指示指点飞行的窗口
      guideFlightDone: true, //指点飞行是否已完成
      guideFlightLat: "", //指点飞行选择的纬度
      guideFlightLng: "", //指点飞行选择的经度.
    };
  },
  computed: {
    ...mapState("MMCFlightControlCenter/uav", [
      "uav",
      "airlineEntity",
      "userInfo",
      "uavRealTimeData",
    ]),
    ...mapState("MMCFlightControlCenter", ["userInfo", "cesiumViewer"]),
  },
  watch: {
    "uavRealTimeData.rcChannelState"(val) {
      // 判断是否为外场权限
      if (this.uavRealTimeData.rcState == 0) {
        // 判断油门是否处于中位
        if (val >= 470 && val <= 530) {
          this.isAcceleratorMedian = true;
          if (!this.YGPermissionsSend) {
            this.YGPermissionsSend = true;
            // 发送抢权限指令
            this.$store.dispatch(
              "MMCFlightControlCenter/uav/changeYGPermissions",
              {
                callback: () => {},
              }
            );
            setTimeout(() => {
              if (this.uavRealTimeData.rcState == 1) {
                this.$message.success("已切换内场权限，请使用摇杆控制！");
                this.showInfieldControlDialog = false;
              } else {
                // this.$message.error("摇杆权限切换失败");
                console.log("摇杆权限切换失败");
              }
              this.YGPermissionsSend = false;
            }, 2000);
          }
        } else {
          this.isAcceleratorMedian = false;
        }
      }
    },
  },
  beforeDestroy() {
    if (Point) {
      window.viewer.entities.remove(Point);
    }
  },
  methods: {
    ...mapActions("MMCFlightControlCenter/uav", [
      "continueFly",
      "pauseFly",
      "land",
      "routeControl",
      "isTakeOver",
    ]),
    async isTake() {
      // 判断是否已接管
      if (!this.isHangar && !(await this.isTakeOver())) {
        this.$message.warning("请先接管设备");
        return false;
      }
      return true;
    },
    /**
     * 显示隐藏航线
     */
    onSwitchAirline() {
      if (this.airlineEntity) {
        this.airlineEntity.show = !this.airlineEntity.show;
      }
    },
    /**
     * 暂停飞行
     */
    async onPauseFly() {
      // 判断是否已接管
      if (!(await this.isTake())) {
        return;
      }
      this.pauseFly({
        callback: () => {
          this.$message.success("暂停飞行指令已发出");
        },
      });
    },
    /**
     * 继续飞行
     */
    async onContinueFly() {
      // 判断是否已接管
      if (!(await this.isTake())) {
        return;
      }
      this.continueFly({
        callback: () => {
          this.$message.success("继续飞行指令已发出");
        },
      });
    },
    /**
     * 紧急迫降
     */
    async onLand() {
      // 判断是否已接管
      if (!(await this.isTake())) {
        return;
      }
      this.safetyNotice = false;
      this.land();
    },
    /**
     * 内场控制
     */
    async onInfieldControl() {
      // 判断是否已接管
      if (!(await this.isTake())) {
        return;
      }
      if (this.online === 0)
        return this.$message.warning("处于离线状态，不可操作！");
      // 自动切换摇杆权限
      if (this.uavRealTimeData.rcState == 1) {
        this.$message.success("当前处于内场模式，请使用摇杆控制！");
      } else {
        this.showInfieldControlDialog = true;
      }
    },
    /**
     * cesium添加目标点
     */
    addTargetPoint(viewer, position, name) {
      return viewer.entities.add({
        position,
        point: {
          pixelSize: 12,
          color: Cesium.Color.fromCssColorString("#ee0000"),
          outlineColor: Cesium.Color.fromCssColorString("#fff"),
          outlineWidth: 1,
          show: true,
        },
        label: {
          text: name,
          scale: 0.5,
          horizontalOrigin: Cesium.VerticalOrigin.CENTER,
          verticalOrigin: Cesium.VerticalOrigin.CENTER,
          disableDepthTestDistance: Number.POSITIVE_INFINITY,
          showBackground: true,
          outlineWidth: 0,
          pixelOffset: new Cesium.Cartesian2(26, -20),
        },
      });
    },
    /**
     * 指点飞行
     */
    async guideFlight() {
      // 判断是否已接管
      if (!(await this.isTake())) {
        return;
      }
      if (this.uav.online === 0)
        return this.$message.warning("处于离线状态，不可操作！");
      if (!this.guideFlightDone) {
        return this.$message.warning("指点飞行操作中！");
      }

      let viewer = this.cesiumViewer;
      // 指点飞行 wgs84
      this.guideFlightDone = false;
      let position = null;
      this.$message("请点击地图获取目标位置");
      handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas);
      handler.setInputAction((movement) => {
        let earthPosition = viewer.camera.pickEllipsoid(
          movement.position,
          viewer.scene.globe.ellipsoid
        );
        let cartographic = Cesium.Cartographic.fromCartesian(
          earthPosition,
          viewer.scene.globe.ellipsoid,
          new Cesium.Cartographic()
        );
        let lng = Cesium.Math.toDegrees(cartographic.longitude);
        let lat = Cesium.Math.toDegrees(cartographic.latitude);
        this.guideFlightLat = lat;
        this.guideFlightLng = lng;
        if (Point) {
          viewer.entities.remove(Point);
        }
        console.log(movement.position, "movement.position");
        (position = Cesium.Cartesian3.fromDegrees(lng, lat, 20)),
          (Point = this.addTargetPoint(viewer, position, "目标点"));
        // 指点飞行
        this.guideFlightShow = true;
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    },
    /**
     * 指点飞行确定事件
     */
    async onGuideFlightConfirm() {
      // 判断是否已接管
      if (!(await this.isTake())) {
        return;
      }
      console.log(
        {
          data: {
            latitude: this.guideFlightLat,
            longitude: this.guideFlightLng,
            speed: Number(this.flySpeed),
          },
          type: 518,
        },
        "指点移动指令下发"
      );
      // console.log(this.wsShow,'this.wsShow');
      // return
      if (this.flySpeed > 8) {
        this.maxSpeed = true;
      } else {
        // console.log(123);
        this.maxSpeed = false;
        this.guideFlightShow = false;
        this.routeControl({
          latitude: this.guideFlightLat,
          longitude: this.guideFlightLng,
        });
        this.flySpeed = 6;
        handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
      }
    },
    /**
     * 指点飞行取消事件
     */
    onGuideFlightCancel() {
      this.maxSpeed = false;
      this.guideFlightShow = false;
      this.flySpeed = 6;
      if (Point) {
        window.viewer.entities.remove(Point);
      }
      handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
      this.$message({
        type: "info",
        message: "已取消操作",
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.nset_control_box::v-deep {
  min-height: 111px;
  background: #222222;
  box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.1);
  border-radius: 10px;
  position: absolute;
  right: 65px;
  top: 126px;

  .nset_control_box_header {
    display: flex;
    justify-content: space-between;
    height: 36px;
    background: #3c3c3c;
    border-radius: 10px 10px 0px 0px;
    padding-left: 10px;

    .title {
      display: flex;
      align-items: center;

      .font {
        font-size: 20px;
        font-family: YouSheBiaoTiHei;
        color: #14faff;
        line-height: 26px;
        text-shadow: 0px 1px 1px rgba(2, 32, 56, 0.2);
        background: linear-gradient(
          135deg,
          #e3aa77 0%,
          #f5cda9 38%,
          #f9ecd3 58%,
          #fcdbb1 79%,
          #edb07a 100%
        );
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
      }
    }

    .exit {
      font-size: 14px;
      font-family: MicrosoftYaHei;
      color: #d2dfff;
      margin-right: 8px;
      cursor: pointer;
      display: flex;
      align-items: center;
    }
  }

  .nset_control_box_area {
    padding: 16px;
    .yc {
      display: flex;
      justify-content: space-between;

      .item {
        background-image: linear-gradient(
          179deg,
          #1773b6 0%,
          #3484c3 36%,
          #2a7abd 56%,
          #084681 100%
        );
        box-shadow: 0 0 5px 0 #0c1c47;
        border-radius: 4.5px;
      }
    }

    .wrj {
      display: flex;
      gap: 4px;

      .item {
        flex-shrink: 0;
        width: 58px;
        height: 58px;
        background: #3c3c3c;
        color: #fff;
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
        font-size: 28px;
        flex-direction: column;
        align-items: center;
        padding: 8px;
        box-sizing: border-box;
        cursor: pointer;

        .txt {
          font-size: 10px !important;
        }
      }
    }
  }
}

// 弹框样式
.endrenwu {
  width: 100%;
  height: 177px;
  border: 1px solid #70daf9;
  background: rgba(9, 32, 87, 0.7) !important;
}
.guideFlight::v-deep {
  height: 240px;
  display: flex;
  flex-direction: column;
  align-items: center;
  .fleSpeed {
    margin-top: 16px;
    color: #fff;
    display: flex;
    white-space: nowrap;
    align-items: center;
    .el-input__inner {
      background: transparent;
      color: #fff;
    }
  }
  .red {
    margin-top: 8px;
    color: red;
  }
  .btn {
    margin-top: 16px !important;
  }
}

.queding {
  color: #92d9ff;
  text-align: center;
  width: 100%;
  font-size: 14px;
  margin: 30px 0 0 0;
}

.tishiyu {
  color: #92d9ff;
  font-size: 18px;
  margin: 30px 0 0 0;
  text-align: center;
  width: 100%;
}

.btn_kuang {
  display: flex;
  justify-content: center;
  width: 100%;
}

.btn {
  width: 79px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  border-radius: 6px;
  font-size: 12px;
  margin: 20px 0 0 0;
  cursor: pointer;
}

.btn_lan {
  border-image: linear-gradient(180deg, #8adaff, rgba(82, 179, 255, 0)) 1 1;
  box-shadow: inset 0 0 5px #00ffff;
  background: rgba(23, 70, 216, 0.2);
  color: #606266;
}

.btn_lv {
  border-image: linear-gradient(180deg, #8adaff, rgba(82, 179, 255, 0)) 1 1;
  box-shadow: inset 0 0 5px #00ffff;
  background: rgba(23, 70, 216, 0.2);
  color: #fff;
}

.el-dialog__header {
  margin-left: 0;
  padding: 0;
  background: #3c3c3c;
}

.el-dialog__body {
  padding: 0;
  z-index: 2023 !important;
}

.el-dialog {
  z-index: 2022 !important;
  background: transparent !important;
}
.filter {
  cursor: no-drop;
  filter: grayscale(100%);
}
</style>
