import DH from "../DH/index";
import axios from "axios";

class dhDriver {
  constructor() {
    // this.params = params;
    // this.sp = "tencent";
  }

  isError(data) {
    if (!data) {
      // message.error("接口内部错误", 3);
      this.eventEmitter({
        name: "error",
        data: "接口内部错误",
      });
      return false;
    }
    if (data.data.status === 0 || data.data.errorCode === 0) {
      return false;
    }
    // message.error("接口错误" + data.data.errorInfo, 3);
    this.eventEmitter({
      name: "error",
      data: "接口错误" + data.data.errorInfo,
    });
    return true;
  }

  subscribe(callback) {
    this.callBack = callback;
  }

  async initDHResource() {
    const initOptions = {
      url:
        "https://hz-test.ikandy.cn:60010/ipaas_api/new/" +
        this.params["sessionId"],
      method: "get",
    };
    const result = await axios(initOptions);
    if (!this.isError(result)) this.initDh(result.data.data);
  }

  async initDh(initData) {
    // console.log("initDH-start");
    if (initData.supplier) {
      this.sp = initData.supplier;
    }

    const userDh = new DH({ sp: this.sp });
    // if (params["mode"] === "driver") {
    userDh.on("initError", (err) => {
      // message.error("initError: " + err, 3);
      this.eventEmitter({
        name: "error",
        data: "初始化错误" + err,
      });
      // alert(err);
    });

    userDh.on("renderError", (err) => {
      // alert(err);
      // message.error("renderError: " + JSON.stringify(err), 3);
      this.eventEmitter({
        name: "error",
        data: "渲染错误" + JSON.stringify(err),
      });
    });

    userDh.on("immediateCompleted", () => {
      // this.render();
    });

    userDh.on("textRenderError", (err) => {
      // alert(err);
      message.error("textRenderError: " + JSON.stringify(err), 3);
      this.eventEmitter({
        name: "error",
        data: "文本驱动错误" + JSON.stringify(err),
      });
    });

    userDh.on("playError", (err) => {
      // alert(err);
      // message.error("playError: " + err, 3);
      this.eventEmitter({
        name: "error",
        data: "播放错误" + JSON.stringify(err),
      });
    });

    userDh.on("videoError", (err) => {
      // alert(err);
      // message.error("videoError: " + err, 3);
      this.eventEmitter({
        name: "error",
        data: "视频资源错误" + err,
      });
    });

    userDh.on("webSocketError", (err) => {
      // message.error("webSocketError: " + err + "，请重新申请会话", 3);
      this.eventEmitter({
        name: "error",
        data: "消息错误" + err + "请重新申请会话",
      });
    });
    // 结束，更新状态
    userDh.on("renderCompleted", async (data) => {
      // this.updataStatus(data.nodeName + ":complete");
      this.eventEmitter({
        name: "renderCompleted",
        data: data,
      });
    });

    userDh.on("branchCompleted", (data) => {
      // this.updataStatus("branch_complete");
    });

    // 开始，更新状态
    userDh.on("renderStart", async (data) => {
      // this.updataStatus(data.nodeName + ":start");

      this.eventEmitter({
        name: "renderStart",
        data: data,
      });
    });

    userDh.on("textRender", (text) => {
      this.eventEmitter({
        name: "textRender",
        data: text,
      });
    });

    // 提问，更新状态
    userDh.on("renderInterrupted", async (data) => {});

    userDh.on("resources", (data) => {
      this.playData = { ...data };
      this.eventEmitter({
        data: data,
        name: "play",
      });
      this.isSynced = true;
    });

    // 提问结束，更新状态
    userDh.on("renderBack", async (data) => {});

    userDh.on("card", async (data) => {
      this.eventEmitter({
        data: data,
        name: "card",
      });
    });

    const sessionId = await userDh.init({
      display: initData.display,
      playerUrl: initData.addr,
      topic: initData.topic,
    });

    this.dh = userDh;
    this.loaded = true;
    console.log("initDH-end");
  }

  textRender(text) {
    if(this.dh) {
      this.dh.immediateDrive(text);
    } else {
      this.eventEmitter({
        name: "error",
        data: "数字人资源不存在",
      });
    }
  }

  publish2Es(event) {
    Promise.resolve().then(() => {
      this.callBack({
        event: event,
        sessionId: this.sessionId,
        to: "es",
      });
    });
  }

  updataStatus(status, title) {
    this.publish2Es({
      title: title,
      headers: {
        token: this.params["jwt"],
        "Content-type": "application/json",
      },
      session: {
        tenantId: this.params["tenantId"],
        appId: this.params["appId"],
        appKey: this.params["appKey"],
        userId: this.params["userId"],
        groupId: this.params["groupId"],
        roomId: this.params["roomId"],
        sessionId: this.params["sessionId"],
      },
      body: {
        sessionId: this.params["sessionId"],
        event: status,
        // userId: this.params["userId"],
        // event: {
        //   title: status,
        //   data: {},
        // },
      },
      receivers: [this.params["receivers"]],
    });
  }

  eventHandler(event) {
    switch (event.name) {
      case "join":
        if (!this.inited) {
          this.params = event.data;
          this.initDHResource();
          this.inited = true;
        } else if (this.isSynced) {
          this.eventEmitter({
            data: this.playData,
            name: "play",
          });
        }
        break;
      case "init":
        this.remoteInited = true;
        this.updataStatus("session_start", "command");
        break;
    }
  }

  eventEmitter(event, channel) {
    Promise.resolve().then(() => {
      this.callBack({
        to: channel || "client",
        event: event,
        sessionId: this.sessionId,
      });
    });
  }
}

export function initDhDriver() {
  return new dhDriver();
}
