import axios from "axios";
// if (typeof WebSocket === "undefined") {
//   WebSocket = require("ws");
// }

const baseOptions = {
  // const baseOptions = {
  //   url: "https://sop-tips-uat.ikandy.cn/dh",
  // url: "http://192.168.1.7:1002/dh",
  method: "post",
  headers: {
    "access-token": "1234",
    "Content-type": "application/json",
  },
};

function callHook(eventName, data) {
  if (this.eventObj[eventName]) {
    Promise.resolve().then(() => {
      this.eventObj[eventName](data);
    });
  }
}

class tencentDH {
  constructor(options) {
    this.eventTimer = [];
    this.eventObj = {};
    this.options = options;
    this.isConnected = false;
    this.topic = options.topic || "";
    this.playerUrl = options.playerUrl || "";
    this.status = 0;
    this.socket = null;
    this.speechId = "";
    this.allowInterrupt = true;
    this.apiUrl = options.apiUrl;
    this.socketUrl = options.socketUrl;
    this.video = null;
    // this.isBroswer = window ? true : false;
  }

  async initResource() {
    const option = {
      url: this.apiUrl,
      method: "post",
      data: {
        resource: {
          type: "dh",
          sp: "tencent",
        },
        module: "new",
        arguments: {
          user_id: this.options.user || "dh_test",
          chat_type: this.options.chatType || 8,
          solution: this.options.solution || "s1_black",
          protocol: this.options.protocol || "flv",
          speech_type: this.options.speechType || 1,
          resIndex: 1,
        },
      },
      headers: {
        "Content-type": "application/json",
      },
    };
    try {
      const res = await axios(option);
      if (res.data.status !== 0) {
        callHook.call(
          this,
          "initError",
          (res.data.msg += ": " + res.data.data.msg ? res.data.data.msg : "")
        );
        return;
      }
      this.topic = res.data.data.topic;
      this.playerUrl = res.data.data.play_stream_addr;
    } catch (err) {
      callHook.call(this, "initError", "初始化资源失败，接口内部错误");
    }
  }

  initPlayer() {
    callHook.call(this, "resources", {
      playerUrl: this.playerUrl,
      topic: this.topic,
    });
  }

  initMessage() {
    this.socket = new WebSocket(this.socketUrl + "?topic=" + this.topic);
    console.log("socket", this.socketUrl + "?topic=" + this.topic);
    this.socket.onopen = () => {
      this.isConnected = true;
      callHook.call(this, "loaded", this.topic);
    };
    this.socket.onmessage = (e) => {
      const data = JSON.parse(e.data);
      // console.log("websocket :>> ", data);

      switch (data.type) {
        case 1:
          break;
        case 2:
          break;
        case 3:
          if (data.text === "speak_start") {
            console.log("websocket :>> ", data);

            if (this.status === 1) {
              this.status = 2;
            }
          } else if (data.text === "speak_over") {
            if (this.status === 2) {
              this.status = 0;
              callHook.call(this, "next");
            }
          }
          break;
        default:
          callHook.call(this, "renderError", data.text);
          break;
      }
    };
    this.socket.onerror = (e) => {
      callHook.call(this, "webSocketError", "websocket出错");
    };
  }

  addEventListener(eventName, callback) {
    // this.eventObj[eventName] = callback;
    this.eventObj[eventName] = callback;
  }

  removeEventListener(eventName, callback) {
    // if (this.eventObj[eventName] === callback) {
    //   delete this.eventObj[eventName];
    // }
    if (this.eventObj[eventName] === callback) {
      delete this.eventObj[eventName];
    }
  }

  interrupt() {}

  exec(mission, data, moreMessage) {
    let text = "";
    this.eventTimer = [];
    if (moreMessage) text += moreMessage;
    text += mission.text;
    this.allowInterrupt = mission.interrupt;
    this.textRender(text);
    mission.events?.forEach((event) => {
      event.data.content.data.resources = data;
      this.eventTimer.push(
        setTimeout(
          function () {
            callHook.call(
              this,
              event.data.content.eventName,
              event.data.content.data
            );
          }.bind(this),
          event.time
        )
      );
    });
  }

  show(message) {}

  command(command) {}

  mute(mute) {
    if (this.options.videosink !== "publish")
      this.video && (this.video.muted = mute);
  }

  interrupt() {
    if (this.allowInterrupt) {
      this.eventTimer.forEach((timer) => {
        clearTimeout(timer);
      });
      // this.textRender(" ");
    }
  }

  textRender(message) {
    if (this.status > 0 && !this.allowInterrupt) {
      return;
    }
    this.status = 1;
    axios({
      ...baseOptions,
      url: this.apiUrl,
      data: JSON.stringify({
        path: "input",
        args: { topic: this.topic, text: message },
      }),
    }).then((res) => {
      if (res.data.errorCode !== 0) {
        callHook.call(this, "textRenderError", res.data.msg);
      }
    });
  }
}

export default tencentDH;
