<template>
  <div class="control-bottom">
    <div class="control-bottom-item" @click="onStartTask">
      <img src="./assets/images/start.svg" />
      <span class="dib">{{ $t('common.一键任务') }} </span>
    </div>
    <div class="control-bottom-item" @click="onReturnFlight">
      <img src="./assets/images/return.svg" />
      <span class="dib">{{ $t('common.一键返航') }}</span>
    </div>
    <div class="control-bottom-item" @click="onLand" v-if="isHangar">
      <img src="./assets/images/end.svg" />
      <span class="dib">{{ $t('common.紧急迫降') }}</span>
    </div>
    <div class="control-bottom-item" @click="onTaskEnd" v-else>
      <img src="./assets/images/end.svg" />
      <span class="dib">{{ $t('common.任务结束') }}</span>
    </div>
    <template v-if="uav.network === 2">
      <div v-if="controlType === 0" class="control-bottom-item" @click="onInfieldControl">
        <img src="./assets/images/auto.svg" />
        <span class="dib">{{ $t('common.自动') }}</span>
      </div>
      <div v-else-if="controlType === 1"
        :class="manualControlStatus ? 'active control-bottom-item' : 'control-bottom-item'" @click="onModeKeyboard">
        <img :src="require(`./assets/images/${manualControlStatus ? 'manual' : 'manual1'}.svg`)" />
        <span class="dib">{{ $t('common.摇杆') }} </span>
      </div>
      <div v-else-if="controlType === 2" class="control-bottom-item" @click="onModeAuto">
        <img src="../../assets/images/keyboard.png" alt />
        <span class="dib">{{ $t('common.键盘') }}</span>
      </div>
    </template>

    <template v-else>
      <div v-if="controlType === 0" class="control-bottom-item" @click="onModeManual">
        <SymbolIcon icon="zidong" />
        <span class="dib">{{ $t('common.自动') }}</span>
      </div>
      <div v-if="controlType === 1" class="control-bottom-item" @click="onModeAuto">
        <SymbolIcon icon="shoudong" />
        <span class="dib">{{ $t('common.手动') }}</span>
      </div>
      <div class="control-bottom-item">
        <img src="./assets/images/network.svg" />
        <span class="dib">{{ network() }}</span>
      </div>
      <div class="control-bottom-item">
        <img src="./assets/images/video.svg" />
        <span class="dib">{{ $t('common.图传') }}</span>
      </div>
    </template>
    <!-- 键盘控制 -->
    <KeyControl v-if="controlType === 2" @close="onModeAuto"></KeyControl>
    <!-- 强制切换外场权限 -->
    <el-dialog title :visible.sync="showInfieldControlDialog" width="30%" :append-to-body="true" custom-class="mmc"
      style="margin-top: 20vh">      <div class="endrenwu">
        <div class="tishiyu">{{ $t('common.温馨提示') }}</div>
        <div class="queding" v-if="!isAcceleratorMedian">
          {{ $t('common.当前油门值为请调到中位', { value: throttleValue.toFixed(2) || 0 }) }}
        </div>
        <div class="queding" v-if="isAcceleratorMedian">
            {{ $t('common.摇杆已处于中位即将切换内场权限') }}
          </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapActions } from "vuex";
import { flightTaskAPI, Control_API } from "../../../../../../api";
import KeyControl from "./components/keyControl";
import joystick from "../../../../../../mixins/joystick";

export default {
  name: "ControlBottom",
  mixins: [joystick],
  components: {
    KeyControl,
  },
  inject: ["bus"],
  props: {
    // 是否是机库组件
    isHangar: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      showInfieldControlDialog: false, //强制切换状态为内场权限 提示框
      isAcceleratorMedian: false, //油门是否在中位
      YGPermissionsSend: false, //摇杆权限更改中
      // 摇杆手动控制状态
      manualControlStatus: false,
      controlType: 0, //控制类型, 0: 自动 1: 摇杆 2: 键盘
    };
  },
  watch: {
    // 状态改变时摇杆会切换为手动模式并且抢权限
    "onInfieldControlFn": {
      handler(val) {
        if (val) {
          this.onInfieldControl()
        }
      }
    },
    throttleValue(val) {
      // val = -1 代表摇杆已经建立连接 ，rcState为0 代表当前权限在外场需要去展示摇杆油门值 
      if (val == -1 &&this.uavRealTimeData.rcState == 0) {
        this.showInfieldControlDialog = true;
      }
      // 判断是否为外场权限
      if (this.uavRealTimeData.rcState == 0) {
        // 判断油门是否处于中位
        if (val >= 470 && val <= 530) {
          console.log(this.uavRealTimeData, val, 'val');

          this.isAcceleratorMedian = true;
          if (!this.YGPermissionsSend) {
            this.YGPermissionsSend = true;
            // 发送抢权限指令
            this.$store.dispatch(
              "MMCFlightControlCenter/uav/changeYGPermissions",
              {
                callback: () => { },
              }
            );
            setTimeout(() => {
              if (this.uavRealTimeData.rcState == 1) {
                // 摇杆切换为手动模式
                if (!this.manualControlStatus) {
                  this.$message.success(this.$t('common.已切换内场权限摇杆即将切换为手动模式'));
                  // 切换为是手动模式
                  this.onModeManual();
                } else {
                  this.$message.success(this.$t('common.已切换内场权限请使用摇杆控制'));

                }
                this.showInfieldControlDialog = false;
              } else {
                // this.$message.error(this.$t('common.摇杆权限切换失败'));
        console.log(this.$t('common.摇杆权限切换失败'));
              }
              this.YGPermissionsSend = false;
            }, 2000);
          }
        } else {
          this.isAcceleratorMedian = false;
        }
      }
    },
    "manualControlStatus": {
      handler(val) {
        if (val) {
          this.$message.success(this.$t('common.手动模式已开启'));
        }
        this.$store.commit("MMCFlightControlCenter/joystick/setState", {
          key: "manualControlStatus",
          value: val,
        });
      },
    },
    immediate: true,
  },
  computed: {
    ...mapState("MMCFlightControlCenter/uav", ["uav", "airlineData", "uavRealTimeData"]),
    ...mapState("MMCFlightControlCenter/joystick", ["onInfieldControlFn", "throttleValue"]),
  },
  methods: {
    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 this.$t('common.专网');
          } else if (k.priority == 3 && k.using) {
            return this.$t('common.公网');
          } else if (k.priority == 1 && k.using) {
            return this.$t('common.图传');
          }
        }
      }
      return name || this.$t('common.离线');
    },
    async onInfieldControl() {
      // 判断是否已接管
      if (!(await this.isTakeOver())) {
        this.$message.warning(this.$t('common.请先接管设备'));
        return;
      }
      let networkType = this.network()
      if (networkType == this.$t('common.离线')) {
        return this.$message.info(this.$t('common.无人机不在线'));
      }
      // 如果是内场权限 且摇杆为手动模式就提示用户使用
      if (this.uavRealTimeData.rcState == 1 && this.manualControlStatus) {
        this.$message.success(this.$t('common.当前处于内场模式请使用摇杆控制'));
      } else {
        // 否则如果摇杆是手动模式没内场权限，则展示油门弹窗,油门值为中位时发起抢权限指令
        if (this.manualControlStatus) {
          this.showInfieldControlDialog = true;
        } else {
          this.$message.success("摇杆即将切换为手动模式,请稍等！");
          // 切换为手动模式
          this.onModeManual();
        }
      }
    },
    /**
     * 接管判断, 机库模块中不需要判断接管
     */
    async isTakeOver() {
      if (this.isHangar) {
        return await this.$store.dispatch(
          "MMCFlightControlCenter/hangar/isTakeOver"
        );
      } else {
        return await this.$store.dispatch(
          "MMCFlightControlCenter/uav/isTakeOver"
        );
      }
    },
    // 一键任务
    onStartTask() {
      this.bus.$emit("startTask");
    },
    // 一键返航
    async onReturnFlight() {
      // 判断是否已接管
      if (!(await this.isTakeOver())) {
        this.$message.warning(this.$t('common.请先接管设备'));
        return;
      }
      this.$confirm(this.$t('common.请确认是否进行一键返航操作'), this.$t('common.安全确认'), {
        cancelButtonText: this.$t('common.取消'),
        confirmButtonText: this.$t('common.确定'),
        customClass: "uav_controlPane",
        showClose: false,
      }).then((res) => {
        this.$store.dispatch("MMCFlightControlCenter/uav/returnFlight", {
          callback: (isOk) => {
            isOk && this.$message.success(this.$t('common.发出返航指令成功'));
          },
        });
      });
    },
    // 任务结束
    async onTaskEnd() {
      // 判断是否已接管
      if (!(await this.isTakeOver())) {
        this.$message.warning(this.$t('common.请先接管设备'));
        return;
      }
      this.$confirm(this.$t('common.请确认是否进行任务结束操作'), this.$t('common.安全确认'), {
        cancelButtonText: this.$t('common.取消'),
        confirmButtonText: this.$t('common.确定'),
        customClass: "uav_controlPane",
        showClose: false,
      }).then((res) => {
        this.$store.dispatch("MMCFlightControlCenter/uav/takeEnd", {
          callback: (isOk) => {
            isOk && this.$message.success(this.$t('common.发出任务结束指令成功'));
          },
        });
      });
    },
    // 紧急降落
    async onLand() {
      // 判断是否已接管
      if (!(await this.isTakeOver())) {
        this.$message.warning(this.$t('common.请先接管设备'));
        return;
      }
      this.$confirm(this.$t('common.请确认是否进行紧急降落操作'), this.$t('common.安全确认'), {
        cancelButtonText: this.$t('common.取消'),
        confirmButtonText: this.$t('common.确定'),
        customClass: "uav_controlPane",
        showClose: false,
      }).then((res) => {
        this.$store.dispatch("MMCFlightControlCenter/uav/land", {
          callback: (isOk) => {
            isOk && this.$message.success(this.$t('common.发出紧急降落指令成功'));
          },
        });
      });
    },
    /**
     * 手动模式
     */
    async onModeManual() {
      // 判断是否已接管
      if (!(await this.isTakeOver())) {
        this.$message.warning(this.$t('common.请先接管设备'));
        return;
      }

      this.$store.dispatch("MMCFlightControlCenter/uav/modeManual", {
        callback: (isOk) => {
          if (isOk) { }
          isOk && (this.controlType = 1);
        },
      });
      // 打开软件
      let a = document.createElement("a");
      a.href = "JoystickTools://";
      a.click();
      setTimeout(() => {
        this.initJoystick();
      }, 5000);
    },

    /**
     * 自动模式
     */
    async onModeAuto() {
      // 判断是否已接管
      if (!(await this.isTakeOver())) {
        this.$message.warning(this.$t('common.请先接管设备'));
        return;
      }
      this.$store.dispatch("MMCFlightControlCenter/uav/modeAuto", {
        callback: (isOk) => {
          isOk && (this.controlType = 0);
        },
      });
      this.closeJoystick();
    },
    /**
     * 键盘模式
     */
    async onModeKeyboard() {
      // 判断是否已接管
      if (!(await this.isTakeOver())) {
        this.$message.warning(this.$t('common.请先接管设备'));
        return;
      }
      this.controlType = 2;
    },
    /**
     * 键盘控制
     */
    clickControl() { },
    /**
     * 停止键盘控制
     */
    cancelControl() { },
  },
};
</script>

<style lang="scss" scoped>
.control-bottom {
  position: absolute;
  left: 50%;
  bottom: 150px;
  transform: translate(-50%, 0);
  display: flex;
  gap: 34px;
  z-index: 1;

  .control-bottom-item {
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    gap: 4px;
    background: #ffffff;
    border-radius: 2px;
    color: #000;
    width: 48px;
    text-align:center;
    height: 48px;
    font-size: 10px;
    flex-wrap: wrap;
    cursor: pointer;
    

    &:hover {
      transform: scale(1.1);
    }
  }

  .active {
    background-color: #0cc81f;
  }
}

.key-control {
  position: fixed;
  right: 100px;
  bottom: 120px;
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 360px;
  height: 120px;
  background: rgba(32, 32, 30, 0.8);
  border-radius: 10px;
  padding: 8px;

  .head {
    width: 360px;
    color: #fff;
    text-indent: 16px;
    line-height: 32px;
    display: flex;
  }

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

    >div {
      flex-direction: column;
      display: flex;
      align-items: center;

      >div {
        display: flex;

        div {
          background: #333;
          width: 32px;
          height: 32px;
          font-family: MicrosoftYaHei;
          font-size: 16px;
          color: #ffffff;
          font-style: normal;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
        }

        .active {
          background: #ead91b;
        }
      }
    }

    .line {
      width: 1px;
      height: 60px;
      border: 1px solid;
      border-image: linear-gradient(180deg,
          rgba(255, 255, 255, 0),
          rgba(255, 255, 255, 1),
          rgba(255, 255, 255, 0)) 1 1;
    }
  }
}

.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;
}

.endrenwu {
  width: 100%;
  height: 177px;
  border: 1px solid #70daf9;
  background: rgba(9, 32, 87, 0.7) !important;
}

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

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