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


// 对局状态 10未开始 100即将开始 200进行中 300已结束
// enum BattleStatus {
//   UNKNOWN = 0,
//   NOT_START = 10,
//   WILL_START = 100,
//   PLAYING = 200,
//   END = 300,
//   DESTROYED = 400,
// }

//  0未开始，100已开打进行中，200已结束
enum ScheState {
  NOT_START = 0,
  ING = 100,
  END = 200,
}

const getBattleIndex = (battle: Record<string, any>) => {
  console.log('battle?.battle_id', battle?.battle_id);
  const index = (`${battle?.battle_id}` || '').split('_')?.[4];
  return index;
};


const getMyScore = (myTeamId: string, schScore: Record<string, any> = {}) => {
  const { teama_id: teamAId, teamb_id: teamBId, teama_score: teamAScore, teamb_score: teamBScore } = schScore;
  if (myTeamId === teamAId) {
    return teamAScore || 0;
  }
  if (myTeamId === teamBId) {
    return teamBScore || 0;
  }
  return;
};

function getBattleScoreList({
  battleList,
  myTeamIdOrUId = '',
}: {
  battleList: Array<Record<string, any>>;
  myTeamIdOrUId?: string;
}) {
  return battleList.map((item: any, index: number) => ({
    scoreOrRank: getMyScore(myTeamIdOrUId, item.schScore) || 0,
    title: `第${getBattleIndex(item) ?? (index + 1)}局`,

    isWin: item.battle_result === 100,
    isFail: item.battle_result === 200,
    isTie: false,
    isPending: item.battle_result === 300,
  }));
}

function getCycleMatchCardState({
  gameResult,
}: {
  battleList?: Array<Record<string, any>>;
  gameResult?: number;
}) {
  // 比赛结果  100晋级 200淘汰 300结算中
  if (gameResult == 100) {
    return CARD_STATUS_MAP.RESULT_WIN;
  }
  if (gameResult == 200) {
    return CARD_STATUS_MAP.RESULT_FAIL;
  }
  if (gameResult == 300) {
    return CARD_STATUS_MAP.RESULT_WAITING;
  }

  return CARD_STATUS_MAP.CYCLE_MATCH;
}

export function parseCycleMatchCard({
  gameResult,
  gameRank,

  battleList = [],
  curShowingBattleIndex,

  matchingStatus,
  matchingCountdown,

  actEndTime,
  actStartTime,

  myTeamIdOrUId = '',
}: {
  gameResult?: number;
  gameRank?: number;

  battleList: Array<Record<string, any>>;
  curShowingBattleIndex: number;

  matchingStatus?: MatchingStatus;
  matchingCountdown?: number;

  actEndTime?: number;
  actStartTime?: number;

  myTeamIdOrUId?: string;
}) {
  console.log('battleList', battleList);
  const cardState = getCycleMatchCardState({
    gameResult,
  });

  const curGoingBattleIndex = Math.max(battleList.length - 1, 0);

  const cardCustom = getCycleMatchCardCustom({
    battleList,
    curGoingBattleIndex,
    curShowingBattleIndex,

    matchingStatus,
    matchingCountdown,

    actEndTime,
    actStartTime,

    myTeamIdOrUId,
  });


  let parsedBattleList = battleList.map((item, index) => {
    const realBattleSeq = getBattleIndex(item) ?? (index + 1);
    return {
      ...item,
      title: `第${realBattleSeq}局`,
      realBattleSeq,
    };
  });


  const noBattle = !battleList.length;

  if (noBattle) {
    parsedBattleList = [{
      title: '第1局',
      realBattleSeq: '1',
    }];
  }

  return {
    cardState,
    curGoingBattleIndex: noBattle ? 0 : curGoingBattleIndex,
    battleList: parsedBattleList,
    cardCustom: {
      [cardState]: {
        ...cardCustom,
      },
    },
    curBattleInfo: battleList[battleList.length - 1] || {},
    gameRank,
    battleScoreList: getBattleScoreList({
      battleList,
      myTeamIdOrUId,
    }),
  };
}


export function getCycleMatchCardCustom({
  battleList,
  curGoingBattleIndex,
  curShowingBattleIndex,

  matchingStatus,
  matchingCountdown = 0,

  actEndTime,
  actStartTime,

  myTeamIdOrUId = '',
}: {
  battleList: Array<Record<string, any>>;
  curGoingBattleIndex: number;
  curShowingBattleIndex: number;

  matchingStatus?: MatchingStatus;
  matchingCountdown?: number;

  actEndTime?: number;
  actStartTime?: number;

  myTeamIdOrUId?: string;
}) {
  const iconCustom = {
    leftIconFont: '',
    leftIconText: '',
    rightIconFont: CARD_ICON_FONT_MAP.CHECK_RANK_LIST,
    rightIconText: CARD_ICON_TEXT_MAP.CHECK_RANK_LIST,
  };
  const now = parseInt(`${Date.now() / 1000}`, 10);
  console.log('curShowingBattleIndex', curShowingBattleIndex, curGoingBattleIndex);

  const getMainType = (info: Record<string, string | boolean | number>) => ({
    matchingTitle: '',
    matchingCountdown: 0,
    showMatchingResult: false,
    showBattleResultList: false,
    showBattleScoreList: false,
    isMatchingFail: false,
    isMatchingSuccess: false,
    ...info,
  });

  if (actStartTime && actStartTime > now) {
    // 匹配时间未到
    // 显示待匹配按钮、匹配未开启
    return {
      ...getMainType({
        matchingTitle: '匹配未开启',
        matchingCountdown: actStartTime ? Math.max(actStartTime - now, 0) * 1000 : 0,
      }),

      mainButton: CARD_BUTTON_MAP.WAIT_MATCHING,
      mainButtonClass: CARD_BUTTON_CLASS.INVALID,
      buttonTips: '',
      ...iconCustom,
      memo: 'actStartTime > now',
    };
  }

  if (actEndTime && actEndTime < now) {
    return {
      ...getMainType({ showBattleResultList: true }),
      battleScoreList: getBattleScoreList({
        battleList,
        myTeamIdOrUId,
      }),

      mainButton: CARD_BUTTON_MAP.CHECK_DATA,
      mainButtonClass: CARD_BUTTON_CLASS.PRIMARY,

      leftIconFont: '',
      leftIconText: '',
      rightIconFont: '',
      rightIconText: '',
      memo: 'actEndTime < now',
    };
  }
  if (curShowingBattleIndex > curGoingBattleIndex) {
    // 显示待匹配按钮、匹配未开启
    return {
      ...getMainType({
        matchingTitle: '匹配未开启',
        matchingCountdown: 0,
      }),

      mainButton: CARD_BUTTON_MAP.WAIT_MATCHING,
      mainButtonClass: CARD_BUTTON_CLASS.INVALID,
      buttonTips: '',
      ...iconCustom,
      memo: 'check next battle',
    };
  }

  if (curShowingBattleIndex < curGoingBattleIndex) {
    // 显示匹配已结束按钮、积分排名

    console.log('myTeamIdOrUId', myTeamIdOrUId);
    const battleScoreList = getBattleScoreList({
      battleList,
      myTeamIdOrUId,
    });
    return {
      ...getMainType({ showBattleScoreList: true }),

      battleScoreList,

      mainButton: CARD_BUTTON_MAP.MATCHING_END,
      mainButtonClass: CARD_BUTTON_CLASS.INVALID,
      buttonTips: '',
      ...iconCustom,
      memo: 'check last battle',
    };
  }

  const lastBattle = battleList[battleList.length - 1];

  console.log('lastBattle', lastBattle);

  // 匹配失败
  if (matchingStatus === MatchingStatus.FAILED) {
    return {
      ...getMainType({
        showMatchingResult: true,
        isMatchingFail: true,
      }),

      mainButton: CARD_BUTTON_MAP.CONTINUE_MATCHING,
      mainButtonClass: CARD_BUTTON_CLASS.PRIMARY,
      buttonTips: '',
      ...iconCustom,
      memo: 'match status is FAILED',
    };
  }


  // 比赛已结束
  if (lastBattle && lastBattle.scheState === ScheState.END && matchingStatus !== MatchingStatus.ON_GOING
    && actEndTime && actEndTime > now
  ) {
    return {
      ...getMainType({
        matchingTitle: '匹配已开启',
        matchingCountdown: actEndTime ? Math.max(actEndTime - now, 0) * 1000 : 0,
      }),

      mainButton: CARD_BUTTON_MAP.START_MATCHING,
      mainButtonClass: CARD_BUTTON_CLASS.PRIMARY,
      buttonTips: '',
      ...iconCustom,
      memo: 'last battle is end & act not end',
    };
  }

  // 匹配未开启
  if (matchingStatus === MatchingStatus.UNKNOWN) {
    return {
      ...getMainType({
        matchingTitle: '匹配未开启',
        matchingCountdown: 0,
      }),

      mainButton: CARD_BUTTON_MAP.WAIT_MATCHING,
      mainButtonClass: CARD_BUTTON_CLASS.INVALID,
      buttonTips: '',
      ...iconCustom,
      memo: 'match status is UNKNOWN',
    };
  }

  // 开始匹配
  if (matchingStatus === MatchingStatus.UN_JOIN) {
    return {
      ...getMainType({
        matchingTitle: '匹配已开启',
        matchingCountdown: actEndTime ? Math.max(actEndTime - now, 0) * 1000 : 0,
      }),

      mainButton: CARD_BUTTON_MAP.START_MATCHING,
      mainButtonClass: CARD_BUTTON_CLASS.PRIMARY,
      buttonTips: '',
      ...iconCustom,
      memo: 'match status is UN_JOIN',
    };
  }

  // 匹配中
  if (matchingStatus === MatchingStatus.ON_GOING) {
    return {
      ...getMainType({
        matchingTitle: '匹配已开启',
        matchingCountdown: matchingCountdown * 1000,
      }),

      mainButton: CARD_BUTTON_MAP.MATCHING,
      mainButtonClass: CARD_BUTTON_CLASS.PRIMARY,
      buttonTips: '',
      ...iconCustom,
      memo: 'match status is ON_GOING',
    };
  }

  // 匹配成功
  if (matchingStatus === MatchingStatus.SUCCESS) {
    let buttonInfo: Record<string, string | number> = {
      mainButton: CARD_BUTTON_MAP.BATTLE_PLAYING,
      mainButtonClass: CARD_BUTTON_CLASS.INVALID,
      buttonTips: '',
    };

    if (lastBattle?.can_enter_game) {
      buttonInfo = {
        mainButton: CARD_BUTTON_MAP.LAUNCH_GAME,
        mainButtonClass: CARD_BUTTON_CLASS.PRIMARY,
        buttonCountdown: (lastBattle.enter_game_remain || 0) * 1000 + Date.now(),
        buttonTips: '',
      };
    }

    return {
      ...getMainType({
        showMatchingResult: true,
        isMatchingSuccess: true,
      }),

      ...buttonInfo,
      ...iconCustom,
      memo: 'match status is SUCCESS',
    };
  }


  if (!lastBattle && !matchingStatus) {
    return {
      ...getMainType({
        matchingTitle: '匹配已开启',
        matchingCountdown: actEndTime ? Math.max(actEndTime - now, 0) * 1000 : 0,
      }),

      mainButton: CARD_BUTTON_MAP.START_MATCHING,
      mainButtonClass: CARD_BUTTON_CLASS.PRIMARY,
      buttonTips: '',
      ...iconCustom,
      memo: 'not battle && not match status',
    };
  }

  return {

  };
}
