import { launchGPGameRoom } from 't-comm/lib/launch-game/game-gp';
import { LAUNCH_GP_SOURCE_MAP } from 't-comm/lib/launch-game/helper';

import { APP_ID_MAP } from './config-gp';


const DEFAULT_EXTRA_QQ_MP_URL = '&autolaunch=1';


export const launchGPGameRoomInUni = ({
  roomId,
  roomPwd,
  source = LAUNCH_GP_SOURCE_MAP.NORMAL,

  extraQQMPUrl = DEFAULT_EXTRA_QQ_MP_URL,
  env = {},

  message,
  type,

  useGPHelperSchemePrefix = false,
  useTrialSchemePrefix = false,
  justLaunchGame = false,
}: {
  roomId: string;
  roomPwd: string;
  source?: string | number;

  extraQQMPUrl?: string;
  env?: Record<string, any>;

  message?: string;
  type?: number;

  useGPHelperSchemePrefix?: boolean;
  useTrialSchemePrefix?: boolean;
  justLaunchGame?: boolean;
}) => {
  let promise: Promise<any> = Promise.resolve(1);

  // #ifdef H5
  promise = launchGPGameRoom({
    roomId,
    roomPwd,
    source,

    env,

    useGPHelperSchemePrefix,
    useTrialSchemePrefix,
    justLaunchGame,
  });
  // #endif

  // #ifdef MP-WEIXIN
  if (typeof wx !== 'undefined' && typeof wx?.navigateToMiniProgram === 'function') {
    promise = launchGPInMP({
      roomId,
      roomPwd,
      message,
      type,
    });
  }
  // #endif

  // #ifdef MP-QQ

  if (typeof qq !== 'undefined' && typeof qq.openUrl === 'function') {
    promise = launchGPInMpQQ({
      roomId,
      roomPwd,
      message,
      extraQQMPUrl,
    });
  }
  // #endif

  return promise;
};


export function launchGPInMP({
  type = 1,
  message = '',

  currentMemberCount,
  maxMemberCount,

  roomId = '',
  roomPwd = '',
}: {
  message?: string;
  type?: number;

  currentMemberCount?: number;
  maxMemberCount?: number;

  roomId?: string;
  roomPwd?: string;
}) {
  let mpMessage = JSON.stringify({
    game_roomid: roomId,
    game_roompw: roomPwd,
  });
  if (message) {
    mpMessage = message;
  }

  console.info('[mpMessage]', mpMessage);
  console.info('[type]', type);

  return new Promise((resolve, reject) => {
    wx.navigateToMiniProgram({
      appId: 'wx4bfd324d7e80de2e',
      path: 'packageGame/pages/launchgamecenter/index',
      extraData: {
        appId: 'wxc4c0253df149f02d',
        passData: JSON.stringify({
          type: type || 1,
          current_member_count: currentMemberCount,
          max_member_count: maxMemberCount,
          message: mpMessage,
        }),
      },
      success(res: any) {
        resolve(res);
      },
      fail(err: any) {
        reject(err);
      },
    });
  });
}

export function launchGPInMpQQ({
  message = '',

  roomId = '',
  roomPwd = '',
  extraQQMPUrl = DEFAULT_EXTRA_QQ_MP_URL,
}: {
  message?: string;
  roomId?: string;
  roomPwd?: string;
  extraQQMPUrl?: string
}) {
  let appParameter = encodeURIComponent(JSON.stringify({
    game_roomid: roomId,
    game_roompw: roomPwd,
  }));

  if (message) {
    appParameter = message;
  }

  const url = `https://speed.gamecenter.qq.com/pushgame/v1/detail?appid=1106467070&_wv=2164260896&_wwv=448&ADTAG=hpjyminiapp&gamedata=${appParameter}${extraQQMPUrl}`;

  console.log('[launchGPInMpQQ] url: ', url);


  // @ts-ignore
  qq.openUrl({
    url,
  });

  return Promise.resolve(1);
}


export function launchEmbeddedMiniProgram({
  roomId,
  roomPwd,
  source = LAUNCH_GP_SOURCE_MAP.NORMAL,

  thirdPage = true,
  justLaunchGame = false,
}: {
  roomId?: string;
  roomPwd?: string;
  source?: number;

  thirdPage?: boolean;
  justLaunchGame?: boolean;
}) {
  return new Promise((resolve, reject) => {
    let appId = APP_ID_MAP.GP_GAME_WX;
    // #ifdef MP-QQ
    appId = APP_ID_MAP.GP_GAME_QQ;
    // #endif


    const messageStr = encodeURIComponent(JSON.stringify({
      source,
      game_roomid: `${roomId}`,
      game_roompw: `${roomPwd}`,
    }));
    console.info('[launch game] messageStr', messageStr);

    const getLaunchPath = () => {
      if (!thirdPage) {
        return `convert-cross/views/launch-game/launch-game?roomId=${roomId}&roomPwd=${roomPwd}`;
      }
      if (justLaunchGame) {
        return 'pages/launch/index';
      }
      return `pages/launch/index?message=${messageStr}`;
    };

    const data = {
      appId,
      path: getLaunchPath(),
      extraData: {
        roomId,
        roomPwd,
      },
      envVersion: 'release' as const,
      success(res: any) {
        resolve(res);
      },
      fail(err: any) {
        reject(err);
      },
    };
    if (uni.openEmbeddedMiniProgram) {
      uni.openEmbeddedMiniProgram(data);
    } else {
      uni.navigateToMiniProgram(data);
    }
  });
}
