import { SPECIAL_TEAM_STATE_MAP, SPECIAL_TEAM_ID_MAP } from '../config';

/**
 * 1. 若 team_id = "999" 表示 “弃权”
   2. both_team_set < 3，team_id="" 表示“待定”
   3. both_team_set = 3	team_id = ""  表示 “轮空”
   4. both_team_set = 4 也表示双方待定
 */

// 获取队伍信息
export function getTeamInfo({
  nodeItem,
  pos,
  isPreview,
  teamMap,
}: {
  nodeItem: Record<string, any>,
  pos: string,
  isPreview: number,
  teamMap: Record<string, any>,
}) {
  const schScore = nodeItem?.sch_score || {};
  const bothTeamSet = nodeItem?.sch_dantao?.both_team_set || 0;
  const teamid = schScore[`team${pos}_id`];

  const teamInfo = {
    ...(teamMap[teamid] || {}),
  };

  // 根据 teamid 和 bothTeamSet，联合判断状态是轮空还是待定
  if (!teamid) {
    if (bothTeamSet == 4 || bothTeamSet < 3) {
      teamInfo.teamname = SPECIAL_TEAM_STATE_MAP.DAI_DING.name;
      teamInfo.teamavatar = SPECIAL_TEAM_STATE_MAP.DAI_DING.avatar;
    } else {
      teamInfo.teamname = SPECIAL_TEAM_STATE_MAP.LUN_KONG.name;
      teamInfo.teamavatar = SPECIAL_TEAM_STATE_MAP.LUN_KONG.avatar;
    }
  } else if (teamid == 999) {
    teamInfo.teamname = SPECIAL_TEAM_STATE_MAP.QUIT_RIGHT.name;
    teamInfo.teamavatar = SPECIAL_TEAM_STATE_MAP.QUIT_RIGHT.avatar;
  } else {
    teamInfo.score = schScore[`team${pos}_score`] || 0;
  }

  // 裁判强制设置结果的，只有AdminResult有值，winner没有值
  if (nodeItem.admin_result && nodeItem.admin_result === teamid) {
    teamInfo.isWinner = 1;
  } else if (!nodeItem.admin_result && nodeItem.winner && nodeItem.winner === teamid) {
    teamInfo.isWinner = 1;
  }

  // 预赛程逻辑
  if (isPreview) {
    if (teamid === undefined) {
      schScore[`team${pos}_id`] = SPECIAL_TEAM_ID_MAP.PREVIEW_EMPTY;
      teamInfo.teamid = SPECIAL_TEAM_ID_MAP.PREVIEW_EMPTY;
    } else {
      schScore[`team${pos}_id`] = SPECIAL_TEAM_ID_MAP.PREVIEW;
      teamInfo.teamid = SPECIAL_TEAM_ID_MAP.PREVIEW;
    }
  }

  teamInfo.teamNameDesc = teamInfo.teamname || '待定';
  teamInfo.scoreDesc = `${teamInfo.score || 0}`;
  teamInfo.teamAvatar = teamInfo.teamavatar || SPECIAL_TEAM_STATE_MAP.DAI_DING.avatar;

  return teamInfo;
}


/**
 * 拉平队伍
 * @param {Array} teamList
 */
export function flattenTeamInfo(teamList: Array<any> = []) {
  return teamList.reduce((acc, item) => {
    acc[item.teamid] = item;
    return acc;
  }, {});
}


export const iFindTeam = (
  schInfo: Record<string, any>,
  myTeamId: string,
) => schInfo?.battleList?.[0]?.teamList?.[0]?.teamid == myTeamId
  || schInfo?.battleList?.[0]?.teamList?.[1]?.teamid == myTeamId;
