import * as mountList from "../../MMCMount/utils.js";
import { mapState } from "vuex";

export default {
  data() {
    return {
      wsJoystick: null,
      control_speed: 3, //控制速度
      mountList,
      lastDirection: "stop", //最后一次操控方向
      str: null,
      mountCtrlList: null,
    };
  },
  mounted() {
    this.mountCtrlList = {
      ...this.mountList,
    };
  },
  computed: {
    ...mapState("MMCFlightControlCenter", ["mqttIP"]),
    ...mapState("MMCFlightControlCenter/uav", ["selectMount", "uav"]),
    mountCtrl() {
      return this.mountCtrlList[this.selectMount?.gimbalName];
    },
  },
  watch: {
    str: function (val) {
      this.$store.dispatch("MMCMQTT/publish", {
        topic: "PX4/OBTAIN/" + this.uav.deviceId,
        data: {
          type: 513,
          data: val,
        },
        callback() {},
      });
    },
  },
  beforeDestroy() {
    console.log("closeJoystick.........................");
    this.closeJoystick();
  },
  methods: {
    /**
     * 初始化操纵杆连接
     */
    initJoystick() {
      this.wsJoystick && this.wsJoystick.close();
      let uavCate = "PX4";
      let topic = `${uavCate}/OBTAIN/${this.uav.deviceId}`;
      this.wsJoystick = new WebSocket("ws://127.0.0.1:8802");
      this.wsJoystick.onopen = () => {
        console.log("joystick.js 连接上 ws://127.0.0.1:8802");
        this.wsJoystick.send(
          JSON.stringify({
            type: 2003,
            data: {
              mqttAddr: this.mqttIP,
              mqttIport: 1883,
              mqttTopic: topic,
              vehicleType: uavCate == "PX4" ? 1 : 0,
            },
          })
        );
        this.wsJoystick.send(JSON.stringify({ type: 2001, data: {} }));
      };
      let _this = this;
      this.wsJoystick.onmessage = (e) => {
        let reader = new FileReader();
        reader.onload = (event) => {
          let obj = JSON.parse(event.currentTarget.result);
          if (obj.type == 518) {
          }
          let data = JSON.parse(event.currentTarget.result).data;
          window.$log("joystick.js message", data);
          let y = data.channel03; //油门值 0-1000

          // console.log(data.channel03,data,"yyyyyyyy");
          if (y || y == 0) {
            this.$store.commit("MMCFlightControlCenter/joystick/setState", {
              key: "throttleValue",
              value: y,
            });
          }
          if (this.mountCtrl) {
            //拍照
            if (data.channel06) {
              let buffer = this.mountCtrl.take_photo();
              this.send_mqtt(buffer);
            }
            //录像
            if (data.channel05) {
              let buffer = null;
              if (data.channel05 == 1) {
                buffer = this.mountCtrl.record(true);
              } else if (data.channel05 == 2) {
                buffer = this.mountCtrl.record(false);
              }
              this.send_mqtt(buffer);
            }
            //云台模式
            // if (data.channel07) {
            //   let buffer = null
            //   if (data.channel07 == 1) {
            //     buffer = this.mountCtrl.gimbal_mode_ctrl(0)
            //   } else if (data.channel07 == 2) {
            //     buffer = this.mountCtrl.gimbal_mode_ctrl(2)
            //   }
            //   this.send_mqtt(buffer)
            // } else {
            //   let buffer = this.mountCtrl.gimbal_mode_ctrl(1)
            //   this.send_mqtt(buffer)
            // }
            //变焦
            if (data.channel09) {
              let buffer = null;
              if (data.channel09 == 1) {
                buffer = this.mountCtrl.zoom(2, 0);
              } else if (data.channel09 == 2) {
                buffer = this.mountCtrl.zoom(0, 0);
              }
              this.send_mqtt(buffer);
              buffer = this.mountCtrl.zoom(1, 0);
              this.send_mqtt(buffer);
            }
          }

          //飞行模式
          if (data.channel08) {
            if (data.channel08 == 1) {
              //定点
              this.str = "POSITION";
            } else if (data.channel08 == 2) {
              //航线
              this.str = "AUTO_MISSION";
            } else if (data.channel08 == 3) {
              //返航
              this.str = "AUTO_RTL";
            } else if (data.channel08 == 4) {
              //保持
              this.str = "HOLD";
            }
          }

          //channel10 云台俯仰 0：没按 1：上 2：下
          if (data.channel10) {
            const direction = {
              1: "up",
              2: "down",
            };

            const ctr = direction[data.channel10];
            // console.log('摇杆按下了channel10', ctr);
            _this.cameraMountCtr(ctr);
          }
          //channel11 云台偏航 0：没按 1：左 2：右
          if (data.channel11) {
            const direction = {
              1: "left",
              2: "right",
            };

            const ctr = direction[data.channel11];
            // console.log('摇杆按下了channel11', ctr);
            _this.cameraMountCtr(ctr);
          }

          if (data.channel10 == 0 && data.channel11 == 0) {
            _this.cameraMountCtr("stop");
          }
        };
        reader.readAsText(e.data);
      };
    },
    /**
     * 关闭操纵杆
     */
    closeJoystick() {
      if (!this.wsJoystick) {
        return;
      }
      this.cameraMountCtr("stop", this.lastMountCtrl);
      setTimeout(() => {
        this.wsJoystick.send(JSON.stringify({ type: 2010, data: {} }));
        this.wsJoystick && this.wsJoystick.close();
        this.wsJoystick = null;
      }, 2000);
    },
    /**
     * 相机挂载控制
     * @param {String} type up: 上，left：打，right：右，down：下
     */
    cameraMountCtr(type) {
      /* if(type !== 'stop'){
        console.log('cameraMountCtr', !this.wsJoystick, !this.mountCtrl || !type, this.lastDirection === type)
        console.log('this.mountCtrl', this.mountCtrl, type)
      } */

      if (!this.wsJoystick) {
        return;
      }

      if (!this.mountCtrl || !type) {
        return;
      }

      if (this.lastDirection === type) {
        return;
      }

      console.log("摇杆按下了", type);

      let buffer = null;
      switch (type) {
        case "stop":
          if (["up", "down"].includes(this.lastDirection)) {
            buffer = this.mountCtrl.gimbal_pitch_ctrl(0, this.control_speed);
          } else if (["left", "right"].includes(this.lastDirection)) {
            buffer = this.mountCtrl.gimbal_yaw_ctrl(0, this.control_speed);
          }
          // buffer = this.mountCtrl.gimbal_pitch_ctrl(0, this.control_speed);
          // buffer = this.mountCtrl.gimbal_yaw_ctrl(0, this.control_speed);
          break;
        case "up":
          buffer = this.mountCtrl.gimbal_pitch_ctrl(1, this.control_speed);
          break;
        case "left":
          buffer = this.mountCtrl.gimbal_yaw_ctrl(-1, this.control_speed);
          break;
        case "right":
          buffer = this.mountCtrl.gimbal_yaw_ctrl(1, this.control_speed);
          break;
        case "down":
          buffer = this.mountCtrl.gimbal_pitch_ctrl(-1, this.control_speed);
          break;
      }

      this.lastDirection = type;
      this.send_mqtt(buffer);
    },
    send_mqtt(buffer) {
      this.$store.dispatch("MMCMQTT/publish", {
        topic: "PX4/OBTAIN/" + this.uav.deviceId,
        data: {
          type: 514,
          data: {
            mountId: this.selectMount.mountId,
            payload: buffer,
          },
        },
        callback() {},
      });
    },
  },
};
