eliminate.js 17 KB

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