trainplan.js 33 KB

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