import { SCHEDULE_TYPE_MAP } from '../config';

import { getBattleId, getRedSide } from './battle-id';
import { getBattleState } from './battle-status';
import { iFindTeam, flattenTeamInfo, getTeamInfo } from './team-info';

let teamList = [];
let teamMap = {};


/**
 * 处理赛程列表的主要函数
 *
 * 淘汰赛和循环赛的scheList格式不同，淘汰赛为[[1轮1场，1轮2场],[2轮1场，2轮2场],]
 * 循环赛轮次为同一个，为[[x轮1组1场，x轮1组2场],[x轮2组1场,x轮2组2场]]
 */
export function handleScheList(resp: any, isPreview: any, roundInfo: Record<string, any>): any {
  const myTeamId = resp.my_team_id;
  let activeGrops = 0;
  const treeNodeList = resp.tree_round_list || [];
  let rTree = treeNodeList;
  const { curScheType } = resp;

  const isCycleType = curScheType === SCHEDULE_TYPE_MAP.CYCLE;

  if (roundInfo && isCycleType) {
    rTree = rTree.filter((item: any) => {
      const round = item.round_info || {};
      return round.round_id === roundInfo.round_id && round.round_stage === roundInfo.round_stage;
    });
  }


  const res = rTree.reduce((acc: Array<any>, item: any) => {
    acc.push(handleSchInfo(item, resp, isPreview));
    return acc;
  }, []);

  if (isCycleType) {
    const res2 = res[0] || [];
    res2.sort((a: any, b: any) => a?.partitionId - b?.partitionId);
    const genRes = res2.reduce((acc: Array<any>, item: any) => {
      const last = acc[acc.length - 1];
      if (last && last[0].partitionId == item.partitionId) {
        last.push(item);
      } else {
        acc.push([item]);
      }
      return acc;
    }, []);

    if (resp.my_team_id) {
      genRes?.forEach((item: any) => {
        item?.forEach((cItem: any) => {
          if (iFindTeam(cItem, myTeamId)) {
            activeGrops = cItem.partitionId;
          }
        });
      });
    }
    const obj = {
      scheList: genRes,
      activeGrops,
    };
    return obj;
  }
  const obj = {
    scheList: res,
  };
  return obj;
}


// 处理赛程
function handleSchInfo(treeRound: Record<string, any> = {}, resp: Record<string, any> = {}, isPreview: number) {
  const res: any = [];
  const nodeList = (treeRound.node_list) || [];
  teamList = resp.team_list || [];
  teamMap = flattenTeamInfo(teamList);
  const roundInfo = treeRound.round_info || {};

  let i = 0;

  while (i < nodeList.length) {
    const scheGroupList: any = [];
    scheGroupList.push(handleNodeItem(
      nodeList[i],
      resp?.partition_id,
      resp?.game_info?.game_name,
      treeRound?.round_info?.round_name,
      isPreview,
      roundInfo,
      resp,
    ));


    const { curScheType } = resp;

    const isEliminationType = curScheType == SCHEDULE_TYPE_MAP.DOUBLE_FAIL
      || curScheType == SCHEDULE_TYPE_MAP.KNOCK_OUT;

    // 只有淘汰赛的时候，才一定要找下一组
    if (isEliminationType && nodeList.length != 1) {
      i += 1;
      scheGroupList.push(handleNodeItem(
        nodeList[i],
        resp?.partition_id,
        resp?.game_info?.game_name,
        treeRound?.round_info?.round_name,
        isPreview,
        roundInfo,
        resp,
      ));
    }

    res.push({
      battleList: scheGroupList,
      roundInfo,
      partitionId: nodeList[i]?.sch_rule?.partition_id,
      isChamp: isChamp(),
    });
    i += 1;
  }

  function isChamp() {
    if (resp.stage == 3) {
      return nodeList.length == 1;
    }
    return nodeList[i] && nodeList[i].sch_type == 4 && nodeList.length == 1;
  }
  return res;
}


// 处理节点项，即node_list的每一项，nodeItem是两个队伍
function handleNodeItem(
  nodeItem: Record<string, any> = {},
  partitionId: number,
  gameName: string,
  roundName: string,
  isPreview: number,
  roundInfo: Record<string, any>,
  resp: any,
) {
  nodeItem.rawState = nodeItem.state;
  const upTeamInfo = getTeamInfo(nodeItem, 'a', isPreview, roundInfo, teamMap);
  const downTeamInfo = getTeamInfo(nodeItem, 'b', isPreview, roundInfo, teamMap);
  const battleid = getBattleId(nodeItem);
  const boType = nodeItem.sch_score?.bo_type || 1;
  const curBo = nodeItem.sch_score?.cur_bo || 1;
  const roomType = nodeItem.sch_score?.room_type || 1;
  const isWinner = roundInfo.round_type === 'winner';
  const { curScheType } = resp;
  const liveInfo = resp.live_info || {};
  const battleStatus = getBattleState(nodeItem);
  const redSide = getRedSide(nodeItem);
  // 顶号相关,不区分用户类型
  const abnormalErr = nodeItem.sch_score?.err_flag === 9999;

  const scheGroup: any = {
    teamList: [
      upTeamInfo,
      downTeamInfo,
    ],
    battleid,
    partitionId,
    gameName,
    roundName,
    boType,
    curBo,
    roomType,
    battleStatus,
    redSide,
    schid: nodeItem.schid,
    status: nodeItem.status,
    realStatus: nodeItem.state,
    isWeChatLiving: liveInfo.living_status == 1 && liveInfo.battleid == battleid,
    liveInfo,
    nodeItem,
    abnormalErr,
  };
  if (curScheType == SCHEDULE_TYPE_MAP.DOUBLE_FAIL) {
    scheGroup.bracketIdDesc = `${isWinner ? 'U' : 'L'}${nodeItem?.sch_rule?.bracket_id}`;
  } else {
    // 1.2.7的赛程图优化，双败赛之外使用共同的编号模式
    scheGroup.bracketIdDesc = nodeItem?.sch_rule?.bracket_id ? `#${nodeItem?.sch_rule?.bracket_id}` : '';
  }
  return scheGroup;
}


