import mqtt from 'mqtt';
import mqttOrders from "./mqttOrders";

function uint8array2json(uint8array) {
  if (!uint8array || !uint8array.length) {
    return uint8array;
  }
  let decoder = new TextDecoder("utf-8");
  let content = decoder.decode(uint8array);
  return content ? JSON.parse(content) : content;
}

export default {
  namespaced: true,
  state: {
    client: null, //mqtt client
    clientId: "",
    url: "", //mqtt地址
    dataSet: {
      //数据集
      /* deviceHardId: {
        type(如258): {}
      } */
    },
    mqttOrders, //所有指令
  },
  mutations: {
    setClient(state, data) {
      state.client = data;
    },
    setClientId(state, data) {
      state.clientId = data;
    },
    setUrl(state, data) {
      state.url = data;
    },
    setDataSet(state, data) {
      state.dataSet = data;
    },
  },
  actions: {
    init({ commit, state }, data) {
      let protocol = state.url.replace(/(.+)\:\/\/.*/, "$1");
      let clientId = Date.now();
      let client = mqtt.connect(data.url, {
        protocol,
        clientId,
      });

      commit("setClient", client);
      commit("setClientId", clientId);

      client.on("reconnect", function (reconnect) {
        console.log(reconnect, "reconnect");
      });

      client.on("message", (topic, payload, packet) => {
        let data = uint8array2json(payload);
        let deviceHardId = packet.topic.split("/")[2];

        if (!state.dataSet[deviceHardId]) {
          state.dataSet[deviceHardId] = {};
        }
        state.dataSet[deviceHardId][data.type] = data;
        let temp = {};
        Object.keys(state.dataSet).forEach((key) => {
          temp[key] = state.dataSet[key];
        });
        commit("setDataSet", temp);
      });

      /**
       * 订阅无人机上线下线消息
       */
      /* subscribe(`on_and_off_broker`, (e) => {
        console.log("subscribe on_and_off_broker");
      }); */

      return new Promise((resolve, reject) => {
        client.on("connect", () => {
          console.log("mqtt is connected");
          resolve();
        });

        client.on("`error`", (error) => {
          console.log("mqtt is `error`", error);
          reject();
        });
      });
    },
    /**
     * 订阅
     * @param {*} topic
     * @param {*} callback
     */
    subscribe({ state }, { topic, callback }) {
      if (!topic) {
        return topic;
      }
      let { client } = state;
      if (client) {
        console.log("订阅数据a", topic);
        client.subscribe(topic, callback);
      }
    },
    /**
     * 取消订阅
     * @param {*} topic
     * @returns
     */
    unsubscribe({ state }, { topic }) {
      if (!topic) {
        return topic;
      }
      let { client } = state;
      if (client) {
        client.unsubscribe(topic);
      }
    },
    /**
     * 发布
     * QoS 0：消息最多传递一次，如果当时客户端不可用，则会丢失该消息。
     * QoS 1：消息传递至少 1 次。
     * QoS 2：消息仅传送一次。
     * @param {*} publication
     * @param {*} callback
     * @param {*} options
     * @param {*} type
     */
    publish({ state }, { topic, data, callback, options = { qos: 0 } }) {
      console.log('publish', topic, data)
      state.client.publish(
        topic,
        new TextEncoder().encode(JSON.stringify(data)),
        options,
        callback
      );
    },
    /**
     * 全部指令
     * @param {*} param0
     * @param {*} param1
     * @param {String} param1.topic 发送的主题
     * @param {String} param1.order 指令名称
     * @param {Object} param1.data 指令对应的数据
     * @param {Function} param1.callback 成功回调
     */
    order({ dispatch }, { topic, order, data, callback }) {
      if (mqttOrders[order] === undefined) {
        throw "该命令不存在！";
      }

      dispatch("publish", {
        topic,
        data: {
          type: mqttOrders[order],
          data,
          callback,
        },
      });
    },
  },
};