'use strict'; const { CrudService } = require('naf-framework-mongoose-free/lib/service'); const { BusinessError, ErrorCode } = require('naf-core').Error; const _ = require('lodash'); const assert = require('assert'); class EliminateService extends CrudService { constructor(ctx) { super(ctx, 'eliminate'); this.model = this.ctx.model.Race.Eliminate; this.matchModel = this.ctx.model.Race.Match; this.matchGroupModel = this.ctx.model.Race.MatchTeamGroup; } /** * 获取流程图数据 * @param {Object} param 比赛项目的参数 * @return {Array} 选手列表 */ async playerList({ match_id, group_id, project_id }) { assert(match_id, '缺少赛事信息'); assert(group_id, '缺少组别信息'); assert(project_id, '缺少项目信息'); const match = await this.matchModel.findById(match_id); if (!match) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到赛事信息'); const { format } = match; // 0为小组赛,不需要这里处理 if (format === '0') return; let players = []; // 1.为淘汰赛,直接找项目的报名选手进行安排 // 2.为小组后淘汰,先找项目的小组再给小组排名;然后根据每组的取前几,决定淘汰赛选手 const groupResult = await this.ctx.model.Race.MatchSmallGroupSchedule.find({ project_id, status: '2' }); const r = await this.groupRanking(groupResult); for (const team_id in r) { const list = r[team_id]; for (const p of list) { players.push(p.player); } } const head = _.head(groupResult); const player_type = _.get(head, 'player_type'); if (player_type === 'Race.TeamApply') { const list = await this.ctx.service.teamApply.query({ _id: players }); players = list.map(i => { const { one_member_name, two_member_name, _id } = i; const obj = { _id, name: `${one_member_name}-${two_member_name}` }; return obj; }); } return players; } /** * 获取流程图数据 * @param {Object} param 比赛项目的参数 * @return {Object} {nodes,edges} 流程图数据 */ async graphData({ match_id, group_id, project_id }) { assert(match_id, '缺少赛事信息'); assert(group_id, '缺少组别信息'); assert(project_id, '缺少项目信息'); const match = await this.matchModel.findById(match_id); if (!match) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到赛事信息'); const { format } = match; // 0为小组赛,不需要这里处理 if (format === '0') return; // 1.为淘汰赛,直接找项目的报名选手进行安排 // 2.为小组后淘汰,先找项目的小组再给小组排名;然后根据每组的取前几,决定淘汰赛选手 // 总之第一步是将选手取出来 const groupResult = await this.ctx.model.Race.MatchSmallGroupSchedule.find({ project_id, status: '2' }); const r = await this.groupRanking(groupResult); const players = []; for (const team_id in r) { const list = r[team_id]; for (const p of list) { players.push(p.player); } } const level = this.getLevel(players.length); const chartData = this.getChartData(level); return chartData; } /** * 获取赛事流程数据(在matchTeamGroup的service中使用的) * 利用边关系,2个节点指向同一节点,即为一场比赛 * @param {Object} data 流程图数据 * @property {Array} edges 流程图数据的边关系 * @return {Array} 赛事流程数据 */ getEliminateData(data) { const { edges } = data; let stop = false; const schList = []; let dupAll = JSON.parse(JSON.stringify(edges)); while (!stop) { const dup = JSON.parse(JSON.stringify(dupAll)); // 取出第一个关系 const head = dup[0]; // 删除第一个关系 dup.shift(); // 查看是否有与第一个关系指向一个目标的地方 const r = dup.find(f => f.target === head.target); if (r) { // 有,则将这俩关系组为一个比赛,然后在dup中删除 const sch = { player_one_node: head.source, player_two_node: r.source }; schList.push(sch); const ri = dup.find(f => f.target === head.target); dup.splice(ri, 1); } dupAll = dup; if (dupAll.length <= 0) stop = true; } return schList; } // 获取表单数据 getChartData(level) { let returnData = {}; const nodes = []; const edges = []; // 生成基数层 const allPersonNumber = 2 ** level; for (let i = 1; i <= allPersonNumber; i++) { const level = 1; // 基数层固定为第一层 const node = this.getNode(level, i); nodes.push(node); } // 生成 胜败组 const winnerTeamLine = allPersonNumber / 2; for (let i = 1; i <= allPersonNumber; i++) { const level = 2; // 胜负组固定为第二层 const mark = i <= winnerTeamLine ? 'w' : 'l'; const node = this.getNode(level, i, mark); nodes.push(node); // 但是只有 胜者组线 以前会产生 边关系; 胜者组线以后的数据为败者组,不与基数层产生关系线 if (i <= winnerTeamLine) { const { level, pos, id } = node; const source1 = `${level - 1}-${2 * pos - 1}`; const source2 = `${level - 1}-${2 * pos}`; const target = id; const edge1 = this.getEdge(source1, target); const edge2 = this.getEdge(source2, target); edges.push(edge1, edge2); } } // 接下来开始进行赛事统一处理 returnData = this.nextProcess(3, nodes, edges); return returnData; } nextProcess(startLevel, nodes, edges) { // 1.正常进行安排:level向前进 const lastLevel = nodes.filter(f => f.level === startLevel - 1); const group = _.chunk(lastLevel, 2); const thisLevelNodes = []; const thisLevelEdges = []; for (let i = 1; i <= group.length; i++) { const e = group[i - 1]; const source1 = _.head(e); const source2 = _.last(e); const mark1 = _.get(source1, 'mark'); const mark2 = _.get(source2, 'mark'); // 先检查mark是否是一致的,如果不一致,就不需要处理了 if (mark1 !== mark2) continue; const nl = startLevel; const pos = i; const node = this.getNode(nl, pos, mark1); const edge1 = this.getEdge(source1.id, node.id); const edge2 = this.getEdge(source2.id, node.id); thisLevelNodes.push(node); thisLevelEdges.push(edge1, edge2); } // 2.检查当前层级是否应该加入败者的比赛(例如:4进2, 剩余2个人要决出名次,就需要加比赛) const thisLevelNodesGroup = _.chunk(thisLevelNodes, 2); for (let i = 0; i < thisLevelNodesGroup.length; i++) { const e = thisLevelNodesGroup[i]; // 先检查mark是否是一致的,如果不一致,就不需要处理了 const s1 = _.head(e); const s2 = _.last(e); if (s1.mark !== s2.mark) continue; // 获取最后一个节点,为了下面计算新节点的pos const last = _.last(thisLevelNodes); const groupLast = _.last(e); const mark = `${_.get(groupLast, 'mark')}l`; const pos = _.get(last, 'pos') + 1; const level = startLevel; // 这地方应该生成的是 const obj1 = this.getNode(level, pos, mark); const obj2 = this.getNode(level, pos + 1, mark); thisLevelNodes.push(obj1, obj2); } nodes.push(...thisLevelNodes); edges.push(...thisLevelEdges); if (thisLevelNodes.length > 0) { const { nodes: sn, edges: se } = this.nextProcess(startLevel + 1, nodes, edges); nodes = sn; edges = se; } return { nodes, edges }; } getNode(level, pos, mark, name = '选手') { const id = `${mark ? `${mark}-` : ''}${level}-${pos}`; const nName = `${name}${id}`; return { id, name: nName, level, pos, mark }; } getEdge(source, target) { return { source, target }; } async getPersonNumber({ match_id, group_id, project_id }) { const list = await this.matchGroupModel.find({ match_id, group_id, project_id }, { rise: 1 }); const number = list.reduce((p, n) => p + parseInt(n.rise) || 0, 0); return number; } /** * 返回按比赛结果,将各个小组晋级的选手及成绩 * @param {Array} list 某项目的所有比赛 * @return {Array} {team_id:[{player,win,score}]} */ async groupRanking(list) { list = JSON.parse(JSON.stringify(list)); // 先看每场比赛有没有胜者,有胜者就过,没有就设置下 list = list.map(i => { const { winner, player_one, player_one_score, player_two, player_two_score } = i; if (winner) return i; if (player_one_score > player_two_score) i.winner = player_one; else i.winner = player_two; return i; }); list = _.groupBy(list, 'team_id'); for (const team_id in list) { const groups = list[team_id]; // 过滤出选手 let players = []; const p1s = groups.map(i => i.player_one); const p2s = groups.map(i => i.player_two); players.push(...p1s, ...p2s); players = _.uniq(players); // 转换成object[], player:选手; win: 胜场; score:净胜球 players = players.map(i => ({ player: i, win: 0, score: 0 })); for (const g of groups) { const { winner, player_one, player_one_score, player_two, player_two_score } = g; const p1RoundScore = this.getScore(player_one_score, player_two_score); const p2RoundScore = this.getScore(player_two_score, player_one_score); const p1 = players.find(f => f.player === player_one); const p2 = players.find(f => f.player === player_two); // p1,p2谁没有就不行 if (!p1 || !p2) continue; p1.score = p1.score + p1RoundScore; p2.score = p2.score + p2RoundScore; if (winner === player_one) p1.win += 1; else p2.win += 1; } players = _.orderBy(players, [ 'win', 'score' ], [ 'desc', 'desc' ]); const team = await this.ctx.model.Race.MatchTeamGroup.findById(team_id); if (!team) continue; const { rise } = team; const toNext = _.head(_.chunk(players, rise)); list[team_id] = toNext; } return list; } /** * 计算净胜分 * @param {String|Number} s1 分数1 * @param {String|Number} s2 分数2 * @return {Number} 净胜分 */ getScore(s1, s2) { return parseInt(s1) - parseInt(s2); } /** * 计算比赛轮数 * @param {Number} number 淘汰赛总人数 * @return {Number} 比赛轮数 */ getLevel(number) { let i = 1; let stop = false; while (!stop) { const num = 2 ** i; if (num === number) stop = true; else if (i > 10) stop = true; else i++; } if (i > 10) throw new BusinessError(ErrorCode.SERVICE_FAULT, '人数过多,请使用小组赛+淘汰赛赛制'); return i; } // 如果打完比赛,则自动推进 async afterUpdate(filter, data) { const { status } = data; if (status === '2') await this.toNextRace(data); return data; } // 自动推进至下一场 async toNextRace(data) { const { match_id, group_id, project_id, player_one, player_one_score, player_one_node, player_two, player_two_node, player_two_score } = data; let winner = _.get(data, 'winner'); let looser; // 找到输家 if (!winner) { if (player_one_score > player_two_score) winner = player_one; else winner = player_two; } if (winner === player_one) looser = player_two; else looser = player_one; const number = await this.getPersonNumber({ match_id, group_id, project_id }); const chartLevel = this.getLevel(number); const chartData = this.getChartData(chartLevel); // 通过整图关系,找到下一步 const { edges, nodes } = chartData; // 通过边关系找到下一节点 const list = edges.filter(f => f.source === player_one_node || f.source === player_two_node); const getTarget = nodeEdge => _.get(nodeEdge, 'target'); if (getTarget(_.head(list)) !== getTarget(_.last(list))) throw new BusinessError(ErrorCode.DATA_INVALID, '两个选手的图位置错误'); // 确定了胜者晋级的节点id const target = getTarget(_.head(list)); const node = nodes.find(f => f.id === target); const { id } = node; const wQeury = { $or: [ { player_one_node: id, player_one: { $exists: false } }, { player_two_node: id, player_two: { $exists: false } }, ], }; const wEData = await this.model.findOne(wQeury); if (id === wEData.player_one_node) wEData.player_one = winner; else wEData.player_two = winner; await wEData.save(); // 再得出败者的节点id const { mark, level } = node; let midArr = nodes.filter(f => f.level === level); // 先过滤掉胜者节点的mark类型 midArr = midArr.filter(f => f.mark !== mark); // 再依次找,哪个节点没有人,没有人就安排上 midArr = _.orderBy(midArr, [ 'pos' ], [ 'asc' ]); for (const n of midArr) { const { id } = n; const query = { $or: [ { player_one_node: id, player_one: { $exists: false } }, { player_two_node: id, player_two: { $exists: false } }, ], }; const eliminate = await this.model.findOne(query); if (!eliminate) continue; if (eliminate.player_one_node === id) eliminate.player_one = looser; else eliminate.player_two = looser; await eliminate.save(); break; } } } module.exports = EliminateService;