import { getCurrentUser } from "@/api/tenant-user-controller";
import { getTencentSig, getTencentTRTCSig, getWFToken } from "@/api/bcxin/identify";
import tim from "@/tim";
import store from "@/store/index";
import TIM from "tim-js-sdk";
import Config from "@/config";
import wfc from "@/wfc/client/wfc";
import { setItem } from "@/ui/util/storageHelper";
import { getConfig } from "@/utils/index";
import { isElectron } from "@/platform";
import WFStore from "@/store.js";

async function onReadyStateUpdate({ name }) {
  console.log(name);
  const isSDKReady = name === TIM.EVENT.SDK_READY;
  store.commit("toggleIsSDKReady", isSDKReady);
  if (isSDKReady) {
    tim
      .getMyProfile()
      .then(({ data }) => {
        store.commit("updateCurrentUserProfile", data);
      })
      .catch((error) => {
        console.log(error);
        store.commit("showMessage", {
          type: "error",
          message: error.message,
        });
      });
    // 登录trtc calling
    // trtcCalling.login({
    //   sdkAppID: Number(process.env.VUE_APP_SDK_IM_ID),
    //   userID,
    //   userSig,
    // });
  }
}

function onKickOut(event) {
  store.commit("showMessage", {
    message: `${kickedOutReason(event.data.type)}被踢出，请重新登录。`,
    type: "error",
  });
  store.commit("toggleIsLogin", false);
  store.commit("reset");
}

function kickedOutReason(type) {
  switch (type) {
    case this.TIM.TYPES.KICKED_OUT_MULT_ACCOUNT:
      return "由于多实例登录";
    case this.TIM.TYPES.KICKED_OUT_MULT_DEVICE:
      return "由于多设备登录";
    case this.TIM.TYPES.KICKED_OUT_USERSIG_EXPIRED:
      return "由于 userSig 过期";
    default:
      return "";
  }
}

function onError({ data }) {
  if (data.message !== "Network Error") {
    store.commit("showMessage", {
      message: data.message,
      type: "error",
    });
  }
}

function onReceiveMessage({ data: messageList }) {
  // this.playNotifyAudio();
  // this.handleAutoReply(messageList);
  // this.handleVideoMessage(messageList);
  // this.handleQuitGroupTip(messageList);
  console.log("pushCurrentMessageList", messageList);
  store.commit("pushCurrentMessageList", messageList);
}

function onUpdateConversationList(event) {
  console.log("onUpdateConversationList", event);
  const { data: converstationList } = event;
  const sortList = converstationList.filter((converstation) => {
    return converstation.lastMessage.lastTime > 0;
  });
  console.log("onUpdateConversationList", sortList);
  store.commit("updateConversationList", sortList);
}

function onUpdateGroupList(event) {
  store.commit("updateGroupList", event.data);
}

function onTotalUnreadMessageCountUpdated(event) {
  console.log(event.data); // 当前单聊和群聊会话的未读总数
  store.commit("updateTotalUnreadMessageCount", event.data);
}

/**
 * * 根据用户信息获取腾讯SigId
 * * 根据SigId和UserId登录TIM
 */
export async function getUserInfo() {
  return getCurrentUser().then(async (response) => {
    return Promise.resolve(response);
  });
}

export async function LoginTIM(response) {
  const TRTC_SIG = await getTencentTRTCSig({
    name: response.name,
    cid: response.tencentUserId,
  });
  console.log("TRTC_SIG===", TRTC_SIG);
  const userID = response.tencentUserId;
  const data = await getTencentSig({
    name: response.name,
    mobilePhone: response.tencentUserId,
  });
  const userSig = data.data;
  console.log("userSig===", userSig);
  let promise = tim.login({ userID, userSig });
  promise
    .then(function (imResponse) {
      console.log(imResponse.data); // 登录成功
      store.commit("toggleIsLogin", true);
      store.commit("startComputeCurrent");
      store.commit({
        type: "GET_USER_INFO",
        userID,
        userSig,
        sdkAppID: Number(process.env.VUE_APP_SDK_IM_ID),
      });
      // 登录成功后会触发 SDK_READY 事件，该事件触发后，可正常使用 SDK 接口
      tim.on(TIM.EVENT.SDK_READY, ({ name }) => onReadyStateUpdate({ name }));
      // SDK NOT READY
      tim.on(TIM.EVENT.SDK_NOT_READY, ({ name }) => onReadyStateUpdate({ name }));
      // 被踢出
      tim.on(TIM.EVENT.KICKED_OUT, onKickOut);
      // SDK内部出错
      tim.on(TIM.EVENT.ERROR, onError);
      // 收到新消息
      tim.on(TIM.EVENT.MESSAGE_RECEIVED, onReceiveMessage);
      // 会话列表更新
      tim.on(TIM.EVENT.CONVERSATION_LIST_UPDATED, onUpdateConversationList);
      // 群组列表更新
      tim.on(TIM.EVENT.GROUP_LIST_UPDATED, onUpdateGroupList);
      // 会话未读总数更新，event.data 是当前单聊和群聊会话的未读总数
      tim.on(TIM.EVENT.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED, onTotalUnreadMessageCountUpdated);
      if (imResponse.data.repeatLogin === true) {
        // 标识帐号已登录，本次登录操作为重复登录。v2.5.1 起支持
        console.log(imResponse.data.errorInfo);
      }
    })
    .catch(function (imError) {
      console.warn("login error:", imError); // 登录失败的相关信息
      store.commit("showMessage", { type: "error", message: imError });
    });
}

/**
 * * 野火登录
 */
export async function loginWF(response) {
  let href = window.location.href;
  let path = href.substring(href.indexOf("#") + 1);
  console.log("init", href, path);
  // 判断是否是主窗口，请根据实际情况进行调整
  if (path === "/" /*login*/ || path.startsWith("/dispatch") || href.indexOf("#") === -1) {
    console.log("init wfc");
    if (isElectron()) {
      wfc.init();
      // 双网环境配置
      //     // 设置网络策略
      //     wfc.setBackupAddressStrategy(0)
      //     // 设置备选网络
      //     wfc.setBackupAddress('192.168.10.11', 80)
    } else {
      wfc.init();
      // 双网环境配置
      // 可以根据访问网页的地址，配置是否切换备选网络策略
      // 比如公网，通过域名访问，采用默认的主网络；内网，通过ip访问，使用备选网络
      // 需要在wfc.connect之前调用
      // if (new URL(window.origin).host.startsWith('192.168.2.169')) {
      //     // 设置备选网络不走WSS
      //     Config.USE_WSS = false;
      //     // 设置网络策略
      //     wfc.setBackupAddressStrategy(2)
      //     // 设置备选网络
      //     wfc.setBackupAddress('192.168.10.11', 80)
      // }
    }
    WFStore.init(true);
  } else {
    console.error(
      "not home window, not init wfc, 如果此窗口就是主窗口或者应用只有一个窗口，可能会导致功能不正常，请更新上面的主窗口判断逻辑"
    );
    if (isElectron()) {
      wfc.attach();
    }
    let subWindowLoadDataOptions = {
      loadFavGroupList: true,
      loadChannelList: true,
      loadFriendList: true,
      loadFavContactList: true,
      loadFriendRequestList: true,
      loadDefaultConversationList: true,
    };
    // TODO 优化，有的窗口并不需要store，或者不需要加载所有默认数据
    WFStore.init(false, subWindowLoadDataOptions);
  }
  const { tencentUserId, name, telephone /*, idCardNo*/ /*, idNumber*/ } = response;
  getWFToken({
    platform: Config.getWFCPlatform(),
    clientId: wfc.getClientId(),
    userId: tencentUserId,
    idNumber: "66",
    displayName: name,
    mobile: telephone,
  }).then(async (res) => {
    console.log("wft token", res);
    const { authToken, token } = res;
    // !!!以下几步操作一定要有!!!
    wfc.connect(tencentUserId, token);
    setItem("authToken-" + new URL(Config.APP_SERVER).host, authToken);
    setItem("wfcUserId", tencentUserId);
    setItem("wfcToken", token);
  });
}

export default async function () {
  const client = await getConfig("dispatchClient");
  console.log("client: ", client);
  store.commit("SET_DISPATCH_CLIENT", client);
  localStorage.setItem("dispatchClient", client.toString());
  if (client === "tencent") {
    const response = await getUserInfo();
    await LoginTIM(response);
    return response;
  } else if (client === "wildfire") {
    const response = await getUserInfo();
    await loginWF(response);
    return response;
  }
}
