'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'); const { ObjectId } = require('mongoose').Types; 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; this.baseUserModel = this.ctx.model.Base.User; this.userModel = this.ctx.model.Race.User; this.teamApplyModel = this.ctx.model.Race.TeamApply; } /** * 查询淘汰赛的排名 * @param {Object} query 查询参数 */ async ranking({ match_id, group_id, project_id }) { let raceList = await this.model.find({ match_id, group_id, project_id }); if (raceList.length <= 0) return []; raceList = JSON.parse(JSON.stringify(raceList)); const rarr = []; for (const i of raceList) { const d = await this.getPlayerName(i); rarr.push(d); } const { edges, nodes } = await this.graphData({ match_id, group_id, project_id }); const topEdges = this.getTopNodes(edges); const topNodes = nodes.filter(f => topEdges.find(ff => ff.target === f.id)); // 然后将顶点的节点排序,根据标记进行排序 // 第一名一定是 w, 胜者组: w开头,l越多,越优先; 败者组: l越少,越优先 let winGroup = topNodes.filter(f => f.mark.includes('w')); winGroup = winGroup.map(i => { const markArr = i.mark.split(''); i.sort = markArr.length; return i; }); winGroup = _.orderBy(winGroup, [ 'sort' ], [ 'asc' ]); let loseGroup = topNodes.filter(f => !f.mark.includes('w')); loseGroup = loseGroup.map(i => { const markArr = i.mark.split(''); i.sort = markArr.length; return i; }); loseGroup = _.orderBy(loseGroup, [ 'sort' ], [ 'asc' ]); const orderNodes = [ ...winGroup, ...loseGroup ]; const arr = []; let num = 1; for (const n of orderNodes) { const { id } = n; const es = topEdges.filter(f => f.target === id); const s1 = _.head(es); const s2 = _.last(es); const r = rarr.find(f => (f.player_one_node === s1.source && f.player_two_node === s2.source) || (f.player_one_node === s2.source && f.player_two_node === s1.source)); if (!r) continue; const { player_one_score, player_two_score, player_one_name, player_two_name } = r; let win, lose; if (player_one_score > player_two_score) { win = player_one_name; lose = player_two_name; } else { win = player_two_name; lose = player_one_name; } arr.push({ name: win, num }); if (num < 5) num++; arr.push({ name: lose, num }); if (num < 5) num++; } return arr; } getTopNodes(edges) { const list = edges.filter(f => !edges.find(ff => ff.source === f.target)); return list; } /** * 获取流程图数据 * @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 fetch(filter, { sort, desc, projection } = {}) { assert(filter); filter = await this.beforeFetch(filter); const { _id, id } = filter; if (_id || id) filter = { _id: ObjectId(_id || id) }; // 处理排序 if (sort && _.isString(sort)) { sort = { [sort]: desc ? -1 : 1 }; } else if (sort && _.isArray(sort)) { sort = sort.map(f => ({ [f]: desc ? -1 : 1 })).reduce((p, c) => ({ ...p, ...c }), {}); } // 过滤出ref字段 const { populate } = this.getRefMods(); let res = await this.model.findOne(filter, projection).populate(populate).exec(); res = JSON.parse(JSON.stringify(res)); res = await this.getOtherName(res); res = await this.getPlayerName(res); res = await this.afterFetch(filter, res); return res; } // 换选手名称 async getPlayerName(data) { if (!data) return data; data = JSON.parse(JSON.stringify(data)); const { player_type, player_one, player_two } = data; if (!player_type) return data; // 人处理 if (player_type === 'Race.User') { if (player_one) { const p1 = await this.userModel.findById(player_one, { user_id: 1 }).populate({ path: 'user_id', model: this.baseUserModel, select: 'name' }); data.player_one_name = _.get(p1, 'user_id.name'); } if (player_two) { const p2 = await this.userModel.findById(player_two, { user_id: 1 }).populate({ path: 'user_id', model: this.baseUserModel, select: 'name' }); data.player_two_name = _.get(p2, 'user_id.name'); } } else if (player_type === 'Race.TeamApply') { if (player_one) { const p1 = await this.teamApplyModel.findById(player_one, { one_member_name: 1, two_member_name: 1 }); data.player_one_name = `${_.get(p1, 'one_member_name')}-${_.get(p1, 'two_member_name')}`; } if (player_two) { const p2 = await this.teamApplyModel.findById(player_two, { one_member_name: 1, two_member_name: 1 }); data.player_two_name = `${_.get(p2, 'one_member_name')}-${_.get(p2, 'two_member_name')}`; } } return data; } // 获取其他名称 async getOtherName(data) { if (!data) return data; data = JSON.parse(JSON.stringify(data)); const { referee_id, match_id, group_id, project_id, address_id } = data; if (match_id) { data.match_id_name = _.get(data, 'match_id.name'); data.match_id = _.get(data, 'match_id._id'); } if (group_id) { data.group_id_name = _.get(data, 'group_id.name'); data.group_id = _.get(data, 'group_id._id'); } if (project_id) { data.project_id_name = _.get(data, 'project_id.name'); data.project_id = _.get(data, 'project_id._id'); } if (address_id) { data.address_id_name = _.get(data, 'address_id.name'); data.address_id = _.get(data, 'address_id._id'); } if (referee_id) { data.referee_id_name = _.get(data, 'referee_id.user_id.name'); data.referee_id = _.get(data, 'referee_id._id'); } return data; } async afterQuery(filter, data) { const arr = []; for (let d of data) { d = await this.getOtherName(d); d = await this.getPlayerName(d); arr.push(d); } return arr; } // 如果打完比赛,则自动推进 async afterUpdate(filter, update, data) { const { status } = data; if (status === '2') await this.toNextRace(data); const { _id } = data; const nd = await this.fetch({ _id }); return nd; } // 自动推进至下一场 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; 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; let winner = _.get(data, 'winner'); let looser; let looserNode; // 找到败者 if (!winner) { if (player_one_score > player_two_score) winner = player_one; else winner = player_two; } // 设置败者并获取败者节点 if (winner === player_one) { looser = player_two; looserNode = nodes.find(f => f.id === player_two_node); } else { looser = player_one; looserNode = nodes.find(f => f.id === player_one_node); } const looserNextNodeMark = `${looserNode.mark || ''}l`; // 通过边关系找到下一节点 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_two_node: id }], }; const wEData = await this.model.findOne(wQeury); if (!wEData) return data; if (id === wEData.player_one_node) wEData.player_one = winner; else if (id === wEData.player_two_node) wEData.player_two = winner; await wEData.save(); // 再得出败者的节点id const { level } = node; let midArr = nodes.filter(f => f.level === level); // 先过滤掉胜者节点的mark类型 midArr = midArr.filter(f => f.mark === looserNextNodeMark); console.log(midArr); // 再依次找,哪个节点没有人,没有人就安排上 midArr = _.orderBy(midArr, [ 'pos' ], [ 'asc' ]); for (const n of midArr) { const { id } = n; const query = { $or: [{ player_one_node: id }, { player_two_node: id }], }; const eliminate = await this.model.findOne(query); if (!eliminate) continue; if (!ObjectId.isValid(eliminate.player_one)) eliminate.player_one = looser; else if (!ObjectId.isValid(eliminate.player_two)) eliminate.player_two = looser; else continue; await eliminate.save(); break; } } async beforeQuery(filter) { const user_name = _.get(filter, 'user_name'); let user_id = _.get(filter, 'user_id'); // 没有user_id就不需要处理查询条件 if (!user_id && !user_name) return filter; const usualCondition = _.pick(filter, [ 'match_id', 'group_id', 'project_id' ]); if (user_name) { // 要先找比赛用户模块的数据id const baseUser = await this.baseUserModel.findOne({ name: new RegExp(user_name) }, { _id: 1 }); if (!baseUser) delete filter.user_name; delete filter.user_name; const baseUserId = baseUser._id; const raceUser = await this.userModel.findOne({ user_id: baseUserId, type: '0' }); if (raceUser) user_id = raceUser._id; } if (user_id) { // 需要查:该用户是 单打 和 双打 的情况 // 单打,直接user_id 为player_one/two 就可以,双打需要查teamApply // 所以先把user_id添加进查询范围里 let probablyList = [ user_id ]; // 尽可能的缩小查询范围 // 接着找组队申请中和该用户有关的人 const teamApplyList = await this.teamApplyModel.find({ ...usualCondition, status: '1', $or: [{ one_member_id: user_id }, { two_member_id: user_id }] }, { _id: 1 }); const teamApplyIds = teamApplyList.map(i => i._id); probablyList.push(...teamApplyIds); // 删除user_id.会造成错误 delete filter.user_id; // 添加该用户正确的范围条件 probablyList = probablyList.map(i => ObjectId(i).toString()); filter.$or = [{ player_one: { $in: probablyList } }, { player_two: { $in: probablyList } }]; } return filter; } } module.exports = EliminateService;