package com.ruoyi.project.training.controller; import com.deepoove.poi.XWPFTemplate; import com.deepoove.poi.data.*; import com.deepoove.poi.data.style.CellStyle; import com.deepoove.poi.data.style.TableStyle; import com.ruoyi.common.utils.DateUtils; import com.ruoyi.common.utils.DictUtils; import com.ruoyi.common.utils.file.FileUploadUtils; import com.ruoyi.common.utils.file.FileUtils; import com.ruoyi.common.utils.poi.ExcelUtil; import com.ruoyi.framework.aspectj.lang.annotation.Log; import com.ruoyi.framework.aspectj.lang.enums.BusinessType; import com.ruoyi.framework.config.RuoYiConfig; import com.ruoyi.framework.web.controller.BaseController; import com.ruoyi.framework.web.domain.AjaxResult; import com.ruoyi.framework.web.page.TableDataInfo; import com.ruoyi.project.officeConvert.OfficeConvertController; import com.ruoyi.project.plant.domain.TStaffmgr; import com.ruoyi.project.plant.service.ITStaffmgrService; import com.ruoyi.project.system.domain.SysUser; import com.ruoyi.project.system.mapper.SysUserMapper; import com.ruoyi.project.document.domain.TPlantproglist; import com.ruoyi.project.document.service.ITPlantproglistService; import com.ruoyi.project.training.domain.TTrainingbcc; import com.ruoyi.project.training.domain.TTrainingbccDevice; import com.ruoyi.project.training.mapper.TTrainingbccDeviceMapper; import com.ruoyi.project.training.mapper.TTrainingbccMapper; import com.ruoyi.project.training.service.ITTrainingbccService; import io.jsonwebtoken.lang.Assert; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * 装置培训跟踪bController * * @author ssy * @date 2024-06-19 */ @RestController @RequestMapping("/training/trainingbcc") public class TTrainingbccController extends BaseController { @Autowired private ITTrainingbccService tTrainingbccService; @Resource private TTrainingbccDeviceMapper tTrainingbccDeviceMapper; @Resource private TTrainingbccMapper tTrainingbccMapper; @Autowired private ITStaffmgrService tStaffmgrService; @Autowired private SysUserMapper sysUserMapper; @Autowired private ITPlantproglistService tPlantproglistService; @Resource private OfficeConvertController officeConvertController; /** * 查询装置培训跟踪b列表 */ @GetMapping("/list") public TableDataInfo list(TTrainingbcc tTrainingbcc) { startPage(); List list = tTrainingbccService.selectTTrainingbccList(tTrainingbcc); for (TTrainingbcc t : list ) { TTrainingbccDevice device = new TTrainingbccDevice(); device.setRegularId(t.getId()); int all = tTrainingbccDeviceMapper.countTraining(device); device.setExamState(1l); int finish = tTrainingbccDeviceMapper.countTraining(device); t.setHaveTraining(finish); t.setMustTraining(all); if (all != 0) { String per = String.valueOf(finish * 100 / all); t.setTrainingPercent(per); } else { t.setTrainingPercent("0"); } // 检查统计数据与isFinish字段的一致性,不一致则更新 boolean shouldBeFinished = (all > 0 && finish == all); // 有培训人员且全部完成 boolean currentIsFinish = (t.getIsfinish() != null && t.getIsfinish() == 1L); // 当前标记为完成 if (shouldBeFinished != currentIsFinish) { // 不一致,更新isFinish字段 Long newIsFinish = shouldBeFinished ? 1L : 0L; t.setIsfinish(newIsFinish); // 更新数据库中的isFinish字段 TTrainingbcc updateParam = new TTrainingbcc(); updateParam.setId(t.getId()); updateParam.setIsfinish(newIsFinish); tTrainingbccService.updateTTrainingbcc(updateParam); logger.info("更新培训完成状态 - 培训ID: {}, 原状态: {}, 新状态: {}, 统计: {}/{}", t.getId(), currentIsFinish ? "完成" : "未完成", shouldBeFinished ? "完成" : "未完成", finish, all); } } return getDataTable(list); } /** * 导出装置培训跟踪b列表 */ @PreAuthorize("@ss.hasPermi('training:trainingbcc:export')") @Log(title = "装置培训跟踪b", businessType = BusinessType.EXPORT) @GetMapping("/export") public AjaxResult export(TTrainingbcc tTrainingbcc) { List list = tTrainingbccService.selectTTrainingbccList(tTrainingbcc); ExcelUtil util = new ExcelUtil(TTrainingbcc.class); return util.exportExcel(list, "trainingbcc"); } /** * 获取装置培训跟踪b详细信息 */ @PreAuthorize("@ss.hasPermi('training:trainingbcc:query')") @GetMapping(value = "/{id}") public AjaxResult getInfo(@PathVariable("id") Long id) { return AjaxResult.success(tTrainingbccService.selectTTrainingbccById(id)); } /** * 获取装置培训跟踪b详细信息 */ @PreAuthorize("@ss.hasPermi('training:trainingbcc:query')") @GetMapping(value = "/staffIds/{id}") public AjaxResult getStaffIds(@PathVariable("id") Long id) { TTrainingbcc tTrainingbcc = tTrainingbccService.selectTTrainingbccById(id); TTrainingbccDevice param = new TTrainingbccDevice(); param.setRegularId(id); List list = tTrainingbccDeviceMapper.selectTTrainingbccDeviceList(param); String staffIds = ""; for (TTrainingbccDevice t : list ) { staffIds = staffIds + "," + t.getStaffId(); } tTrainingbcc.setStaffIds(staffIds); return AjaxResult.success(tTrainingbcc); } /** * 新增装置培训跟踪b */ @PreAuthorize("@ss.hasPermi('training:trainingbcc:add')") @Log(title = "装置培训跟踪b", businessType = BusinessType.INSERT) @PostMapping public AjaxResult add(@RequestBody TTrainingbcc tTrainingbcc) { tTrainingbccService.insertTTrainingbcc(tTrainingbcc); //培训岗位人员 if (tTrainingbcc.getPosition() != null) { TStaffmgr s = new TStaffmgr(); s.setActualposts(tTrainingbcc.getPosition()); s.setDeptId(103l); List trainingStaff = tStaffmgrService.selectAllTStaffmgrList(s); try { //判断离职 if (!org.apache.commons.lang.StringUtils.isEmpty(tTrainingbcc.getYears())) { Iterator iterator = trainingStaff.iterator(); while (iterator.hasNext()) { TStaffmgr t = iterator.next(); if (t.getLeftDate() != null && t.getDelFlag() == 9) { if (t.getLeftDate().getTime() - tTrainingbcc.getCourseStartdate().getTime() < 0l) { logger.debug(t.getName() + "离职时间小于培训时间"); iterator.remove(); } } } } } catch (Exception e) { logger.error(e.toString()); } for (TStaffmgr staff : trainingStaff) { TTrainingbccDevice tTrainingDevice = new TTrainingbccDevice(); tTrainingDevice.setStaffId(staff.getStaffid()); tTrainingDevice.setRegularId(tTrainingbcc.getId()); tTrainingDevice.setStartDate(tTrainingbcc.getCourseStartdate()); tTrainingDevice.setSupplementary("0"); tTrainingbccDeviceMapper.insertTTrainingbccDevice(tTrainingDevice); } } return toAjax(1); } /** * 修改装置培训跟踪b */ @PreAuthorize("@ss.hasPermi('training:trainingbcc:edit')") @Log(title = "装置培训跟踪b", businessType = BusinessType.UPDATE) @PutMapping public AjaxResult edit(@RequestBody TTrainingbcc tTrainingbcc) { return toAjax(tTrainingbccService.updateTTrainingbcc(tTrainingbcc)); } /** * 修改装置培训跟踪b */ @PreAuthorize("@ss.hasPermi('training:trainingbcc:edit')") @Log(title = "装置培训跟踪b", businessType = BusinessType.UPDATE) @PostMapping(value = "/updateStaffIds") public AjaxResult updateStaffIds(@RequestBody TTrainingbcc tTrainingbcc) { return toAjax(tTrainingbccService.updateStaffIds(tTrainingbcc)); } /** * 删除装置培训跟踪b */ @PreAuthorize("@ss.hasPermi('training:trainingbcc:remove')") @Log(title = "装置培训跟踪b", businessType = BusinessType.DELETE) @DeleteMapping("/{ids}") public AjaxResult remove(@PathVariable Long[] ids) { tTrainingbccDeviceMapper.deleteTTrainingbccDeviceByTrainingbcc(ids); return toAjax(tTrainingbccService.deleteTTrainingbccByIds(ids)); } @Log(title = "附件上传", businessType = BusinessType.UPDATE) @PostMapping("/uploadFile/{id}") public AjaxResult uploadFile(@RequestParam("file") MultipartFile file, @PathVariable Long id) throws IOException { if (!file.isEmpty()) { // 获取当前日期 LocalDate currentDate = LocalDate.now(); // 获取年份 int year = currentDate.getYear(); // 获取月份 int month = currentDate.getMonthValue(); String dir = "/elearn/" + year; String url = FileUploadUtils.upload(RuoYiConfig.getFilePath(dir), file); TTrainingbcc entity = tTrainingbccService.selectTTrainingbccById(id); entity.setFileUrl(url); entity.setFileName(file.getOriginalFilename()); tTrainingbccService.updateTTrainingbcc(entity); return AjaxResult.success(id); } return AjaxResult.error("上传失败,请联系管理员"); } @PreAuthorize("@ss.hasPermi('pssr:subcontent:export')") @Log(title = "导出签名表", businessType = BusinessType.EXPORT) @GetMapping("/exportSign") public AjaxResult exportSign(TTrainingbcc tTrainingbcc) throws Exception { TTrainingbcc tTraining = tTrainingbccMapper.selectTTrainingbccById(tTrainingbcc.getId()); String tempUrl = ""; // 模板路径 if (tTraining.getTrainingType().equals("20")) { tempUrl = "static/word/training/signMOCbcc.docx"; // 模板文件 } else { tempUrl = "static/word/training/signbcc.docx"; // 模板文件 } //渲染文本 Map params = getWordData(tTraining); // 生成word的路径 String fileDir = RuoYiConfig.getProfile() + "/" + "tTrainingbcc"; // 生成word的文件名称 String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss")); String fileName = time + tTraining.getId() + "_" + DateUtils.getDate() + ".docx"; String wordPath = createWord(tempUrl, fileDir, fileName, params, "tTrainingbcc"); return AjaxResult.success(officeConvertController.wordTransPdf(wordPath)); } public Map getWordData(TTrainingbcc trainingbcc) { Map params = new HashMap<>(); TableRenderData tableRenderData = new TableRenderData(); TableStyle tableStyle = new TableStyle(); tableStyle.setWidth("100%"); tableStyle.setColWidths(new int[]{8, 10, 10, 12, 10, 8, 10, 10, 12, 10}); tableRenderData.setTableStyle(tableStyle); // 创建表头行 RowRenderData row1 = Rows.of("序号", "姓名", "部门", "签名", "日期", "序号", "姓名", "部门", "签名", "日期").center().textBold().rowExactHeight(1.1f).create(); tableRenderData.addRow(row1); int plant = 0, ctm = 0, cta = 0, count = 1; PictureRenderData plantMgr = null; TTrainingbccDevice tTrainingbccDevice = new TTrainingbccDevice(); tTrainingbccDevice.setRegularId(trainingbcc.getId()); List list = tTrainingbccDeviceMapper.sortSelectTTrainingbccDeviceList(tTrainingbccDevice); for (int i = 0; i < list.size(); i++) { TTrainingbccDevice t1 = list.get(i); for (int j = i+1; j < list.size(); j++) { TTrainingbccDevice t2 = list.get(j); if (t1.getName().equals(t2.getName())) { t1.setName(t1.getName() +"1"); t2.setName(t2.getName() + "2"); } } } for (int i = 0; i < list.size(); i++) { //如果当前行为偶数,直接开始下一行 if (i % 2 != 0) { continue; } TTrainingbccDevice device = list.get(i); TTrainingbccDevice device2 = null; if (i < list.size() - 1) { device2 = list.get(i + 1); } SysUser user1 = sysUserMapper.selectUserByStaffId(device.getStaffId()); SysUser user2 = null; if (device2 != null) { user2 = sysUserMapper.selectUserByStaffId(device2.getStaffId()); } // 获取员工部门信息 String department1 = "CBP/C"; // 默认值 String department2 = "CBP/C"; // 默认值 if (device.getStaffId() != null) { TStaffmgr staffmgr1 = tStaffmgrService.selectTStaffmgrByStaffId(device.getStaffId()); if (staffmgr1 != null && staffmgr1.getUnit() != null) { department1 = DictUtils.getDictLabel("STAFF_UNIT", staffmgr1.getUnit()); if (department1 == null || department1.isEmpty()) { department1 = "CBP/C"; // 如果字典转换失败,使用默认值 } } } if (device2 != null && device2.getStaffId() != null) { TStaffmgr staffmgr2 = tStaffmgrService.selectTStaffmgrByStaffId(device2.getStaffId()); if (staffmgr2 != null && staffmgr2.getUnit() != null) { department2 = DictUtils.getDictLabel("STAFF_UNIT", staffmgr2.getUnit()); if (department2 == null || department2.isEmpty()) { department2 = "CBP/C"; // 如果字典转换失败,使用默认值 } } } RowRenderData row = null; String lineNum=""; String lineNum2=""; // 创建数据行 lineNum = String.valueOf(i + 1); lineNum2 = String.valueOf(i + 2); if (device2!=null) row = Rows.of(lineNum, device.getName(), department1, "", DateUtils.dateTime(device.getFinishDate()), lineNum2, device2.getName(), department2, "", DateUtils.dateTime(device2.getFinishDate())).verticalCenter().textFontSize(8).rowExactHeight(1.1f).create(); else row = Rows.of(lineNum, device.getName(), department1, "", DateUtils.dateTime(device.getFinishDate()), "", "", "", "", "").verticalCenter().horizontalCenter().textFontSize(8).rowExactHeight(1.1f).create(); if (device.getExamState() == 1) { if (user1 != null) row.getCells().set(3, new CellRenderData().addParagraph(new ParagraphRenderData().addPicture(Pictures.ofLocal(FileUtils.fileName(user1.getSignUrl())).size(60, 20).create()))); } if (device2!=null&&device2.getExamState() == 1) { if (user2 != null) row.getCells().set(8, new CellRenderData().addParagraph(new ParagraphRenderData().addPicture(Pictures.ofLocal(FileUtils.fileName(user2.getSignUrl())).size(60, 20).create()))); } tableRenderData.addRow(row); } // 准备表格数据和其他参数 params.put("course", trainingbcc.getCourse() != null ? trainingbcc.getCourse() : "NA"); // 培训课程名称 params.put("courseid", trainingbcc.getCourseid() != null ? trainingbcc.getCourseid() : "NA"); // 培训材料编号 // 处理培训材料版本:通过courseid查询TPlantproglist获取版本号 String revision = "NA"; if (trainingbcc.getCourseid() != null && !trainingbcc.getCourseid().trim().isEmpty()) { TPlantproglist plantproglist = new TPlantproglist(); plantproglist.setFileno(trainingbcc.getCourseid().trim()); List plantproglistList = tPlantproglistService.selectTPlantproglistList(plantproglist); if (plantproglistList != null && !plantproglistList.isEmpty()) { TPlantproglist matchedPlantproglist = plantproglistList.get(0); if (matchedPlantproglist.getRevision() != null && !matchedPlantproglist.getRevision().trim().isEmpty()) { revision = matchedPlantproglist.getRevision(); } } } params.put("revision", revision); // 培训材料版本 params.put("duration", trainingbcc.getDuration() != null ? trainingbcc.getDuration() : "NA"); // 培训时长 params.put("content", trainingbcc.getContent() != null ? trainingbcc.getContent() : "NA"); // 培训内容 // 处理讲师信息:通过员工号查询讲师姓名 String trainerNames = "NA"; if (trainingbcc.getTrainer() != null && !trainingbcc.getTrainer().trim().isEmpty()) { String[] staffIds = trainingbcc.getTrainer().split(","); StringBuilder trainerNameList = new StringBuilder(); for (String staffId : staffIds) { if (staffId.trim().isEmpty()) continue; TStaffmgr staffmgr = tStaffmgrService.selectTStaffmgrByStaffId(staffId.trim()); if (staffmgr != null && staffmgr.getName() != null) { if (trainerNameList.length() > 0) { trainerNameList.append("、"); } trainerNameList.append(staffmgr.getName()); } } trainerNames = trainerNameList.length() > 0 ? trainerNameList.toString() : "NA"; } params.put("trainer", trainerNames); // 培训讲师姓名 // 处理培训日期:使用斜杠格式 yyyy/MM/dd String courseStartdateStr = ""; if (trainingbcc.getCourseStartdate() != null) { String startDate = DateUtils.parseDateToStr("yyyy/MM/dd", trainingbcc.getCourseStartdate()); if (trainingbcc.getCourseEnddate() != null) { String endDate = DateUtils.parseDateToStr("yyyy/MM/dd", trainingbcc.getCourseEnddate()); // 如果开始和结束日期不同,显示日期范围 if (!startDate.equals(endDate)) { courseStartdateStr = startDate + "-" + endDate; } else { courseStartdateStr = startDate; } } else { courseStartdateStr = startDate; } } params.put("courseStartdate", courseStartdateStr); // 培训日期 params.put("table1", tableRenderData); return params; } private String createWord(String templatePath, String fileDir, String fileName, Map paramMap, String directory) throws IOException { Assert.notNull(templatePath, "word模板文件路径不能为空"); Assert.notNull(fileDir, "生成的文件存放地址不能为空"); Assert.notNull(fileName, "生成的文件名不能为空"); File dir = new File(fileDir); if (!dir.exists()) { logger.info("目录不存在,创建文件夹{}!", fileDir); dir.mkdirs(); } fileName = fileName.replaceAll("/", "_"); //替换文件中敏感字段 logger.info("目录文件{}!", fileName); String filePath = fileDir + "/" + fileName; logger.info("目录{}!", filePath); logger.info("模板{}!", templatePath); // 读取模板渲染参数 InputStream is = getClass().getClassLoader().getResourceAsStream(templatePath); XWPFTemplate template = XWPFTemplate.compile(is).render(paramMap); try { // 将模板参数写入路径 template.writeToFile(filePath); template.close(); is.close(); } catch (Exception e) { logger.error("生成word异常{}", e.getMessage()); e.printStackTrace(); } String pathFileName = FileUploadUtils.getPathFileName(RuoYiConfig.getFilePath("/" + directory), fileName); return pathFileName; } }