trainplan.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997
  1. 'use strict';
  2. const _ = require('lodash');
  3. const { CrudService } = require('naf-framework-mongoose/lib/service');
  4. const assert = require('assert');
  5. const { BusinessError, ErrorCode } = require('naf-core').Error;
  6. const XLSX = require('xlsx');
  7. const utils = require('../utils/utils.js');
  8. const moment = require('moment');
  9. const XLSXStyle = require('xlsx-style');
  10. class TrainplanService extends CrudService {
  11. constructor(ctx) {
  12. super(ctx, 'trainplan');
  13. this.model = this.ctx.model.Trainplan;
  14. this.clamodel = this.ctx.model.Class;
  15. this.umodel = this.ctx.model.User;
  16. this.smodel = this.ctx.model.School;
  17. this.tmodel = this.ctx.model.Teacher;
  18. this.stumodel = this.ctx.model.Student;
  19. this.schmodel = this.ctx.model.Schtime;
  20. this.lmmodel = this.ctx.model.Lessonmode;
  21. }
  22. async create(data) {
  23. const { planyearid, year, title } = data;
  24. assert(planyearid, '缺少大批次信息');
  25. assert(year, '缺少年度');
  26. assert(title, '缺少标题');
  27. const res = await this.model.create(data);
  28. console.log(res);
  29. let planid = '';
  30. if (res) planid = res._id;
  31. const schoolList = await this.smodel.find();
  32. const schtimeArr = [];
  33. for (const sch of schoolList) {
  34. const { code } = sch;
  35. const obj = { schid: code, year, planid };
  36. const schtimeres = await this.schmodel.create(obj);
  37. if (schtimeres) schtimeArr.push(schtimeres);
  38. }
  39. if (!schtimeArr.every(e => e)) { throw new BusinessError(ErrorCode.DATA_INVALID, '学校计划生成失败'); } else return res;
  40. }
  41. async update({ id }, data) {
  42. const trainplan = await this.model.findById(id);
  43. // 保存原数据
  44. const trainplanold = _.cloneDeep(trainplan);
  45. const { year, title, termnum, festivals, status, school } = data;
  46. if (year) {
  47. trainplan.year = year;
  48. }
  49. if (title) {
  50. trainplan.title = title;
  51. }
  52. if (termnum) {
  53. trainplan.termnum = termnum;
  54. }
  55. if (school) {
  56. trainplan.school = school;
  57. }
  58. if (festivals) {
  59. trainplan.festivals = festivals;
  60. }
  61. if (status === '1') {
  62. trainplan.status = status;
  63. }
  64. // 日历安排中添加课表信息,查询每种班级类型的课表,然后显示
  65. if (trainplan.termnum) {
  66. // trainplan.termnum =
  67. trainplan.termnum = await this.termGetLesson(trainplan.termnum);
  68. }
  69. // 如果培训计划状态改为发布,发送培训计划信息,并自动生成班级
  70. const res = await trainplan.save();
  71. if (res) {
  72. if (status === '1') {
  73. // 自动生成班级
  74. // await this.autoclass(res, trainplanold);
  75. // await this.autoclassNew(res, trainplanold);
  76. // 将生成的班级重新将班级排班名
  77. // await this.autoclassname(res);
  78. // 发送培训计划信息通知给相应人员
  79. // 查询所有入库的教师
  80. const teachers = await this.tmodel.find({ status: '4' });
  81. for (const teacher of teachers) {
  82. const teacherid = teacher._id;
  83. const _teacher = await this.umodel.findOne({
  84. uid: teacherid,
  85. type: '3',
  86. });
  87. const openid = _teacher.openid;
  88. const detail = trainplan.title + '已发布,请注意查收!';
  89. const date = await this.ctx.service.util.updatedate();
  90. const remark = '感谢您的使用';
  91. if (openid) {
  92. this.ctx.service.weixin.sendTemplateMsg(
  93. this.ctx.app.config.REVIEW_TEMPLATE_ID,
  94. openid,
  95. '您有一个新的通知',
  96. detail,
  97. date,
  98. remark
  99. );
  100. }
  101. }
  102. // 查询所有学校用户
  103. const schools = await this.umodel.find({ type: '2' });
  104. for (const school of schools) {
  105. const openid = school.openid;
  106. const detail = trainplan.title + '已发布,请注意查收!';
  107. const date = await this.ctx.service.util.updatedate();
  108. const remark = '感谢您的使用';
  109. if (openid) {
  110. this.ctx.service.weixin.sendTemplateMsg(
  111. this.ctx.app.config.REVIEW_TEMPLATE_ID,
  112. openid,
  113. '您有一个新的通知',
  114. detail,
  115. date,
  116. remark
  117. );
  118. }
  119. }
  120. }
  121. }
  122. return res;
  123. }
  124. async termGetLesson(termnum) {
  125. const lessonModelList = await this.lmmodel.find();
  126. for (const term of termnum) {
  127. for (const batch of term.batchnum) {
  128. const { class: classes, startdate, enddate } = batch;
  129. // 获取每批次下每个班的班级类型
  130. const typeList = _.uniq(classes.map(i => i.type));
  131. const h = _.head(typeList);
  132. if (!h) continue;
  133. const tem = lessonModelList.find(f => f.type === h);
  134. let { lessons } = tem;
  135. if (!lessons) break;
  136. lessons = JSON.parse(lessons);
  137. // 过滤出上课的时间段
  138. lessons = lessons.filter(f => {
  139. const keys = Object.keys(f).filter(f => f.includes('subid'));
  140. return keys.length > 0;
  141. });
  142. // 记录上课的时间
  143. const times = [];
  144. // 记录所有的科目
  145. let subject = [];
  146. lessons.map(i => {
  147. times.push(i.time);
  148. const keys = Object.keys(i);
  149. let arr = [];
  150. for (const key of keys) {
  151. if (key.match(/\d/g)) arr.push(_.head(key.match(/\d/g)));
  152. }
  153. arr = _.uniq(arr);
  154. for (const ai of arr) {
  155. if (i[`day${ai}subid`]) {
  156. subject.push({
  157. subname: i[`day${ai}`],
  158. subid: i[`day${ai}subid`],
  159. day: ai,
  160. });
  161. }
  162. }
  163. // console.log(arr);
  164. return i;
  165. });
  166. // 去重
  167. subject = _.uniqBy(subject, 'subid');
  168. // 获得天列表
  169. const dnum = moment(enddate).diff(moment(startdate), 'days') + 1;
  170. const dayList = [];
  171. for (let ind = 0; ind < dnum; ind++) {
  172. dayList.push(moment(startdate).add(ind, 'd').format('YYYY-MM-DD'));
  173. }
  174. // 将subject中的day换成日期
  175. for (const sub of subject) {
  176. sub.day = dayList[sub.day * 1 - 1];
  177. sub.time = times;
  178. }
  179. batch.lessons = subject;
  180. }
  181. }
  182. return termnum;
  183. }
  184. // 自动生成班级私有方法
  185. async autoclassNew(res) {
  186. // 删除所有计划下的班级
  187. await this.clamodel.deleteMany({ planid: res.id });
  188. // 循环出所有班级进行添加操作
  189. for (const term of res.termnum) {
  190. for (const batch of term.batchnum) {
  191. const classs = await batch.class;
  192. for (const cla of classs) {
  193. const newdata = {
  194. name: cla.name,
  195. number: cla.number,
  196. batchid: batch.id,
  197. termid: term.id,
  198. planid: res.id,
  199. type: cla.type,
  200. headteacherid: cla.headteacherid,
  201. };
  202. await this.clamodel.create(newdata);
  203. }
  204. }
  205. }
  206. }
  207. // 自动生成班级私有方法
  208. async autoclass(res, trainplanold) {
  209. // 首先比较当前数据和原数据的值是否有不同
  210. // 保存后所有期id
  211. const tremid_res = _.map(res.termnum, 'id');
  212. // 保存前所有期id
  213. const tremid_old = _.map(trainplanold.termnum, 'id');
  214. // 取得要删除的期id,进行班级中删除已删除期的班级
  215. const deltrem = _.difference(tremid_old, tremid_res);
  216. // 循环删除已经删除期的所有班级
  217. for (const elm of deltrem) {
  218. await this.clamodel.deleteMany({ termid: elm });
  219. }
  220. // 取得所有新加期id
  221. const addtrem = _.difference(tremid_res, tremid_old);
  222. // 清空后循环取得所有期进行批次操作
  223. const terms = res.termnum;
  224. for (const el of terms) {
  225. // 判断是否新加期
  226. if (_.indexOf(addtrem, el.id) !== -1) {
  227. // 循环当前新加期的批次列表,根据批次id和班级数生成班级信息
  228. const batchnums = el.batchnum;
  229. for (const batchnum of batchnums) {
  230. // 取得当前批次的班级数
  231. const classnum = batchnum.class;
  232. for (const cla of classnum) {
  233. const newdata = {
  234. name: cla.name,
  235. number: cla.number,
  236. batchid: batchnum.id,
  237. termid: el.id,
  238. planid: res.id,
  239. type: cla.type,
  240. };
  241. await this.clamodel.create(newdata);
  242. }
  243. }
  244. } else {
  245. // 不是新加期,更新期信息
  246. // 保存后所有期id
  247. const batchid_res = _.map(el.batchnum, 'id');
  248. // 保存前所有期id
  249. const batchid_old = _.map(
  250. trainplanold.termnum.id(el.id).batchnum,
  251. 'id'
  252. );
  253. // 取得要删除的期id,进行班级中删除已删除期的班级
  254. const delbatchs = _.difference(batchid_old, batchid_res);
  255. // 循环删除已经删除期的所有班级
  256. for (const delba of delbatchs) {
  257. await this.clamodel.deleteMany({ termid: el.id, batchid: delba });
  258. }
  259. // 取得所有新加期id
  260. const addbatch = _.difference(batchid_res, batchid_old);
  261. const batchnums = el.batchnum;
  262. for (const batchnum of batchnums) {
  263. // 取得当前批次是否有删除
  264. // 判断是否新加期
  265. if (_.indexOf(addbatch, batchnum.id) !== -1) {
  266. // 取得当前批次的班级数
  267. const classnum = batchnum.class;
  268. for (const cla of classnum) {
  269. const newdata = {
  270. name: cla.name,
  271. number: cla.number,
  272. batchid: batchnum.id,
  273. termid: el.id,
  274. planid: res.id,
  275. type: cla.type,
  276. };
  277. await this.clamodel.create(newdata);
  278. }
  279. } else {
  280. if (
  281. batchnum.class ===
  282. trainplanold.termnum.id(el.id).batchnum.id(batchnum.id).class
  283. ) {
  284. // 编辑只会针对班级人数进行修改。
  285. const _class = await this.clamodel.find({
  286. termid: el.id,
  287. batchid: batchnum.id,
  288. });
  289. if (_class.length !== 0) {
  290. for (const ee of _class) {
  291. ee.number = batchnum.number;
  292. await ee.save();
  293. }
  294. } else {
  295. const classnum = batchnum.class;
  296. for (const cla of classnum) {
  297. const newdata = {
  298. name: cla.name,
  299. number: cla.number,
  300. batchid: batchnum.id,
  301. termid: el.id,
  302. planid: res.id,
  303. type: cla.type,
  304. };
  305. await this.clamodel.create(newdata);
  306. }
  307. }
  308. } else {
  309. // 当班级数有更改时
  310. // 删除所有班级 并重新生成班级
  311. await this.clamodel.deleteMany({
  312. termid: el.id,
  313. batchid: batchnum.id,
  314. });
  315. const classnum = batchnum.class;
  316. for (const cla of classnum) {
  317. const newdata = {
  318. name: cla.name,
  319. number: cla.number,
  320. batchid: batchnum.id,
  321. termid: el.id,
  322. planid: res.id,
  323. type: cla.type,
  324. };
  325. await this.clamodel.create(newdata);
  326. }
  327. }
  328. }
  329. }
  330. }
  331. }
  332. }
  333. // // 将分好的班级重新编排名字
  334. // async autoclassname(res) {
  335. // // 取得所有期id
  336. // const tremid_res = _.map(res.termnum, 'id');
  337. // for (const termid of tremid_res) {
  338. // const classs = await this.clamodel.find({ planid: res.id, termid });
  339. // let i = 0;
  340. // for (const cla of classs) {
  341. // i = i + 1;
  342. // cla.name = i;
  343. // await cla.save();
  344. // }
  345. // }
  346. // }
  347. async exportExcel({ trainplanIds }) {
  348. const nowDate = new Date().getTime();
  349. const path =
  350. 'D:\\wwwroot\\service\\service-file\\upload\\train\\' + nowDate + '.xlsx';
  351. const respath =
  352. 'http://free.liaoningdoupo.com:80/files/train/' + nowDate + '.xlsx';
  353. const wb = {
  354. SheetNames: [],
  355. Sheets: {},
  356. };
  357. for (let i = 0; i < trainplanIds.length; i++) {
  358. // 批次期次都在这里面
  359. const trainplan = await this.model.findOne({ _id: trainplanIds[i] });
  360. // 这个计划下所有的学生
  361. const studentList = await this.stumodel.find({ planid: trainplanIds[i] });
  362. // 计划名称
  363. const trainplandName = trainplan.title;
  364. // 在计划中找到这个学生在哪期以及哪期下的哪批次
  365. for (const student of studentList) {
  366. student.isComming = utils.getIsNot(student.isComming);
  367. student.trainplandName = trainplandName;
  368. // 期次
  369. const term = trainplan.termnum.filter(term => {
  370. return term.id === student.termid;
  371. });
  372. if (term.length > 0) {
  373. student.termName = term[0].term;
  374. }
  375. // 批次
  376. if (term.length !== 0) {
  377. const batch = term[0].batchnum.filter(batch => {
  378. return batch.id === student.batchid;
  379. });
  380. if (batch.length > 0) {
  381. student.batchName = JSON.parse(JSON.stringify(batch[0])).name;
  382. }
  383. }
  384. student.is_fine = utils.getIsNot(student.is_fine);
  385. }
  386. const _headers = [
  387. { key: 'trainplandName', title: '计划标题' },
  388. { key: 'termName', title: '期次' },
  389. { key: 'batchName', title: '批次' },
  390. { key: 'school_name', title: '学校' },
  391. { key: 'faculty', title: '院系' },
  392. { key: 'major', title: '专业' },
  393. { key: 'name', title: '姓名' },
  394. { key: 'id_number', title: '身份证号' },
  395. { key: 'phone', title: '手机号' },
  396. { key: 'gender', title: '性别' },
  397. { key: 'nation', title: '民族' },
  398. { key: 'edua_level', title: '学历层次' },
  399. { key: 'edua_system', title: '学制' },
  400. { key: 'entry_year', title: '入学年份' },
  401. { key: 'finish_year', title: '毕业年份' },
  402. { key: 'school_job', title: '在校职务' },
  403. { key: 'qq', title: 'QQ号' },
  404. { key: 'email', title: '邮箱' },
  405. // { key: 'openid', title: '微信openid' },
  406. { key: 'family_place', title: '家庭位置' },
  407. { key: 'family_is_hard', title: '是否困难' },
  408. { key: 'have_grant', title: ' 是否获得过助学金' },
  409. // { key: 'job', title: '职务' },
  410. { key: 'bedroom', title: '寝室号' },
  411. { key: 'is_fine', title: '是否优秀' },
  412. { key: 'isComming', title: '是否签到' },
  413. { key: 'selfscore', title: '个人分' },
  414. { key: 'score', title: '总分' },
  415. ];
  416. // 需要打出的列表
  417. const _data = studentList;
  418. const headers = _headers
  419. .map(({ title }) => title)
  420. .map((v, i) =>
  421. Object.assign({}, { v, position: String.fromCharCode(65 + i) + 1 })
  422. )
  423. .reduce(
  424. (prev, next) =>
  425. Object.assign({}, prev, { [next.position]: { v: next.v } }),
  426. {}
  427. );
  428. const data = _data
  429. .map((v, i) =>
  430. _headers.map(({ key }, j) =>
  431. Object.assign(
  432. {},
  433. { v: v[key], position: String.fromCharCode(65 + j) + (i + 2) }
  434. )
  435. )
  436. )
  437. .reduce((prev, next) => prev.concat(next))
  438. .reduce(
  439. (prev, next) =>
  440. Object.assign({}, prev, { [next.position]: { v: next.v } }),
  441. {}
  442. );
  443. // 合并 headers 和 data
  444. const output = Object.assign({}, headers, data);
  445. // 获取所有单元格的位置
  446. const outputPos = Object.keys(output);
  447. // 计算出范围
  448. const ref = outputPos[0] + ':' + outputPos[outputPos.length - 1];
  449. // 构建 workbook 对象
  450. wb.SheetNames.push('sheet' + i);
  451. wb.Sheets['sheet' + i] = Object.assign({}, output, { '!ref': ref });
  452. }
  453. // 导出 Excel
  454. XLSX.writeFile(wb, path);
  455. return respath;
  456. }
  457. // 导出学校大表
  458. async exportSchool({ trainplanId }) {
  459. // 备注
  460. const remarks = [];
  461. // 期数
  462. let termCount = [];
  463. // 班级数
  464. const classCount = [];
  465. // 日期
  466. const studyTime = [];
  467. // 合并单元格坐标
  468. const colRows = [];
  469. // 列起始
  470. let colzb = 3;
  471. // 行起始
  472. const rowzb = 1;
  473. // const colRow = {
  474. // s: { c: 3, r: rowzb },
  475. // e: { c: 6, r: rowzb },
  476. // };
  477. // colRows.push(colRow);
  478. const shcoolList = [];
  479. // 计划表
  480. const trainplan = await this.model.findOne({ _id: trainplanId });
  481. // 学校报名表
  482. const schtime = await this.schmodel.find({ planid: trainplanId });
  483. // 期次
  484. const termnums = trainplan.termnum;
  485. // 学校学校数据
  486. // const schools = trainplan.school;
  487. const schools = await this.smodel.find({});
  488. // 组装学校数据
  489. for (let i = 0; i < schools.length; i++) {
  490. // 学校数据
  491. const shcool = [];
  492. // 序号
  493. shcool.push(i + 1);
  494. // 学校名
  495. shcool.push(schools[i].name);
  496. // 总人数
  497. shcool.push('');
  498. for (const termnum of termnums) {
  499. // 批次
  500. const batchnum = termnum.batchnum;
  501. // 期次所占的格(期占格)
  502. const qizhange = batchnum.length - 1;
  503. /**
  504. * 合并单元格元素(decode_range方法解析数据格式)
  505. {
  506. s: { //s start 开始
  507. c: 1,//cols 开始列
  508. r: 0 //rows 开始行
  509. },
  510. e: {//e end 结束
  511. c: 4,//cols 结束列
  512. r: 0 //rows 结束行
  513. }
  514. }
  515. */
  516. // 添加坐标
  517. const colRow = {
  518. s: { c: colzb, r: rowzb },
  519. e: { c: colzb + qizhange, r: rowzb },
  520. };
  521. // colzb为上一次终止,那么起始需+1,
  522. colzb = colzb + qizhange + 1;
  523. colRows.push(colRow);
  524. // 向其中加入空格,以备合并单元格使用
  525. const qi = [];
  526. qi.push(termnum.term);
  527. for (let index = 0; index < qizhange; index++) {
  528. qi.push('');
  529. }
  530. termCount = [ ...termCount, ...qi ];
  531. // 循环
  532. for (const batch of batchnum) {
  533. // 把班级数与日期放入数组中
  534. classCount.push(batch.class.length);
  535. let startDate = batch.startdate;
  536. startDate = startDate.substr(5, 2) + '.' + startDate.substr(8, 2);
  537. let endDate = batch.enddate;
  538. endDate = endDate.substr(5, 2) + '.' + endDate.substr(8, 2);
  539. studyTime.push(startDate + '-' + endDate);
  540. // 拿着batch的id去schtime表中的arrange中查remark,将结果存入remarks中即可完成备注数组
  541. let remark = '';
  542. for (const sch of schtime) {
  543. // 计划中学校的code=上报时的code
  544. if (schools[i].code === sch.schid) {
  545. for (const arrange of sch.arrange) {
  546. if (arrange.batchid === batch.id) {
  547. remark = arrange.remark;
  548. // 查到了退出即可因为是个数组
  549. // 总人数
  550. shcool.push(arrange.number);
  551. }
  552. }
  553. }
  554. }
  555. remarks.push(remark);
  556. }
  557. }
  558. shcoolList.push(shcool);
  559. }
  560. const wscols = [
  561. { wpx: 50 }, // 第一列宽度设置单位px
  562. ];
  563. let xuhao = [ XLSX.utils.decode_range('A1:A4') ];
  564. const xuexiao = [ XLSX.utils.decode_range('B1:B4') ];
  565. xuhao = [ ...xuhao, ...xuexiao, ...colRows ];
  566. // console.log(xuhao);
  567. const data = [];
  568. // 第一行
  569. const row0 = [ '序号', '学校名称', '备注' ].concat(remarks);
  570. data.push(row0);
  571. // 第二行
  572. const row1 = [ '', '', '期数' ].concat(termCount);
  573. data.push(row1);
  574. // 第三行
  575. const row2 = [ '', '', '班级数' ].concat(classCount);
  576. data.push(row2);
  577. // 第四行
  578. const row3 = [ '', '', '日期' ].concat(studyTime);
  579. data.push(row3);
  580. for (const shcoolL of shcoolList) {
  581. let count = 0;
  582. for (let i = 3; i < shcoolL.length; i++) {
  583. count += parseInt(shcoolL[i]);
  584. }
  585. // 计算出总人数,开始总认识默认的是'',这里赋值
  586. shcoolL[2] = count;
  587. data.push(shcoolL);
  588. }
  589. // ...以此类推即可
  590. /** 头部-行列信息*/
  591. const ws = XLSX.utils.aoa_to_sheet(data);
  592. // 构建 workbook 对象
  593. const nowDate = new Date().getTime();
  594. const path =
  595. 'D:\\wwwroot\\service\\service-file\\upload\\train\\' + nowDate + '.xlsx';
  596. const respath =
  597. 'http://free.liaoningdoupo.com:80/files/train/' + nowDate + '.xlsx';
  598. // 导出
  599. const wb = XLSX.utils.book_new();
  600. XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
  601. ws['!cols'] = wscols;
  602. // xuhao.push(XLSX.utils.decode_range('B1:D1')) // 测试数据 仓库1模拟数据
  603. ws['!merges'] = xuhao;
  604. // console.log(xuhao);
  605. XLSX.writeFile(wb, path);
  606. return respath;
  607. }
  608. // 导出学校大表
  609. async exportPlan({ trainplanId }) {
  610. const wscols = [
  611. { wpx: 50 }, // 第一列宽度设置单位px
  612. ];
  613. const monthList = [];
  614. // 月份合并单元格
  615. const colzb = 0;
  616. let rowzb = 1;
  617. // 头部合并单元格
  618. const coltb = 0;
  619. let rowtb = 0;
  620. // 人数合并单元格
  621. const colrs = 0;
  622. let rowrs = 1;
  623. // 人数数量合并单元格
  624. const colrssl = 0;
  625. let rowrssl = 3;
  626. // 班级数合并单元格
  627. const colbjs = 0;
  628. let rowbjs = 1;
  629. // 班级数数量合并单元格
  630. const colbjssl = 0;
  631. let rowbjssl = 3;
  632. // 数据
  633. const data = [];
  634. let colRowBJSSL = {};
  635. // 这里是头部颜色
  636. const tatleCell = { v: '', s: { fill: { fgColor: { rgb: '191970' } } } };
  637. // 坐标
  638. const tatleCellstyle = 0;
  639. let tatleRowstyle = 0;
  640. const styleTatle = [];
  641. // 这里是月份颜色
  642. const monthCell = [
  643. { v: '一月', s: { fill: { fgColor: { rgb: 'B0E2FF' } } } },
  644. { v: '二月', s: { fill: { fgColor: { rgb: 'B0E2FF' } } } },
  645. { v: '三月', s: { fill: { fgColor: { rgb: 'B0E2FF' } } } },
  646. { v: '四月', s: { fill: { fgColor: { rgb: 'B0E2FF' } } } },
  647. { v: '五月', s: { fill: { fgColor: { rgb: 'B0E2FF' } } } },
  648. { v: '六月', s: { fill: { fgColor: { rgb: 'B0E2FF' } } } },
  649. { v: '七月', s: { fill: { fgColor: { rgb: 'B0E2FF' } } } },
  650. { v: '八月', s: { fill: { fgColor: { rgb: 'B0E2FF' } } } },
  651. { v: '九月', s: { fill: { fgColor: { rgb: 'B0E2FF' } } } },
  652. { v: '十月', s: { fill: { fgColor: { rgb: 'B0E2FF' } } } },
  653. { v: '十一月', s: { fill: { fgColor: { rgb: 'B0E2FF' } } } },
  654. { v: '十二月', s: { fill: { fgColor: { rgb: 'B0E2FF' } } } },
  655. ];
  656. // 坐标
  657. const monthCellstyle = 0;
  658. let monthRowstyle = 1;
  659. const styleMonth = [];
  660. // 这里是假期颜色
  661. const festivalsCell = {
  662. v: '',
  663. s: { fill: { fgColor: { rgb: 'A2CD5A' } } },
  664. };
  665. // 坐标
  666. const festivalsCellstyle = 0;
  667. let festivalsRowstyle = 0;
  668. const stylefestivals = [];
  669. // 计划表
  670. const trainplan = await this.model.findOne({ _id: trainplanId });
  671. const termnum = trainplan.termnum;
  672. let classNum = 0;
  673. // 获取最大的班级数,也就是月份的高
  674. for (const term of termnum) {
  675. if (term.classnum > classNum) {
  676. classNum = parseInt(term.classnum);
  677. }
  678. }
  679. // 得到所有的节日日期的数组,然后循环时注意得到一个删除一个
  680. const festivals = trainplan.festivals;
  681. const festivalList = this.getfestivalList(festivals);
  682. console.log(utils.begindateEnddateSum('2020-01-25', '2020-02-05'));
  683. const termnumList = this.gettermnumList(termnum);
  684. // console.log(termnumList);
  685. // 得到所有班级的数组,然后循环时注意得到一个删除一个
  686. // 循环12个月,得到12个月以及每个月的数据
  687. for (let index = 1; index < 13; index++) {
  688. // 这里增加表格头部下标
  689. const tatleCells = XLSX.utils.encode_cell({
  690. c: tatleCellstyle,
  691. r: tatleRowstyle,
  692. });
  693. tatleRowstyle = tatleRowstyle + classNum + 3;
  694. styleTatle.push(tatleCells);
  695. // 这里是月份颜色
  696. const monthCells = XLSX.utils.encode_cell({
  697. c: monthCellstyle,
  698. r: monthRowstyle,
  699. });
  700. monthRowstyle = monthRowstyle + classNum + 3;
  701. styleMonth.push(monthCells);
  702. for (let j = 0; j < festivalList.length; j++) {
  703. const festival = festivalList[j];
  704. // console.log(festival);
  705. // 如果月份相同时才会增加
  706. const yue = parseInt(festival.substr(5, 2));
  707. const lie = parseInt(festival.substr(8, 2));
  708. if (index === yue) {
  709. // 这里是假期颜色这一列列7行都是这个颜色
  710. for (let k = 0; k < classNum; k++) {
  711. const festivalsCells = XLSX.utils.encode_cell({
  712. // 列
  713. c: festivalsCellstyle + lie,
  714. r: festivalsRowstyle + k + 3,
  715. });
  716. stylefestivals.push(festivalsCells);
  717. }
  718. }
  719. }
  720. festivalsRowstyle = festivalsRowstyle + classNum + 3;
  721. // console.log(stylefestivals);
  722. // 添加月份坐标
  723. const colRow = {
  724. s: { c: colzb, r: rowzb },
  725. // 保证留下7个空行,如果需要在上面加值,直接在下面加入即可第几空行加入就行
  726. e: { c: colzb, r: rowzb + classNum + 1 },
  727. };
  728. // rowzb为上一次终止,那么起始需+1,这里加3,代表头部+月份+星期,所以+3
  729. rowzb = rowzb + classNum + 3;
  730. monthList.push(colRow);
  731. // 添加头部坐标
  732. const colRowTB = {
  733. s: { c: coltb, r: rowtb },
  734. // 保证留下7个空行,如果需要在上面加值,直接在下面加入即可第几空行加入就行
  735. e: { c: coltb + 33, r: rowtb },
  736. };
  737. // rowzb为上一次终止,那么起始需+1,
  738. rowtb = rowtb + classNum + 3;
  739. monthList.push(colRowTB);
  740. // 添加人数坐标
  741. const colRowRS = {
  742. s: { c: colrs + 32, r: rowrs },
  743. // 保证留下7个空行,如果需要在上面加值,直接在下面加入即可第几空行加入就行
  744. e: { c: colrs + 32, r: rowrs + 1 },
  745. };
  746. // rowzb为上一次终止,那么起始需+1,
  747. rowrs = rowrs + classNum + 3;
  748. monthList.push(colRowRS);
  749. // 添加人数数量坐标
  750. const colRowRSSL = {
  751. s: { c: colrssl + 32, r: rowrssl },
  752. // 保证留下7个空行,如果需要在上面加值,直接在下面加入即可第几空行加入就行
  753. e: { c: colrssl + 32, r: rowrssl + classNum - 1 },
  754. };
  755. // rowzb为上一次终止,那么起始需+1,
  756. rowrssl = rowrssl + classNum + 3;
  757. monthList.push(colRowRSSL);
  758. // 添加班级数坐标
  759. const colRowBJS = {
  760. s: { c: colbjs + 33, r: rowbjs },
  761. // 保证留下7个空行,如果需要在上面加值,直接在下面加入即可第几空行加入就行
  762. e: { c: colbjs + 33, r: rowbjs + 1 },
  763. };
  764. // rowzb为上一次终止,那么起始需+1,
  765. rowbjs = rowbjs + classNum + 3;
  766. monthList.push(colRowBJS);
  767. // 添加班级数数量坐标
  768. colRowBJSSL = {
  769. s: { c: colbjssl + 33, r: rowbjssl },
  770. // 保证留下7个空行,如果需要在上面加值,直接在下面加入即可第几空行加入就行
  771. e: { c: colbjssl + 33, r: rowbjssl + classNum - 1 },
  772. };
  773. // rowzb为上一次终止,那么起始需+1,
  774. rowbjssl = rowbjssl + classNum + 3;
  775. monthList.push(colRowBJSSL);
  776. const resDate = this.makeCalendar(trainplan.year, index);
  777. data.push([ '' ]);
  778. data.push(
  779. [[ this.getBigMonth(index) + '月' ]]
  780. .concat(resDate.dlist)
  781. .concat([ '人数' ].concat([ '班级数' ]))
  782. );
  783. data.push([ '' ].concat(resDate.tlist));
  784. // 加列数组
  785. for (let i = 0; i < classNum; i++) {
  786. data.push('');
  787. }
  788. }
  789. // ...以此类推即可
  790. /** 头部-行列信息*/
  791. const ws = XLSX.utils.aoa_to_sheet(data);
  792. // 构建 workbook 对象
  793. const nowDate = new Date().getTime();
  794. const path =
  795. 'D:\\wwwroot\\service\\service-file\\upload\\train\\' + nowDate + '.xlsx';
  796. const respath =
  797. 'http://free.liaoningdoupo.com:80/files/train/' + nowDate + '.xlsx';
  798. // 导出
  799. const wb = XLSX.utils.book_new();
  800. XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
  801. ws['!cols'] = wscols;
  802. ws['!merges'] = monthList;
  803. // 头部赋值颜色需要计算出坐标
  804. for (const tatlezb of styleTatle) {
  805. ws[tatlezb] = tatleCell;
  806. }
  807. // 月份赋值颜色需要计算出坐标
  808. for (let index = 0; index < styleMonth.length; index++) {
  809. ws[styleMonth[index]] = monthCell[index];
  810. }
  811. // 假期赋值颜色需要计算出坐标
  812. for (const festivals of stylefestivals) {
  813. ws[festivals] = festivalsCell;
  814. }
  815. XLSXStyle.writeFile(wb, path);
  816. return respath;
  817. }
  818. // 获取批次日期列表
  819. gettermnumList(termnums) {
  820. const termnumList = [];
  821. for (const termnum of termnums) {
  822. termnum.term;
  823. termnum.classnum;
  824. for (const batchnum of termnum.batchnum) {
  825. batchnum.batch;
  826. batchnum.class.length;
  827. batchnum.startdate;
  828. batchnum.enddate;
  829. }
  830. }
  831. return termnumList;
  832. }
  833. // 获取节假日集合
  834. getfestivalList(festivals) {
  835. let dateList = [];
  836. for (let index = 0; index < festivals.length; index++) {
  837. dateList = [
  838. ...dateList,
  839. ...utils.begindateEnddateSum(
  840. festivals[index].begindate,
  841. festivals[index].finishdate
  842. ),
  843. ];
  844. }
  845. return dateList;
  846. }
  847. // 获取大月份传过来的值是以1月份开始的
  848. getBigMonth(index) {
  849. const monthBig = [
  850. '一',
  851. '二',
  852. '三',
  853. '四',
  854. '五',
  855. '六',
  856. '七',
  857. '八',
  858. '九',
  859. '十',
  860. '十一',
  861. '十二',
  862. ];
  863. return monthBig[index - 1];
  864. }
  865. // 获取这个月份的所有日期1~30号或者31或者28,或者29
  866. makeCalendar(year, month = 1, month0) {
  867. month0 = month;
  868. if (month * 1 < 10) month = '0' + month;
  869. // 获取这个月份的最大值
  870. const days = moment(year + '-' + month).daysInMonth();
  871. const dlist = this.getDayList(year, month, days, month0);
  872. while (dlist.dlist.length < 31) {
  873. dlist.dlist.push('');
  874. }
  875. return dlist;
  876. }
  877. // 获取这个月份的1-30号经过加工的
  878. getDayList(year, month, days, month0) {
  879. const dlist = [];
  880. const tlist = [];
  881. const all = {};
  882. for (let index = 0; index < days; index++) {
  883. dlist.push(
  884. month0 +
  885. '月' +
  886. moment(year + '-' + month)
  887. .add(index, 'days')
  888. .format('D') +
  889. '日'
  890. );
  891. let dayy = parseInt(index + 1);
  892. if (dayy * 1 < 10) dayy = '0' + dayy;
  893. tlist.push(this.getWeekDay(year + '-' + month + '-' + dayy));
  894. }
  895. all.dlist = dlist;
  896. all.tlist = tlist;
  897. return all;
  898. }
  899. // 获取星期几
  900. getWeekDay(datestr) {
  901. const weekday = moment(datestr).weekday();
  902. if (weekday || weekday === 0) {
  903. // console.log(weekday);
  904. const arr = [ '日', '一', '二', '三', '四', '五', '六' ];
  905. return '星期' + arr[weekday];
  906. }
  907. return '';
  908. }
  909. // async updateclass({ trainplanid, classid, rightHeader }) {
  910. // assert(trainplanid && classid && rightHeader, '缺少参数项');
  911. async updateclass({ trainplanid, termid, batchid, classid, rightHeader }) {
  912. assert(
  913. trainplanid && termid && batchid && classid && rightHeader,
  914. '缺少参数项'
  915. );
  916. // 根据全年计划表id查出对应的全年计划详细信息
  917. const trainplan = await this.model.findById(trainplanid);
  918. if (!trainplan) {
  919. throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '全年计划信息不存在');
  920. }
  921. const term = trainplan.termnum.id(termid);
  922. if (!term) {
  923. throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '期信息不存在');
  924. }
  925. const batch = term.batchnum.id(batchid);
  926. if (!batch) {
  927. throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '批次信息不存在');
  928. }
  929. const class_ = await batch.class.id(classid);
  930. if (class_) {
  931. class_.headteacherid = rightHeader;
  932. }
  933. const res = await trainplan.save();
  934. if (res) {
  935. const cla_ = await this.clamodel.findOne({
  936. termid,
  937. batchid,
  938. name: class_.name,
  939. });
  940. if (cla_) {
  941. cla_.headteacherid = rightHeader;
  942. await cla_.save();
  943. }
  944. }
  945. return res;
  946. }
  947. async updatereteacher({ trainplanid, termid, reteacher }) {
  948. assert(trainplanid && termid && reteacher, '缺少参数项');
  949. // 根据全年计划表id查出对应的全年计划详细信息
  950. const trainplan = await this.model.findById(trainplanid);
  951. if (!trainplan) {
  952. throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '全年计划信息不存在');
  953. }
  954. const term = await trainplan.termnum.id(termid);
  955. if (term) {
  956. term.reteacher = reteacher;
  957. }
  958. return await trainplan.save();
  959. }
  960. }
  961. module.exports = TrainplanService;