import { timeStampFormat } from 't-comm/es/time/time';
import { NUMBER_CHI_MAP } from 't-comm/lib/base/number/number';

import {
  CARD_STATUS_MAP,
  DEFAULT_CARD_CUSTOM,
  CARD_ICON_FONT_MAP,
  CARD_ICON_TEXT_MAP,
  CARD_BUTTON_CLASS,
  CARD_BUTTON_MAP,
} from './utils';

import { getCurBattleSeqFromTime } from './utils-battle-seq';

import {
  getSatisfiedAndCannotInviteCardCustom,
  getSatisfiedAndCanInviteCardCustom,
} from './utils-card-signup-any';


const TIME_MAP = {
  JUMP_TO_ROOM: 30 * 60 * 1000,
  GROUPING_AND_CREATING_ROOM: 5 * 60 * 1000,
};


export function getCardCustom({
  cardState,
  canBattle,

  isSolo,
  isVirtualRoom,

  isGroupingStage,
  isVirtualReadyStage,

  curGoingBattleIndex,
  curShowingBattleIndex,

  battleList,
}: Record<string, any>) {
  let iconCustom = {
    leftIconFont: '',
    leftIconText: '',
    rightIconFont: '',
    rightIconText: '',
  };

  let buttonCustom: Record<string, any> = {};

  if (cardState === CARD_STATUS_MAP.SATISFIED_AND_CAN_NOT_INVITE) {
    buttonCustom = getSatisfiedAndCannotInviteCardCustom({
      rawBattleList: battleList,
      curShowingBattleIndex,
    });
  }

  if (cardState === CARD_STATUS_MAP.SATISFIED_AND_CAN_INVITE) {
    buttonCustom = getSatisfiedAndCanInviteCardCustom({
      rawBattleList: battleList,
      curShowingBattleIndex,
    });
  }

  if (!isSolo) {
    if ([
      CARD_STATUS_MAP.RESULT_WAITING,
      CARD_STATUS_MAP.RESULT_FAIL,
      CARD_STATUS_MAP.RESULT_WIN,
      CARD_STATUS_MAP.RESULT_SHOW_RANK,
    ].includes(cardState)) {
      iconCustom = {
        leftIconFont: '',
        leftIconText: '',
        rightIconFont: CARD_ICON_FONT_MAP.CHECK_OPPONENTS,
        rightIconText: CARD_ICON_TEXT_MAP.CHECK_OPPONENTS,
      };
    } else {
      iconCustom = {
        leftIconFont: CARD_ICON_FONT_MAP.CHECK_OPPONENTS,
        leftIconText: CARD_ICON_TEXT_MAP.CHECK_OPPONENTS,
        rightIconFont: CARD_ICON_FONT_MAP.CHECK_PLAYING_LIST,
        rightIconText: CARD_ICON_TEXT_MAP.CHECK_PLAYING_LIST,
      };
    }
  }

  if (curShowingBattleIndex > curGoingBattleIndex) {
    buttonCustom = {
      mainButton: CARD_BUTTON_MAP.WAIT_START,
      mainButtonClass: CARD_BUTTON_CLASS.INVALID,
      buttonTips: '',
    };
    if (isVirtualRoom) {
      buttonCustom.buttonTips = '开赛前半小时进入备战房准备';

      const curShowingBattle = battleList[curShowingBattleIndex] || {};
      const { start_time: startTime } = curShowingBattle;

      if (startTime * 1000 - Date.now() < TIME_MAP.JUMP_TO_ROOM
      && startTime * 1000 - Date.now() > 0) {
        buttonCustom = {
          mainButton: CARD_BUTTON_MAP.GROUPING,
          mainButtonClass: CARD_BUTTON_CLASS.PRIMARY,
          buttonTips: CARD_BUTTON_MAP.JUMP_TO_ROOM_TIP,
        };
      }
    }
  } else if (curShowingBattleIndex < curGoingBattleIndex) {
    buttonCustom = {
      mainButton: CARD_BUTTON_MAP.BATTLED_ENDED,
      mainButtonClass: CARD_BUTTON_CLASS.INVALID,
      buttonTips: '',
    };
  } else {
    if (cardState === CARD_STATUS_MAP.BATTLE_WILL_START
      || cardState === CARD_STATUS_MAP.GAME_WILL_START) {
      if (isVirtualRoom) {
        buttonCustom = {
          mainButton: CARD_BUTTON_MAP.WAIT_START,
          mainButtonClass: CARD_BUTTON_CLASS.INVALID,
          buttonTips: CARD_BUTTON_MAP.WAIT_VIRTUAL_START_TIP,
        };

        if (isGroupingStage) {
          // 分组建房阶段
          buttonCustom = {
            mainButton: CARD_BUTTON_MAP.GROUPING,
            mainButtonClass: CARD_BUTTON_CLASS.PRIMARY,
            buttonTips: CARD_BUTTON_MAP.GROUPING_TIP,
            title: '比赛已开启',
          };
        } else if (isVirtualReadyStage) {
          // 可以提前进入备战房
          buttonCustom = {
            mainButton: CARD_BUTTON_MAP.GROUPING,
            mainButtonClass: CARD_BUTTON_CLASS.PRIMARY,
            buttonTips: CARD_BUTTON_MAP.JUMP_TO_ROOM_TIP,
          };
        }
      }
    }

    if (cardState === CARD_STATUS_MAP.BATTLE_STARTED) {
      if (canBattle || isSolo) {
        // 可以出战
        buttonCustom = {
          mainButton: CARD_BUTTON_MAP.LAUNCH_GAME,
          mainButtonClass: CARD_BUTTON_CLASS.PRIMARY,
          buttonTips: CARD_BUTTON_MAP.LAUNCH_GAME_TIP,
        };
      } else {
        // 不可以出战
        buttonCustom = {
          mainButton: CARD_BUTTON_MAP.CAN_NOT_BATTLE,
          mainButtonClass: CARD_BUTTON_CLASS.INVALID,
          buttonTips: '',
        };
      }
    }

    if ([
      CARD_STATUS_MAP.BATTLE_PLAYING_JOINED,
      CARD_STATUS_MAP.BATTLE_PLAYING_NOT_JOINED,
    ].includes(cardState)) {
      if (isVirtualRoom) {
        buttonCustom = {
          mainButtonClass: CARD_BUTTON_CLASS.PRIMARY,
          mainButton: CARD_BUTTON_MAP.BATTLE_PLAYING,
        };
      }
    }
  }

  const cardCustom = {
    ...JSON.parse(JSON.stringify(DEFAULT_CARD_CUSTOM)),
    [cardState]: {
      ...(DEFAULT_CARD_CUSTOM[cardState as keyof typeof DEFAULT_CARD_CUSTOM] || {}),
      ...iconCustom,
      ...buttonCustom,
    },
  };
  console.log('cardCustom', cardCustom);
  return cardCustom;
}

function getCardState({
  curJoinStatus,
  gameResult,
  gameStatus,
  battleList,

  curBattleStatus,
  isLastBattle,

  canEnterGame,
  mineInBattle,

  isGroupingStage,

  isPlayingAndCanSignup,
  isPlayingAndNotSatisfied,
  isSatisfiedAndCanInvite,
  isSatisfiedAndCannotInvite,
}: Record<string, any>) {
  if (isPlayingAndCanSignup) {
    return CARD_STATUS_MAP.PLAYING_AND_CAN_SIGN_UP;
  }

  if (isPlayingAndNotSatisfied) {
    return CARD_STATUS_MAP.PLAYING_AND_NOT_SATISFIED;
  }
  if (isSatisfiedAndCanInvite) {
    return CARD_STATUS_MAP.SATISFIED_AND_CAN_INVITE;
  }
  if (isSatisfiedAndCannotInvite) {
    return CARD_STATUS_MAP.SATISFIED_AND_CAN_NOT_INVITE;
  }

  const cardState = '';
  if (curJoinStatus == 2) {
    return CARD_STATUS_MAP.NOT_SIGN_UP;
  }

  if (gameResult == 100) {
    return CARD_STATUS_MAP.RESULT_WIN;
  }
  if (gameResult == 200) {
    return CARD_STATUS_MAP.RESULT_FAIL;
  }

  if (gameStatus <= 10) {
    return CARD_STATUS_MAP.GAME_WILL_START;
  }
  if (battleList.length && curBattleStatus <= 10) {
    return CARD_STATUS_MAP.BATTLE_WILL_START;
  }

  if (curBattleStatus == 100) {
    return CARD_STATUS_MAP.BATTLE_WILL_START;
  }

  if (curBattleStatus == 200) {
    if (canEnterGame == 1) {
      return CARD_STATUS_MAP.BATTLE_STARTED;
    }

    // 虚拟房间类型，battleStatus 进入到200，Date.now() + 5分钟 < cutBattle.startTime
    // 为分组建房阶段，否则要么可进入游戏，要么本场未出战（仍可以跳到虚拟房间）
    if (isGroupingStage) {
      return CARD_STATUS_MAP.BATTLE_WILL_START;
    }

    if (mineInBattle) {
      return CARD_STATUS_MAP.BATTLE_PLAYING_JOINED;
    }
    return CARD_STATUS_MAP.BATTLE_PLAYING_NOT_JOINED;
  }

  if (curBattleStatus == 300) {
    if (gameResult == 300 || (!gameResult && isLastBattle)) {
      return CARD_STATUS_MAP.RESULT_WAITING;
    }

    if (mineInBattle) {
      return CARD_STATUS_MAP.BATTLE_PLAYING_JOINED;
    }
    return CARD_STATUS_MAP.BATTLE_PLAYING_NOT_JOINED;
  }

  // 未开放报名
  if (curJoinStatus == 7) {
    return CARD_STATUS_MAP.NOT_SIGN_UP;
  }
  return cardState;
}

function parseBattleList(battleList: Array<any>, curBattleSeq: number) {
  const newBattleList = battleList.map((item) => {
    const {
      start_time: startTime,
      battle_start_remain: remain = 0,
      battle_seq: seq,
      battle_id: battleId,
    } = item;

    let fixedTime = startTime * 1000;
    if (remain) {
      fixedTime = Date.now() + remain * 1000;
    }

    return {
      title: `第${NUMBER_CHI_MAP[seq as keyof typeof  NUMBER_CHI_MAP]}场`,
      time: fixedTime,
      timeDesc: timeStampFormat(fixedTime, 'MM-dd hh:mm'),
      battleId,
    };
  });


  const battleScoreList = battleList.map((item, index) => {
    const {
      battle_seq: seq = 1,
      battle_status: curBattleStatus = 0,
      score = 0,
    } = item;

    let realScore = score;
    if (!score) {
      if (curBattleSeq < index + 1) {
        realScore = '-';
      } else if (curBattleSeq == index + 1) {
        if (curBattleStatus <= 100) {
          realScore = '-';
        } else {
          realScore = '0';
        }
      }
    }


    return {
      title: `第${NUMBER_CHI_MAP[seq as keyof typeof  NUMBER_CHI_MAP]}场`,
      scoreOrRank: realScore,
    };
  });


  return {
    newBattleList,
    battleScoreList,
  };
}


export function parseBattleInfo(...args: [
  { info: Record<string, any>;
    curJoinStatus?: number;
    mineInBattle?: boolean;

    teamInfo?: Record<string, any>;
    isPlayingAndCanSignup?: boolean;
    isPlayingAndNotSatisfied?: boolean;
    isSatisfiedAndCanInvite?: boolean;
    isSatisfiedAndCannotInvite?: boolean;

    childInfo?: Record<string, any>;
  }
] | [
    info: Record<string, any>,
    curJoinStatus?: number,
    mineInBattle?: boolean,

    teamInfo?: Record<string, any>,
]) {
  let info: Record<string, any>;
  let curJoinStatus = 0;
  let mineInBattle = true;

  let teamInfo: Record<string, any>;
  let isPlayingAndCanSignup = false;
  let isPlayingAndNotSatisfied = false;
  let isSatisfiedAndCanInvite = false;
  let isSatisfiedAndCannotInvite = false;

  let childInfo: Record<string, any> = [];

  if (args.length === 1 && args[0].info) {
    info = args[0].info;
    curJoinStatus = args[0].curJoinStatus ?? 0;
    mineInBattle = args[0].mineInBattle ?? true;

    teamInfo = args[0].teamInfo ?? {};
    isPlayingAndCanSignup = args[0].isPlayingAndCanSignup;
    isPlayingAndNotSatisfied = args[0].isPlayingAndNotSatisfied;
    isSatisfiedAndCanInvite = args[0].isSatisfiedAndCanInvite;
    isSatisfiedAndCannotInvite = args[0].isSatisfiedAndCannotInvite;


    childInfo = args[0].childInfo ?? {};
  } else {
    info = args[0];
    curJoinStatus = args[1] ?? 0;
    mineInBattle = args[2] ?? true;

    teamInfo = args[3] ?? {};
  }

  const defaultCurBattleSeq = getCurBattleSeqFromTime(childInfo?.match_rule_cfg?.pubg_rule_cfg?.round_time_cfg || []);

  const {
    battle_list: battleList = [],
    battle_user_list: battleUserList = [],
    cur_battle_seq: curBattleSeq = defaultCurBattleSeq,

    game_status: gameStatus,
    game_result: gameResult,
    game_rank: gameRank = '-',

    start_battle_type: startBattleType,
    game_start_remain: gameStartRemain = 0,
    join_type: joinType = 1,

    use_match: useMatch,
  } = info;

  const curBattleInfo = battleList[curBattleSeq - 1] || {};

  // 对局状态 10未开始 100即将开始 200进行中 300已结束
  const {
    battle_status: curBattleStatus = 0,
    can_enter_game: canEnterGame,
    can_battle: canBattle,
    start_time: curBattleStartTime,
    enter_game_remain: enterGameRemain = 0,
  } = curBattleInfo;
  const isLastBattle = curBattleSeq == battleList.length;
  const isSolo = joinType == 2;
  const isVirtualRoom = useMatch == 3;

  const isGroupingStage = isVirtualRoom
    && Date.now() - curBattleStartTime * 1000 < TIME_MAP.GROUPING_AND_CREATING_ROOM
    && Date.now() - curBattleStartTime * 1000 > 0;
  const isVirtualReadyStage = isVirtualRoom
    && curBattleStartTime * 1000 - Date.now() < TIME_MAP.JUMP_TO_ROOM
    && curBattleStartTime * 1000 - Date.now() > 0;

  const cardState = getCardState({
    curJoinStatus,
    gameResult,
    gameStatus,
    battleList,

    curBattleStatus,
    isLastBattle,

    canEnterGame,
    mineInBattle,
    isGroupingStage,

    isPlayingAndCanSignup,
    isPlayingAndNotSatisfied,
    isSatisfiedAndCanInvite,
    isSatisfiedAndCannotInvite,
  });

  const {
    newBattleList,
    battleScoreList,
  } = parseBattleList(battleList, curBattleSeq);

  return {
    rawBattleList: battleList,
    battleList: newBattleList,
    curGoingBattleIndex: curBattleSeq - 1,
    curShowingBattleIndex: curBattleSeq - 1,
    isManualStart: startBattleType == 2,
    gameStartCountdown: gameStartRemain * 1000,

    cardState,
    battleScoreList,
    gameRank,
    joinRoomTime: enterGameRemain * 1000 + Date.now(),
    curBattleInfo,

    isVirtualRoom,
    isSolo,
    isGroupingStage,
    isVirtualReadyStage,

    canBattle,

    memberList: (teamInfo?.members || battleUserList || []).map((item: Record<string, any>) => ({
      avatar: item.head,
      name: item.nick,
      nick: item.nick,
      isLeader: item.teamrole == 1 || item.is_cap,
    })),

    minSignNum: childInfo?.match_rule_cfg?.sign_team_min_mem || info.sign_team_min_mem,
  };
}


export function parseMemInfo(memInfo: Record<string, any> = {}) {
  const { game_info: gameInfo = {} } = memInfo;

  return {
    roleName: gameInfo.roleName || '',
    device: gameInfo.device == 2 ? '' : 'iOS',
    roleId: gameInfo.roleid,
  };
}


export function parseChildInfo(info: Record<string, any> = {}) {
  if (!info.join_end) {
    return {
      signUpCountdown: 0,
    };
  }

  const signUpCountdown = info.join_end - parseInt(`${Date.now() / 1000}`, 10);

  return {
    signUpCountdown: signUpCountdown * 1000,
  };
}
