/*
* Copyright (c) 2023. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
* Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
* Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
* Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
* Vestibulum commodo. Ut rhoncus gravida arcu.
*/
package com.junfun.pms.report.service.impl;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.junfun.pms.constant.maint.MaintainStateEnum;
import com.junfun.pms.dic.entity.DicEqu;
import com.junfun.pms.equm.entity.EqumEqu;
import com.junfun.pms.equm.entity.EqumMaint;
import com.junfun.pms.maintain.entity.MaintainJob;
import com.junfun.pms.maintain.entity.MaintainJobLevel;
import com.junfun.pms.maintain.entity.MaintainWork;
import com.junfun.pms.maintain.entity.MaintainWorkHistory;
import com.junfun.pms.maintain.exception.MaintainExceptionCode;
import com.junfun.pms.maintain.service.MaintainWorkService;
import com.junfun.pms.report.dto.MaintainWorkExcel;
import com.junfun.pms.report.service.ExportMaintainWorkExcelService;
import com.junfun.pms.report.util.ExportExcelUtil;
import com.junfun.pms.report.util.ExportUtil;
import com.junfun.pms.ship.entity.Ship;
import com.junfun.pms.ship.mapper.ShipMapper;
import com.junfun.seafar.common.entity.ResultObject;
import com.junfun.seafar.common.entity.ServiceRequest;
import com.junfun.seafar.common.exception.BusinessException;
import com.junfun.seafar.common.util.CurrentUserUtils;
import com.junfun.seafar.dao.mybatis.plus.model.SimpleQuery;
import com.junfun.seafar.dao.mybatis.plus.support.conditions.ILambdaQueryWrapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STFldCharType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Service;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import static com.junfun.pms.report.util.ParamVerifyUtil.DateIsNull;
import static com.junfun.pms.report.util.ParamVerifyUtil.StrIsNull;
/**
* @Description 维保单历史导出Service实现
* @Date 2023/9/1
*/
@Slf4j
@Service
public class ExportMaintainWorkExcelServiceImpl implements ExportMaintainWorkExcelService {
@Autowired
private MaintainWorkService maintainWorkService;
@Autowired
private ShipMapper shipMapper;
@SneakyThrows
@Override
public ResultObject exportExcel(ServiceRequest<SimpleQuery<MaintainWork>> request, HttpServletResponse response) throws Exception {
ResultObject resultObject = new ResultObject<>();
// 查询导出信息
SimpleQuery<MaintainWork> simpleQuery = request.getBody();
ILambdaQueryWrapper<MaintainWork> query = simpleQuery.getLambdaQueryWrapper(MaintainWork.class);
query.selectAll(MaintainWork.class);
query.leftJoin(MaintainJob.class, MaintainJob::getId, MaintainWork::getJobId);
query.leftJoin(MaintainJobLevel.class, MaintainJobLevel::getId, MaintainJob::getJobLevelId);
ResultObject<List<MaintainWorkExcel>> listResultObject = this.maintainWorkService.selectJoinList(MaintainWorkExcel.class, query);
List<MaintainWorkExcel> exportResult = listResultObject.getResult();
if (exportResult == null && exportResult.size() == 0) {
resultObject.setError("没有可导出的数据");
return resultObject;
}
ExportExcelUtil.writeExcel(response, exportResult, "维保单管理", "维保单管理", MaintainWorkExcel.class);
return resultObject;
}
@Override
public void exportPendingExecution(ServiceRequest<SimpleQuery<MaintainWork>> request,HttpServletResponse response) throws Exception {
Map<String, Object> values = request.getBody().getValues();
String shipId = (String)values.get("shipId");
String planDate = (String)values.get("planDate");
String year = "";
String month = "";
if (StringUtils.isNotBlank(planDate)) {
String[] planDateArr = planDate.split("-");
year = planDateArr[0];
month = planDateArr[1];
if (planDateArr.length==2){
//将data转换成Date类型
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Date date = DateUtil.parse(planDate, "yyyy-MM");
String endDateStr=sdf.format(DateUtil.endOfMonth(date));
values.put("planDate",endDateStr); // 如果是只有年月(也就是船端处理的) 就将planDate转换成日期 本月最后一日
}
}
String pageNum = "";
String total = "";
String exportDate = LocalDateTime.now().toString().replace("T", " ");
SimpleQuery<MaintainWork> simpleQuery = request.getBody();
simpleQuery.ignoreCondition(EqumMaint::getState);// 忽略状态 这样审批不审批数据都会被导出
simpleQuery.addClass(EqumEqu.class);
ILambdaQueryWrapper<MaintainWork> query = simpleQuery.getLambdaQueryWrapper(MaintainWork.class);
query.selectAll(MaintainWork.class);
query.selectAll(EqumEqu.class);
query.selectIgnore(MaintainWork::getEquName);
query.selectIgnore(EqumMaint::getShipId);
query.selectIgnore(EqumMaint::getShipName);
query.selectIgnore(EqumMaint::getState);
query.selectIgnore(EqumEqu::getShipId);
query.selectIgnore(EqumEqu::getShipName);
query.selectIgnore(EqumEqu::getState);
query.selectAs(DicEqu::getName, MaintainWork::getEquName);
query.leftJoin(EqumMaint.class, EqumMaint::getId, MaintainWork::getJobId);
query.leftJoin(EqumEqu.class, EqumEqu::getId, MaintainWork::getEquId);
query.leftJoin(DicEqu.class,DicEqu::getId,EqumEqu::getEquDicId);
List<MaintainWork> maintainWorkList = null;
if (false) { // 改成不分页了 导出就全部数据
IPage<MaintainWork> page = simpleQuery.page();
ResultObject<List<MaintainWork>> listResultObject = maintainWorkService.selectJoinPage(page, MaintainWork.class, query);
maintainWorkList = listResultObject.getResult();
pageNum = String.valueOf(listResultObject.getPageNum());
total = String.valueOf(listResultObject.getTotal());
}else{//todo 不传分页参数看看如何处理里面的页数
ResultObject<List<MaintainWork>> listResultObject = maintainWorkService.selectJoinList(MaintainWork.class, query);
maintainWorkList = listResultObject.getResult();
}
if (maintainWorkList == null || maintainWorkList.size() == 0) {
throw new BusinessException(MaintainExceptionCode.NOT_FOUND_JOB, "没有可导出数据");
}
Map<String, Object> map = new HashMap<>();
List<Map<String, Object>> table = this.setListData(maintainWorkList);
Ship ship = this.shipMapper.selectById(shipId);
map.put("year", year);
map.put("month", month);
map.put("shipName", ship.getShipName());
map.put("createTime", DateIsNull(new Date(), true));
map.put("userName", StrIsNull(CurrentUserUtils.getUserName()));
map.put("table", table);
map.put("pageNum", pageNum);
map.put("total", total);
map.put("exportDate", exportDate);
// 导出
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource resource = resolver.getResource("classpath:/word/maintain/maintainWorkPendingExecution.docx");
Configure config = Configure.builder().bind("table", new LoopRowTableRenderPolicy()).build();
XWPFTemplate template = XWPFTemplate.compile(resource.getInputStream(), config).render(map);
// 添加页码
XWPFDocument document = template.getXWPFDocument();
addPageNumbers(document);
String fileName = String.format("%s-预防检修完成情况月度报表.docx", ship.getShipName());
ExportUtil.setHeader(fileName, response);
ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
template.writeAndClose(byteArray);
ServletOutputStream stream = response.getOutputStream();
stream.write(byteArray.toByteArray());
stream.close();
byteArray.close();
}
private void addPageNumbers(XWPFDocument document) {
XWPFHeaderFooterPolicy headerFooterPolicy = document.getHeaderFooterPolicy();
if (headerFooterPolicy == null) {
headerFooterPolicy = document.createHeaderFooterPolicy();
}
// 创建页脚
XWPFFooter footer = headerFooterPolicy.createFooter(XWPFHeaderFooterPolicy.DEFAULT);
// 创建段落
XWPFParagraph paragraph = footer.createParagraph();
paragraph.setAlignment(ParagraphAlignment.CENTER);
// 创建页码
XWPFRun run = paragraph.createRun();
run.setText("第 ");
// 插入页码字段
String pageField = "PAGE"; // 当前页码字段
String totalPageField = "NUMPAGES"; // 总页数字段
// 这里我们使用文档的 XML 结构来插入字段
run.getCTR().addNewFldChar().setFldCharType(STFldCharType.BEGIN);
run.addBreak();
run.setText(pageField);
run.getCTR().addNewFldChar().setFldCharType(STFldCharType.END);
run.setText(" 页");
run.addBreak(); // 换行
run.setText(" 共 ");
// 插入总页数字段
run.getCTR().addNewFldChar().setFldCharType(STFldCharType.BEGIN);
run.addBreak();
run.setText(totalPageField);
run.getCTR().addNewFldChar().setFldCharType(STFldCharType.END);
run.setText(" 页");
}
private List<Map<String, Object>> setListData(List<MaintainWork> maintainWorks) {
List<Map<String, Object>> resultMap = new ArrayList<>();
for (int i = 0; i < maintainWorks.size(); i++) {
MaintainWork maintainWork = maintainWorks.get(i);
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("No", i+1);
dataMap.put("jobName",StrIsNull(maintainWork.getJobName()));
dataMap.put("maintainState", StrIsNull(maintainWork.getJobContent()));
//特定状态才填写完成时间
if (MaintainStateEnum.W0008.getCode().equals(maintainWork.getState())){
dataMap.put("completeDate", DateIsNull(maintainWork.getCompleteDate(),true));
}
resultMap.add(dataMap);
}
return resultMap;
}
}
下面是模板