package com.ruoyi.personnel.service.impl;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.Pictures;
import com.ruoyi.common.core.domain.entity.DepartmentLims;
import com.ruoyi.common.core.domain.entity.User;
import com.ruoyi.common.utils.DateImageUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.exception.ErrorException;
import com.ruoyi.framework.util.HackLoopTableRenderPolicy;
import com.ruoyi.personnel.dto.*;
import com.ruoyi.personnel.excel.PersonTrainingDetailedListener;
import com.ruoyi.personnel.excel.PersonTrainingDetailedUpload;
import com.ruoyi.personnel.mapper.*;
import com.ruoyi.personnel.pojo.*;
import com.ruoyi.personnel.service.PersonTrainingDetailedService;
import com.ruoyi.personnel.service.PersonTrainingService;
import com.ruoyi.system.mapper.DepartmentLimsMapper;
import com.ruoyi.system.mapper.UserMapper;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
/**
*
* 培训计划 服务实现类
*
*
* @author 芯导软件(江苏)有限公司
* @since 2024-10-11 01:11:49
*/
@Service
@Transactional(rollbackFor = Exception.class)
public class PersonTrainingServiceImpl extends ServiceImpl implements PersonTrainingService {
@Autowired
private PersonTrainingDetailedService personTrainingDetailedService;
@Autowired
private UserMapper userMapper;
@Resource
private PersonTrainingDetailedMapper personTrainingDetailedMapper;
@Resource
private PersonTrainingRecordMapper personTrainingRecordMapper;
@Autowired
private DepartmentLimsMapper departmentLimsMapper;
@Value("${file.path}")
private String imgUrl;
@Override
public IPage personTrainingSelect(Page page, String compilerName, Integer departmentId) {
// 当前登录人
Integer userId = SecurityUtils.getUserId().intValue();
// User user = Optional.ofNullable(userMapper.selectById(userId)).orElse(new User());
// if(3==user.getRoleId()){
// departmentId=null;
// }
// 如果传入了departId 就以传入的为准。 如果没有传入就以当前人所在部门为准
if(Objects.isNull(departmentId)) {
User user = userMapper.selectById(userId);
String[] split = user.getDepartLimsId().split(",");
for(String departId : split) {
if(departId != "1" && StringUtils.isNotEmpty(departId)) {
departmentId = Integer.parseInt(departId);
}
}
//todo 待修改 如果当前人是管理员就可查看全部
// if(user.getRoleId() == 3) {
// departmentId = null;
// }
}else {
// 如果传入的departId是1(中天科技) 不做处理
if(departmentId == 1) {
departmentId = null;
}
}
IPage personTrainingDtoIPage = baseMapper.personTrainingSelect(page, compilerName, departmentId);
List records = personTrainingDtoIPage.getRecords();
for (PersonTrainingDto dto : records) {
dto.setCurrentId(userId);
}
return personTrainingDtoIPage;
}
/**
*
* @param id 明细表id
*/
@Override
public void deleteDetail(Integer id) {
personTrainingDetailedMapper.deleteById(id);
personTrainingRecordMapper.delete(Wrappers.lambdaQuery().eq(PersonTrainingRecord::getCourseId,id));
}
@Override
public void personTrainingImport(MultipartFile file) {
int userId = SecurityUtils.getUserId().intValue();
// 年度计划父级新增数据
PersonTraining personSupervisePlan = new PersonTraining();
String fileName = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));
personSupervisePlan.setFileName(fileName);
personSupervisePlan.setCompilerId(userId); // 编制人
personSupervisePlan.setCompilationDate(LocalDateTime.now());
try(Workbook workbook = WorkbookFactory.create(file.getInputStream())) {
// 多个sheet页 得区分一下通信和电力
for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
String sheetName = workbook.getSheetName(i);
// 根据sheet名称来分别给对应的实验室赋值
DepartmentLims departmentLims = departmentLimsMapper.selectOne(Wrappers.lambdaQuery().like(DepartmentLims::getName, sheetName));
if(Objects.nonNull(departmentLims)) {
personSupervisePlan.setDepartId(departmentLims.getId());
// 编制人电力的是胡雪霞 通信的是袁雨露
if(departmentLims.getId().equals(18)) {
personSupervisePlan.setCompilerId(userMapper.selectList(new LambdaQueryWrapper().eq(User::getName,"袁雨露")).get(0).getId());
} else if (departmentLims.getId().equals(19)) {
personSupervisePlan.setCompilerId(userMapper.selectList(new LambdaQueryWrapper().eq(User::getName,"胡雪霞")).get(0).getId());
}
baseMapper.insert(personSupervisePlan);
// 年度计划详情 新增
PersonTrainingDetailedListener personSupervisePlanDetailsListener = new PersonTrainingDetailedListener(personTrainingDetailedService,personSupervisePlan.getId());
personSupervisePlanDetailsListener.setPlanId(personSupervisePlan.getId());
//EasyExcel.read(file.getInputStream(), PersonTrainingDetailedUpload.class, personSupervisePlanDetailsListener).sheet().doRead();
EasyExcel.read(file.getInputStream(),PersonTrainingDetailedUpload.class,new PersonTrainingDetailedListener(personTrainingDetailedService,personSupervisePlan.getId()))
.headRowNumber(3).ignoreEmptyRow(false).sheet(sheetName).doRead();
// 添加一次后 清空id 防止出现重复key
personSupervisePlan.setId(null);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void personTrainingDelete(Integer id) {
personTrainingDetailedService.remove(new LambdaQueryWrapper().eq(PersonTrainingDetailed::getPlanId,id));
baseMapper.deleteById(id);
}
@Override
public void reviewAnnualPersonnelTraining(PersonTrainingUpdateDto personTrainingUpdateDto) {
PersonTraining personTraining = new PersonTraining();
personTraining.setId(personTrainingUpdateDto.getId());
// 如果是通信 审核人就是孙磊 电力的则是刘建德
PersonTraining personTraining1 = baseMapper.selectById(personTrainingUpdateDto.getId());
if(personTraining1.getDepartId().equals(19)) {
personTraining.setReviewerId(userMapper.selectList(new LambdaQueryWrapper().eq(User::getName,"刘建德")).get(0).getId());
}else {
personTraining.setReviewerId(userMapper.selectList(new LambdaQueryWrapper().eq(User::getName,"孙磊")).get(0).getId());
}
personTraining.setAuditDate(LocalDateTime.now());
personTraining.setAuditRemarks(personTrainingUpdateDto.getRemarks());
personTraining.setReviewerStatus(personTrainingUpdateDto.getStatus());
baseMapper.updateById(personTraining);
}
@Override
public void approveAnnualPersonnelTraining(PersonTrainingUpdateDto personTrainingUpdateDto) {
Integer id = userMapper.selectList(new LambdaQueryWrapper().eq(User::getName, "许军")).get(0).getId();
LambdaUpdateWrapper wrapper = Wrappers.lambdaUpdate()
.eq(PersonTraining::getId, personTrainingUpdateDto.getId())
.set(PersonTraining::getApproverId, id) // 只能是许军
.set(PersonTraining::getApprovalDate, LocalDateTime.now())
.set(PersonTraining::getApprovalRemarks, personTrainingUpdateDto.getRemarks())
.set(PersonTraining::getApprovalStatus, personTrainingUpdateDto.getStatus());
if (personTrainingUpdateDto.getStatus().equals(2)) {
wrapper.set(PersonTraining::getReviewerStatus, null);
}
baseMapper.update(new PersonTraining(), wrapper);
}
/**
* 导出人员培训计划
* @param id
* @param response
*/
@Override
public void exportPersonTraining(Integer id, HttpServletResponse response) {
// 查询详情
PersonTraining personTraining = baseMapper.selectById(id);
//获取提交人的签名地址
String writeUrl = userMapper.selectById(personTraining.getCompilerId()).getSignatureUrl();
if (ObjectUtils.isEmpty(writeUrl) || writeUrl.equals("")) {
throw new ErrorException("找不到检验人的签名");
}
//获取复核人的签名地址
String examineUrl = null;
if (personTraining.getReviewerId() != null) {
examineUrl = userMapper.selectById(personTraining.getReviewerId()).getSignatureUrl();
if (StringUtils.isBlank(examineUrl)) {
throw new ErrorException("找不到复核人的签名");
}
}
//获取批准人的签名地址
String ratifyUrl = null;
if (personTraining.getApproverId() != null) {
ratifyUrl = userMapper.selectById(personTraining.getApproverId()).getSignatureUrl();
if (StringUtils.isBlank(ratifyUrl)) {
throw new ErrorException("找不到复核人的签名");
}
}
// 查询详情
List detailedDtos = personTrainingDetailedMapper.selectTrainingList(id);
int index = 1;
for (PersonTrainingDetailedDto detailedDto : detailedDtos) {
detailedDto.setTrainingLecturerName(detailedDto.getTrainingLecturerId());
if (detailedDto.getTrainingDate() != null) {
SimpleDateFormat sdfWithoutTime = new SimpleDateFormat("yyyy-MM-dd");
// detailedDto.setTrainingDateString(sdfWithoutTime.format(detailedDto.getTrainingDate()));
detailedDto.setTrainingDateString(detailedDto.getTrainingDate());
}
DepartmentLims departmentLims = departmentLimsMapper.selectById(detailedDto.getHoldingDepartment());
if(Objects.nonNull(departmentLims)) {
detailedDto.setOrganizingDepartment(departmentLims.getName());
}
detailedDto.setIndex(index);
index++;
}
// 获取路径
InputStream inputStream = this.getClass().getResourceAsStream("/static/person-training.docx");
String finalExamineUrl = examineUrl;
String finalRatifyUrl = ratifyUrl;
Configure configure = Configure.builder()
.bind("trainingDetailedList", new HackLoopTableRenderPolicy())
.build();
XWPFTemplate template = XWPFTemplate.compile(inputStream, configure).render(
new HashMap() {{
put("year", personTraining.getCreateTime().getYear());
put("trainingDetailedList", detailedDtos);
put("writeUrl", StringUtils.isNotBlank(writeUrl) ? Pictures.ofLocal(imgUrl + "/" + writeUrl).create() : null);
put("examineUrl", StringUtils.isNotBlank(finalExamineUrl) ? Pictures.ofLocal(imgUrl + "/" + finalExamineUrl).create() : null);
put("ratifyUrl", StringUtils.isNotBlank(finalRatifyUrl) ? Pictures.ofLocal(imgUrl + "/" + finalRatifyUrl).create() : null);
put("writeDateUrl", personTraining.getCompilationDate() != null ?
Pictures.ofStream(DateImageUtil.createDateImage(personTraining.getCompilationDate())).create() : null);
put("examineDateUrl", personTraining.getAuditDate() != null ?
Pictures.ofStream(DateImageUtil.createDateImage(personTraining.getAuditDate())).create() : null);
put("ratifyDateUrl", personTraining.getApprovalDate() != null ?
Pictures.ofStream(DateImageUtil.createDateImage(personTraining.getApprovalDate())).create() : null);
}});
try {
response.setContentType("application/msword");
String fileName = URLEncoder.encode(
"人员培训计划导出", "UTF-8");
response.setHeader("Content-disposition",
"attachment;filename=" + fileName + ".docx");
OutputStream os = response.getOutputStream();
template.write(os);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("导出失败");
}
}
/**
* 导出人员培训与考核记录
* @param id
* @param response
*/
@Override
public void exportPersonTrainingRecord(Integer id, HttpServletResponse response) {
// 查询人员培训明细
PersonTrainingDetailedDto detailedDto = personTrainingDetailedMapper.selectTrainingDetail(id);
detailedDto.setTrainingContent(detailedDto.getTrainingAbstract());
detailedDto.setTrainingLecturerName(detailedDto.getTrainingLecturerId()); // 培训讲师
detailedDto.setTrainingDateString(detailedDto.getTrainingDateTwo()); // 培训日期
// 查询培训的人员
List recordDtos = personTrainingRecordMapper.selectListByTrainingDetailedId(id);
List exportDtoList = new ArrayList<>();
TrainingRecordExportDto exportDto = new TrainingRecordExportDto();
int count = 0;
for (PersonTrainingRecordDto recordDto : recordDtos) {
switch (count) {
case 0:
exportDto.setUserName1(recordDto.getUserName());
exportDto.setDepartment1(recordDto.getDepartment());
exportDto.setExaminationResults1(recordDto.getExaminationResults());
count ++;
break;
case 1:
exportDto.setUserName2(recordDto.getUserName());
exportDto.setDepartment2(recordDto.getDepartment());
exportDto.setExaminationResults2(recordDto.getExaminationResults());
exportDtoList.add(exportDto);
exportDto = new TrainingRecordExportDto();
count = 0;
break;
}
}
exportDtoList.add(exportDto);
// 质量负责人
String assessmentUserUrl = null;
if (detailedDto.getAssessmentUserId() != null) {
assessmentUserUrl = userMapper.selectById(detailedDto.getAssessmentUserId()).getSignatureUrl();
if (StringUtils.isBlank(assessmentUserUrl)) {
throw new ErrorException("找不到评价人的签名");
}
}
// 获取路径
InputStream inputStream = this.getClass().getResourceAsStream("/static/person-training-record.docx");
Configure configure = Configure.builder()
.bind("trainingRecordsList", new HackLoopTableRenderPolicy())
.build();
String finalAssessmentUserUrl = assessmentUserUrl;
XWPFTemplate template = XWPFTemplate.compile(inputStream, configure).render(
new HashMap() {{
put("trainingDetail", detailedDto);
put("trainingRecordsList", exportDtoList);
put("assessmentUserUrl", StringUtils.isNotBlank(finalAssessmentUserUrl) ? Pictures.ofLocal(imgUrl + "/" + finalAssessmentUserUrl).create() : null);
}});
try {
response.setContentType("application/msword");
String fileName = URLEncoder.encode(
"培训与考核记录导出", "UTF-8");
response.setHeader("Content-disposition",
"attachment;filename=" + fileName + ".docx");
OutputStream os = response.getOutputStream();
template.write(os);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("导出失败");
}
}
}