eliminate.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. 'use strict';
  2. const { CrudService } = require('naf-framework-mongoose-free/lib/service');
  3. const { BusinessError, ErrorCode } = require('naf-core').Error;
  4. const _ = require('lodash');
  5. const assert = require('assert');
  6. class EliminateService extends CrudService {
  7. constructor(ctx) {
  8. super(ctx, 'eliminate');
  9. this.model = this.ctx.model.Race.Eliminate;
  10. this.matchModel = this.ctx.model.Race.Match;
  11. this.matchGroupModel = this.ctx.model.Race.MatchTeamGroup;
  12. }
  13. /**
  14. * 获取流程图数据
  15. * @param {Object} param 比赛项目的参数
  16. * @return {Array} 选手列表
  17. */
  18. async playerList({ match_id, group_id, project_id }) {
  19. assert(match_id, '缺少赛事信息');
  20. assert(group_id, '缺少组别信息');
  21. assert(project_id, '缺少项目信息');
  22. const match = await this.matchModel.findById(match_id);
  23. if (!match) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到赛事信息');
  24. const { format } = match;
  25. // 0为小组赛,不需要这里处理
  26. if (format === '0') return;
  27. let players = [];
  28. // 1.为淘汰赛,直接找项目的报名选手进行安排
  29. // 2.为小组后淘汰,先找项目的小组再给小组排名;然后根据每组的取前几,决定淘汰赛选手
  30. const groupResult = await this.ctx.model.Race.MatchSmallGroupSchedule.find({ project_id, status: '2' });
  31. const r = await this.groupRanking(groupResult);
  32. for (const team_id in r) {
  33. const list = r[team_id];
  34. for (const p of list) {
  35. players.push(p.player);
  36. }
  37. }
  38. const head = _.head(groupResult);
  39. const player_type = _.get(head, 'player_type');
  40. if (player_type === 'Race.TeamApply') {
  41. const list = await this.ctx.service.teamApply.query({ _id: players });
  42. players = list.map(i => {
  43. const { one_member_name, two_member_name, _id } = i;
  44. const obj = { _id, name: `${one_member_name}-${two_member_name}` };
  45. return obj;
  46. });
  47. }
  48. return players;
  49. }
  50. /**
  51. * 获取流程图数据
  52. * @param {Object} param 比赛项目的参数
  53. * @return {Object} {nodes,edges} 流程图数据
  54. */
  55. async graphData({ match_id, group_id, project_id }) {
  56. assert(match_id, '缺少赛事信息');
  57. assert(group_id, '缺少组别信息');
  58. assert(project_id, '缺少项目信息');
  59. const match = await this.matchModel.findById(match_id);
  60. if (!match) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到赛事信息');
  61. const { format } = match;
  62. // 0为小组赛,不需要这里处理
  63. if (format === '0') return;
  64. // 1.为淘汰赛,直接找项目的报名选手进行安排
  65. // 2.为小组后淘汰,先找项目的小组再给小组排名;然后根据每组的取前几,决定淘汰赛选手
  66. // 总之第一步是将选手取出来
  67. const groupResult = await this.ctx.model.Race.MatchSmallGroupSchedule.find({ project_id, status: '2' });
  68. const r = await this.groupRanking(groupResult);
  69. const players = [];
  70. for (const team_id in r) {
  71. const list = r[team_id];
  72. for (const p of list) {
  73. players.push(p.player);
  74. }
  75. }
  76. const level = this.getLevel(players.length);
  77. const chartData = this.getChartData(level);
  78. return chartData;
  79. }
  80. /**
  81. * 获取赛事流程数据(在matchTeamGroup的service中使用的)
  82. * 利用边关系,2个节点指向同一节点,即为一场比赛
  83. * @param {Object} data 流程图数据
  84. * @property {Array} edges 流程图数据的边关系
  85. * @return {Array} 赛事流程数据
  86. */
  87. getEliminateData(data) {
  88. const { edges } = data;
  89. let stop = false;
  90. const schList = [];
  91. let dupAll = JSON.parse(JSON.stringify(edges));
  92. while (!stop) {
  93. const dup = JSON.parse(JSON.stringify(dupAll));
  94. // 取出第一个关系
  95. const head = dup[0];
  96. // 删除第一个关系
  97. dup.shift();
  98. // 查看是否有与第一个关系指向一个目标的地方
  99. const r = dup.find(f => f.target === head.target);
  100. if (r) {
  101. // 有,则将这俩关系组为一个比赛,然后在dup中删除
  102. const sch = { player_one_node: head.source, player_two_node: r.source };
  103. schList.push(sch);
  104. const ri = dup.find(f => f.target === head.target);
  105. dup.splice(ri, 1);
  106. }
  107. dupAll = dup;
  108. if (dupAll.length <= 0) stop = true;
  109. }
  110. return schList;
  111. }
  112. // 获取表单数据
  113. getChartData(level) {
  114. let returnData = {};
  115. const nodes = [];
  116. const edges = [];
  117. // 生成基数层
  118. const allPersonNumber = 2 ** level;
  119. for (let i = 1; i <= allPersonNumber; i++) {
  120. const level = 1; // 基数层固定为第一层
  121. const node = this.getNode(level, i);
  122. nodes.push(node);
  123. }
  124. // 生成 胜败组
  125. const winnerTeamLine = allPersonNumber / 2;
  126. for (let i = 1; i <= allPersonNumber; i++) {
  127. const level = 2; // 胜负组固定为第二层
  128. const mark = i <= winnerTeamLine ? 'w' : 'l';
  129. const node = this.getNode(level, i, mark);
  130. nodes.push(node);
  131. // 但是只有 胜者组线 以前会产生 边关系; 胜者组线以后的数据为败者组,不与基数层产生关系线
  132. if (i <= winnerTeamLine) {
  133. const { level, pos, id } = node;
  134. const source1 = `${level - 1}-${2 * pos - 1}`;
  135. const source2 = `${level - 1}-${2 * pos}`;
  136. const target = id;
  137. const edge1 = this.getEdge(source1, target);
  138. const edge2 = this.getEdge(source2, target);
  139. edges.push(edge1, edge2);
  140. }
  141. }
  142. // 接下来开始进行赛事统一处理
  143. returnData = this.nextProcess(3, nodes, edges);
  144. return returnData;
  145. }
  146. nextProcess(startLevel, nodes, edges) {
  147. // 1.正常进行安排:level向前进
  148. const lastLevel = nodes.filter(f => f.level === startLevel - 1);
  149. const group = _.chunk(lastLevel, 2);
  150. const thisLevelNodes = [];
  151. const thisLevelEdges = [];
  152. for (let i = 1; i <= group.length; i++) {
  153. const e = group[i - 1];
  154. const source1 = _.head(e);
  155. const source2 = _.last(e);
  156. const mark1 = _.get(source1, 'mark');
  157. const mark2 = _.get(source2, 'mark');
  158. // 先检查mark是否是一致的,如果不一致,就不需要处理了
  159. if (mark1 !== mark2) continue;
  160. const nl = startLevel;
  161. const pos = i;
  162. const node = this.getNode(nl, pos, mark1);
  163. const edge1 = this.getEdge(source1.id, node.id);
  164. const edge2 = this.getEdge(source2.id, node.id);
  165. thisLevelNodes.push(node);
  166. thisLevelEdges.push(edge1, edge2);
  167. }
  168. // 2.检查当前层级是否应该加入败者的比赛(例如:4进2, 剩余2个人要决出名次,就需要加比赛)
  169. const thisLevelNodesGroup = _.chunk(thisLevelNodes, 2);
  170. for (let i = 0; i < thisLevelNodesGroup.length; i++) {
  171. const e = thisLevelNodesGroup[i];
  172. // 先检查mark是否是一致的,如果不一致,就不需要处理了
  173. const s1 = _.head(e);
  174. const s2 = _.last(e);
  175. if (s1.mark !== s2.mark) continue;
  176. // 获取最后一个节点,为了下面计算新节点的pos
  177. const last = _.last(thisLevelNodes);
  178. const groupLast = _.last(e);
  179. const mark = `${_.get(groupLast, 'mark')}l`;
  180. const pos = _.get(last, 'pos') + 1;
  181. const level = startLevel;
  182. // 这地方应该生成的是
  183. const obj1 = this.getNode(level, pos, mark);
  184. const obj2 = this.getNode(level, pos + 1, mark);
  185. thisLevelNodes.push(obj1, obj2);
  186. }
  187. nodes.push(...thisLevelNodes);
  188. edges.push(...thisLevelEdges);
  189. if (thisLevelNodes.length > 0) {
  190. const { nodes: sn, edges: se } = this.nextProcess(startLevel + 1, nodes, edges);
  191. nodes = sn;
  192. edges = se;
  193. }
  194. return { nodes, edges };
  195. }
  196. getNode(level, pos, mark, name = '选手') {
  197. const id = `${mark ? `${mark}-` : ''}${level}-${pos}`;
  198. const nName = `${name}${id}`;
  199. return { id, name: nName, level, pos, mark };
  200. }
  201. getEdge(source, target) {
  202. return { source, target };
  203. }
  204. async getPersonNumber({ match_id, group_id, project_id }) {
  205. const list = await this.matchGroupModel.find({ match_id, group_id, project_id }, { rise: 1 });
  206. const number = list.reduce((p, n) => p + parseInt(n.rise) || 0, 0);
  207. return number;
  208. }
  209. /**
  210. * 返回按比赛结果,将各个小组晋级的选手及成绩
  211. * @param {Array} list 某项目的所有比赛
  212. * @return {Array} {team_id:[{player,win,score}]}
  213. */
  214. async groupRanking(list) {
  215. list = JSON.parse(JSON.stringify(list));
  216. // 先看每场比赛有没有胜者,有胜者就过,没有就设置下
  217. list = list.map(i => {
  218. const { winner, player_one, player_one_score, player_two, player_two_score } = i;
  219. if (winner) return i;
  220. if (player_one_score > player_two_score) i.winner = player_one;
  221. else i.winner = player_two;
  222. return i;
  223. });
  224. list = _.groupBy(list, 'team_id');
  225. for (const team_id in list) {
  226. const groups = list[team_id];
  227. // 过滤出选手
  228. let players = [];
  229. const p1s = groups.map(i => i.player_one);
  230. const p2s = groups.map(i => i.player_two);
  231. players.push(...p1s, ...p2s);
  232. players = _.uniq(players);
  233. // 转换成object[], player:选手; win: 胜场; score:净胜球
  234. players = players.map(i => ({ player: i, win: 0, score: 0 }));
  235. for (const g of groups) {
  236. const { winner, player_one, player_one_score, player_two, player_two_score } = g;
  237. const p1RoundScore = this.getScore(player_one_score, player_two_score);
  238. const p2RoundScore = this.getScore(player_two_score, player_one_score);
  239. const p1 = players.find(f => f.player === player_one);
  240. const p2 = players.find(f => f.player === player_two);
  241. // p1,p2谁没有就不行
  242. if (!p1 || !p2) continue;
  243. p1.score = p1.score + p1RoundScore;
  244. p2.score = p2.score + p2RoundScore;
  245. if (winner === player_one) p1.win += 1;
  246. else p2.win += 1;
  247. }
  248. players = _.orderBy(players, [ 'win', 'score' ], [ 'desc', 'desc' ]);
  249. const team = await this.ctx.model.Race.MatchTeamGroup.findById(team_id);
  250. if (!team) continue;
  251. const { rise } = team;
  252. const toNext = _.head(_.chunk(players, rise));
  253. list[team_id] = toNext;
  254. }
  255. return list;
  256. }
  257. /**
  258. * 计算净胜分
  259. * @param {String|Number} s1 分数1
  260. * @param {String|Number} s2 分数2
  261. * @return {Number} 净胜分
  262. */
  263. getScore(s1, s2) {
  264. return parseInt(s1) - parseInt(s2);
  265. }
  266. /**
  267. * 计算比赛轮数
  268. * @param {Number} number 淘汰赛总人数
  269. * @return {Number} 比赛轮数
  270. */
  271. getLevel(number) {
  272. let i = 1;
  273. let stop = false;
  274. while (!stop) {
  275. const num = 2 ** i;
  276. if (num === number) stop = true;
  277. else if (i > 10) stop = true;
  278. else i++;
  279. }
  280. if (i > 10) throw new BusinessError(ErrorCode.SERVICE_FAULT, '人数过多,请使用小组赛+淘汰赛赛制');
  281. return i;
  282. }
  283. // 如果打完比赛,则自动推进
  284. async afterUpdate(filter, data) {
  285. const { status } = data;
  286. if (status === '2') await this.toNextRace(data);
  287. return data;
  288. }
  289. // 自动推进至下一场
  290. async toNextRace(data) {
  291. const { match_id, group_id, project_id, player_one, player_one_score, player_one_node, player_two, player_two_node, player_two_score } = data;
  292. let winner = _.get(data, 'winner');
  293. let looser;
  294. // 找到输家
  295. if (!winner) {
  296. if (player_one_score > player_two_score) winner = player_one;
  297. else winner = player_two;
  298. }
  299. if (winner === player_one) looser = player_two;
  300. else looser = player_one;
  301. const number = await this.getPersonNumber({ match_id, group_id, project_id });
  302. const chartLevel = this.getLevel(number);
  303. const chartData = this.getChartData(chartLevel);
  304. // 通过整图关系,找到下一步
  305. const { edges, nodes } = chartData;
  306. // 通过边关系找到下一节点
  307. const list = edges.filter(f => f.source === player_one_node || f.source === player_two_node);
  308. const getTarget = nodeEdge => _.get(nodeEdge, 'target');
  309. if (getTarget(_.head(list)) !== getTarget(_.last(list))) throw new BusinessError(ErrorCode.DATA_INVALID, '两个选手的图位置错误');
  310. // 确定了胜者晋级的节点id
  311. const target = getTarget(_.head(list));
  312. const node = nodes.find(f => f.id === target);
  313. const { id } = node;
  314. const wQeury = {
  315. $or: [
  316. { player_one_node: id, player_one: { $exists: false } },
  317. { player_two_node: id, player_two: { $exists: false } },
  318. ],
  319. };
  320. const wEData = await this.model.findOne(wQeury);
  321. if (id === wEData.player_one_node) wEData.player_one = winner;
  322. else wEData.player_two = winner;
  323. await wEData.save();
  324. // 再得出败者的节点id
  325. const { mark, level } = node;
  326. let midArr = nodes.filter(f => f.level === level);
  327. // 先过滤掉胜者节点的mark类型
  328. midArr = midArr.filter(f => f.mark !== mark);
  329. // 再依次找,哪个节点没有人,没有人就安排上
  330. midArr = _.orderBy(midArr, [ 'pos' ], [ 'asc' ]);
  331. for (const n of midArr) {
  332. const { id } = n;
  333. const query = {
  334. $or: [
  335. { player_one_node: id, player_one: { $exists: false } },
  336. { player_two_node: id, player_two: { $exists: false } },
  337. ],
  338. };
  339. const eliminate = await this.model.findOne(query);
  340. if (!eliminate) continue;
  341. if (eliminate.player_one_node === id) eliminate.player_one = looser;
  342. else eliminate.player_two = looser;
  343. await eliminate.save();
  344. break;
  345. }
  346. }
  347. }
  348. module.exports = EliminateService;