import { WEBSOCKET_FOR_AUDIO } from "@/constants/constants";
import { useWebSocket } from "@/setups/useWebSocket";
import { store } from "@/store/store";
import { watch } from "vue";

function onAudioAnswer(event: MessageEvent<string>) {
  let res: {
    eventType: string;
    isSuccess: boolean;
    errorMessage: string;
    data: { order: number; fileUrl: string; transferFileType: string };
  };
  try {
    res = JSON.parse(event.data).content;
  } catch (error) {
    logger({
      cnl: ["server"],
      act: "websocket.onmessage",
      dtl: "JSON.parse出错",
      possibleError: error,
    });
    return;
  }
  if (!res) {
    logger({
      cnl: ["server"],
      act: "onAudioAnswer",
      dtl: "event.data.content is null, probably a connected reckon from server",
      ext: { event: JSON.stringify(event) },
    });
    return;
  }
  if (res.eventType && res.eventType !== "HEARTBEAT" && !res.isSuccess) {
    $message.error(res.errorMessage, { duration: 10, closable: true });
    logger({
      lvl: "debug",
      cnl: ["server"],
      act: "onAudioAnswer",
      dtl: "error from server",
      stk: res.errorMessage,
    });
    return;
  }
  switch (res.eventType) {
    case "HEARTBEAT":
      logger({
        cnl: ["server"],
        lvl: "debug",
        act: "ws heartbeat response from server",
      });
      break;
    case "SCAN_QR_CODE":
      logger({ cnl: ["server"], act: "二维码被扫描" });
      store.setQuestionQrCodeScanned({ order: res.data.order });
      break;
    case "GET_FILE_ANSWER":
      logger({ cnl: ["server"], act: "获得音频/图片地址" });
      store.setQuestionFileAnswerUrl(res.data);
      break;
    case "SYSTEM_ERROR":
      logger({
        cnl: ["server"],
        act: "ws get error",
        ejn: JSON.stringify(res),
      });
      break;
  }
}

// let wxSocketLock = false;
export function useWXSocket() {
  const { startWS } = useWebSocket();

  watch(
    () => store.exam.WEIXIN_ANSWER_ENABLED,
    () => {
      if (!store.exam.WEIXIN_ANSWER_ENABLED) return;

      // console.log("start ws");
      logger({ cnl: ["server"], act: "useWXSocket" });

      // if (wxSocketLock) return;
      // wxSocketLock = true;

      // init data
      store.exam.questionAnswerFileUrl = [];
      startWS(
        WEBSOCKET_FOR_AUDIO +
          `?key=${store.user.key}&token=${store.user.token}`,
        onAudioAnswer,
        "微信小程序作答socket"
      );
    },
    { immediate: true }
  );
}
