Commit 9d972b38 authored by xinglei's avatar xinglei

*) 新增月度巡检功能

parent 126bcbb1
package com.yeejoin.amos.patrol.common.entity;
import net.sf.cglib.beans.BeanGenerator;
import net.sf.cglib.beans.BeanMap;
import java.util.Map;
/**
* @Author: xinglei
* @Description:
* @Date: 2020/8/20 20:43
*/
public class DynamicBean {
private Object target;
private BeanMap beanMap;
public DynamicBean(Class superclass, Map<String, Class> propertyMap) {
this.target = generateBean(superclass, propertyMap);
this.beanMap = BeanMap.create(this.target);
}
public void setValue(String property, Object value) {
beanMap.put(property, value);
}
public Object getValue(String property) {
return beanMap.get(property);
}
public Object getTarget() {
return this.target;
}
/**
* 根据属性生成对象
*
*/
private Object generateBean(Class superclass, Map<String, Class> propertyMap) {
BeanGenerator generator = new BeanGenerator();
if (null != superclass) {
generator.setSuperclass(superclass);
}
BeanGenerator.addProperties(generator, propertyMap);
return generator.create();
}
}
package com.yeejoin.amos.patrol.common.enums;
public enum DeptEnum {
XA_JS("西安技术", "XAJS"),
XA_YW("西安业务", "XAYW"),
XY_YW("咸阳技术", "XYJS");
/**
* 名称,描述
*/
private String name;
/**
* 编码
*/
private String code;
DeptEnum(String name, String code) {
this.name = name;
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public static String getEnumCode(String name) {
String code = "";
for(DeptEnum type: DeptEnum.values()) {
if (type.getName().equals(name)) {
code = type.getCode();
break;
}
}
return code;
}
}
package com.yeejoin.amos.patrol.common.enums;
public enum ExcelEnum {
BUSINESS("business", "temp/businessExportTemplate.xls"),
TECHNOLOGY("technology", "temp/technologyExportTemplate.xls");
/**
* 名称,描述
*/
private String type;
/**
* 编码
*/
private String desc;
ExcelEnum(String type, String desc) {
this.type = type;
this.desc = desc;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public static String getEnumDesc(String type) {
String desc = "";
for(ExcelEnum label: ExcelEnum.values()) {
if (label.getType().equals(type)) {
desc = label.getDesc();
break;
}
}
return desc;
}
}
...@@ -28,18 +28,6 @@ ...@@ -28,18 +28,6 @@
<version>2.4</version> <version>2.4</version>
<classifier>jdk15</classifier> <classifier>jdk15</classifier>
</dependency> </dependency>
<!-- <dependency>
<groupId>com.netflix.feign</groupId>
<artifactId>feign-core</artifactId>
<version>8.18.0</version>
<scope>runtime</scope>
</dependency> -->
<!-- <dependency>
<groupId>com.netflix.feign</groupId>
<artifactId>feign-gson</artifactId>
<version>8.18.0</version>
<scope>runtime</scope>
</dependency> -->
</dependencies> </dependencies>
</project> </project>
\ No newline at end of file
...@@ -4,109 +4,130 @@ import java.util.Date; ...@@ -4,109 +4,130 @@ import java.util.Date;
/** /**
* 巡检记录项Bo * 巡检记录项Bo
* @author tianbo
* *
* @author tianbo
*/ */
public class CheckInputBo { public class CheckInputBo {
/** /**
* 检查项名称 * 巡检点ID
*/ */
private String inputItemName; private String pointId;
/** /**
* 检查结果 * 巡检点名称
*/ */
private String inputValue; private String pointName;
/** private String orgCode;
* 是否合格 private String checkDate;
*/ private String beginTime;
private String isOK; /**
* 开始时间字符串
/** */
* 上报时间 private String beginTimeStr;
*/ /**
private Date uploadTime; * 计划ID-状态
*/
private String idStateStr;
/**
* 检查项名称
*/
private String inputItemName;
/**
* 检查结果
*/
private String inputValue;
/**
* 是否合格
*/
private String isOK;
/**
* 上报时间
*/
private Date uploadTime;
// /** // /**
// * 任务状态:0未完成,1已完成 // * 任务状态:0未完成,1已完成
// */ // */
// private int taskStats; // private int taskStats;
/** /**
* 任务执行人 * 任务执行人
*/ */
private String executor; private String executor;
/** /**
* 检查项评分 * 检查项评分
*/ */
private String inputItemScore; private String inputItemScore;
/** /**
* 分类ID * 分类ID
*/ */
private long classifyId; private long classifyId;
/** /**
* 分类名称 * 分类名称
*/ */
private String classifyName; private String classifyName;
/** /**
* 巡检记录检查项检查结果ID * 巡检记录检查项检查结果ID
*/ */
private long checkInputId; private long checkInputId;
/** /**
* 检查项ID * 检查项ID
*/ */
private String inputId; private String inputId;
// 备注说明 // 备注说明
private String remark; private String remark;
private int imgCount; private int imgCount;
public String getInputItemName() { public String getInputItemName() {
return inputItemName; return inputItemName;
} }
public void setInputItemName(String inputItemName) { public void setInputItemName(String inputItemName) {
this.inputItemName = inputItemName; this.inputItemName = inputItemName;
} }
public String getInputValue() { public String getInputValue() {
return inputValue; return inputValue;
} }
public void setInputValue(String inputValue) { public void setInputValue(String inputValue) {
this.inputValue = inputValue; this.inputValue = inputValue;
} }
public String getIsOK() { public String getIsOK() {
return isOK; return isOK;
} }
public void setIsOK(String isOK) { public void setIsOK(String isOK) {
this.isOK = isOK; this.isOK = isOK;
} }
public Date getUploadTime() { public Date getUploadTime() {
return uploadTime; return uploadTime;
} }
public void setUploadTime(Date uploadTime) { public void setUploadTime(Date uploadTime) {
this.uploadTime = uploadTime; this.uploadTime = uploadTime;
} }
// public int getTaskStats() { // public int getTaskStats() {
// return taskStats; // return taskStats;
...@@ -116,71 +137,126 @@ public class CheckInputBo { ...@@ -116,71 +137,126 @@ public class CheckInputBo {
// this.taskStats = taskStats; // this.taskStats = taskStats;
// } // }
public String getExecutor() { public String getExecutor() {
return executor; return executor;
} }
public void setExecutor(String executor) {
this.executor = executor;
}
public String getInputItemScore() {
return inputItemScore;
}
public void setInputItemScore(String inputItemScore) {
this.inputItemScore = inputItemScore;
}
public long getClassifyId() {
return classifyId;
}
public void setClassifyId(long classifyId) {
this.classifyId = classifyId;
}
public String getClassifyName() {
return classifyName;
}
public void setClassifyName(String classifyName) {
this.classifyName = classifyName;
}
public long getCheckInputId() {
return checkInputId;
}
public void setCheckInputId(long checkInputId) {
this.checkInputId = checkInputId;
}
public String getInputId() {
return inputId;
}
public void setInputId(String inputId) {
this.inputId = inputId;
}
public void setExecutor(String executor) { public String getRemark() {
this.executor = executor; return remark;
} }
public String getInputItemScore() { public void setRemark(String remark) {
return inputItemScore; this.remark = remark;
} }
public void setInputItemScore(String inputItemScore) { public int getImgCount() {
this.inputItemScore = inputItemScore; return imgCount;
} }
public long getClassifyId() { public void setImgCount(int imgCount) {
return classifyId; this.imgCount = imgCount;
} }
public void setClassifyId(long classifyId) { public String getPointId() {
this.classifyId = classifyId; return pointId;
} }
public String getClassifyName() { public void setPointId(String pointId) {
return classifyName; this.pointId = pointId;
} }
public void setClassifyName(String classifyName) { public String getPointName() {
this.classifyName = classifyName; return pointName;
} }
public long getCheckInputId() { public void setPointName(String pointName) {
return checkInputId; this.pointName = pointName;
} }
public void setCheckInputId(long checkInputId) { public String getOrgCode() {
this.checkInputId = checkInputId; return orgCode;
} }
public void setOrgCode(String orgCode) {
this.orgCode = orgCode;
}
public String getInputId() { public String getCheckDate() {
return inputId; return checkDate;
} }
public void setInputId(String inputId) { public void setCheckDate(String checkDate) {
this.inputId = inputId; this.checkDate = checkDate;
} }
public String getBeginTime() {
return beginTime;
}
public String getRemark() { public void setBeginTime(String beginTime) {
return remark; this.beginTime = beginTime;
} }
public void setRemark(String remark) { public String getBeginTimeStr() {
this.remark = remark; return beginTimeStr;
} }
public int getImgCount() { public void setBeginTimeStr(String beginTimeStr) {
return imgCount; this.beginTimeStr = beginTimeStr;
} }
public void setImgCount(int imgCount) { public String getIdStateStr() {
this.imgCount = imgCount; return idStateStr;
} }
public void setIdStateStr(String idStateStr) {
this.idStateStr = idStateStr;
}
} }
package com.yeejoin.amos.patrol.service.business.controller; package com.yeejoin.amos.patrol.service.business.controller;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel; import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
...@@ -16,6 +18,7 @@ import com.yeejoin.amos.patrol.common.entity.CommonResponseUtil; ...@@ -16,6 +18,7 @@ import com.yeejoin.amos.patrol.common.entity.CommonResponseUtil;
import com.yeejoin.amos.patrol.common.entity.DaoCriteria; import com.yeejoin.amos.patrol.common.entity.DaoCriteria;
import com.yeejoin.amos.patrol.common.entity.PlanTask; import com.yeejoin.amos.patrol.common.entity.PlanTask;
import com.yeejoin.amos.patrol.common.entity.Point; import com.yeejoin.amos.patrol.common.entity.Point;
import com.yeejoin.amos.patrol.common.enums.ExcelEnum;
import com.yeejoin.amos.patrol.common.enums.PlanTaskFinishStatusEnum; import com.yeejoin.amos.patrol.common.enums.PlanTaskFinishStatusEnum;
import com.yeejoin.amos.patrol.service.business.dto.CheckDto; import com.yeejoin.amos.patrol.service.business.dto.CheckDto;
import com.yeejoin.amos.patrol.service.business.param.CheckImgParam; import com.yeejoin.amos.patrol.service.business.param.CheckImgParam;
...@@ -23,6 +26,7 @@ import com.yeejoin.amos.patrol.service.business.param.CheckInfoPageParam; ...@@ -23,6 +26,7 @@ import com.yeejoin.amos.patrol.service.business.param.CheckInfoPageParam;
import com.yeejoin.amos.patrol.service.business.param.CheckInputParam; import com.yeejoin.amos.patrol.service.business.param.CheckInputParam;
import com.yeejoin.amos.patrol.service.business.param.CheckRecordParam; import com.yeejoin.amos.patrol.service.business.param.CheckRecordParam;
import com.yeejoin.amos.patrol.service.business.param.CheckStatisticalParam; import com.yeejoin.amos.patrol.service.business.param.CheckStatisticalParam;
import com.yeejoin.amos.patrol.service.business.service.impl.TaskReportServiceImpl;
import com.yeejoin.amos.patrol.service.business.service.intfc.ICheckService; import com.yeejoin.amos.patrol.service.business.service.intfc.ICheckService;
import com.yeejoin.amos.patrol.service.business.service.intfc.IPlanTaskService; import com.yeejoin.amos.patrol.service.business.service.intfc.IPlanTaskService;
import com.yeejoin.amos.patrol.service.business.service.intfc.IPointService; import com.yeejoin.amos.patrol.service.business.service.intfc.IPointService;
...@@ -55,15 +59,13 @@ import org.apache.http.entity.StringEntity; ...@@ -55,15 +59,13 @@ import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair; import org.apache.http.message.BasicNameValuePair;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.util.CollectionUtils; import org.springframework.util.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
...@@ -87,12 +89,7 @@ import java.io.FileInputStream; ...@@ -87,12 +89,7 @@ import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors; import java.util.stream.Collectors;
...@@ -127,15 +124,18 @@ public class CheckController extends BaseController { ...@@ -127,15 +124,18 @@ public class CheckController extends BaseController {
private RemoteWebSocketServer remoteWebSocketServer; private RemoteWebSocketServer remoteWebSocketServer;
@Autowired @Autowired
private AmosBankFeign amosBankFeign; private AmosBankFeign amosBankFeign;
@Autowired
private TaskReportServiceImpl taskReportService;
@Value("${upload.root.path}") @Value("${upload.root.path}")
private String uploadRootPath; private String uploadRootPath;
/* @Value("${params.video}") /* @Value("${params.video}")
private String videourl ;*/ private String videourl ;*/
@Value("${params.token}") @Value("${params.token}")
private String tokenurl ; private String tokenurl;
/** /**
* 巡检计划查询 * 巡检计划查询
*/ */
...@@ -147,34 +147,24 @@ public class CheckController extends BaseController { ...@@ -147,34 +147,24 @@ public class CheckController extends BaseController {
ReginParams reginParams = getSelectedOrgInfo(); ReginParams reginParams = getSelectedOrgInfo();
String orgCode = getLoginOrgCode(reginParams); String orgCode = getLoginOrgCode(reginParams);
String roleTypeName = getRoleTypeName(reginParams); String roleTypeName = getRoleTypeName(reginParams);
// HashMap<String, Object> paramMap = buildMybatisDaoCriterias(orgCode, roleTypeName);
HashMap<String, Object> paramMap = new HashMap<>(); HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("orgCode", orgCode); paramMap.put("orgCode", orgCode);
paramMap.put("roleFlag", XJConstant.ADMIN_FLAG); paramMap.put("roleFlag", XJConstant.ADMIN_FLAG);
CheckInfoPageParam param = CheckPageParamUtil.fillCheckInfoParam(queryRequests, commonPageable, paramMap); CheckInfoPageParam param = CheckPageParamUtil.fillCheckInfoParam(queryRequests, commonPageable, paramMap);
if (ObjectUtils.isEmpty(param.getOrderBy())) { if (ObjectUtils.isEmpty(param.getOrderBy())) {
param.setOrderBy("checkDate desc"); param.setOrderBy("checkDate desc");
} }
if (!(ObjectUtils.isEmpty(param.getUserId())) && param.getUserId().equals("-1")) { if (!(ObjectUtils.isEmpty(param.getUserId())) && param.getUserId().equals("-1")) {
param.setUserId(null); param.setUserId(null);
} }
if (!(ObjectUtils.isEmpty(param.getDepartmentId())) && param.getDepartmentId().equals("-1")) { if (!(ObjectUtils.isEmpty(param.getDepartmentId())) && param.getDepartmentId().equals("-1")) {
param.setDepartmentId(null); param.setDepartmentId(null);
} }
Page<CheckInfoVo> list = checkService.getCheckInfo(getToken(),getProduct(),getAppKey(),param);
return CommonResponseUtil.success(list);
Page<CheckInfoVo> list = checkService.getCheckInfo(getToken(), getProduct(), getAppKey(), param);
return CommonResponseUtil.success(list);
} }
@ApiOperation(value = "导出巡检记录", notes = "导出巡检记录") @ApiOperation(value = "导出巡检记录", notes = "导出巡检记录")
...@@ -189,7 +179,7 @@ public class CheckController extends BaseController { ...@@ -189,7 +179,7 @@ public class CheckController extends BaseController {
CheckInfoPageParam param = CheckPageParamUtil.fillCheckInfoParam(queryRequests, null, paramMap); CheckInfoPageParam param = CheckPageParamUtil.fillCheckInfoParam(queryRequests, null, paramMap);
param.setPageSize(-1); param.setPageSize(-1);
param.setOrderBy("checkDate DESC"); param.setOrderBy("checkDate DESC");
List<CheckInfoVo> list = checkService.getCheckInfoList(getToken(),getProduct(),getAppKey(),param); List<CheckInfoVo> list = checkService.getCheckInfoList(getToken(), getProduct(), getAppKey(), param);
String fileName = "巡检记录" + new Date().getTime(); String fileName = "巡检记录" + new Date().getTime();
FileHelper.exportExcel(list, "巡检记录", "巡检记录", CheckInfoVo.class, fileName + ".xls", response); FileHelper.exportExcel(list, "巡检记录", "巡检记录", CheckInfoVo.class, fileName + ".xls", response);
} }
...@@ -199,7 +189,7 @@ public class CheckController extends BaseController { ...@@ -199,7 +189,7 @@ public class CheckController extends BaseController {
public void exportSelectCheckRecord( public void exportSelectCheckRecord(
@ApiParam(value = "查询条件") @RequestParam(required = false) Long[] ids, @ApiParam(value = "查询条件") @RequestParam(required = false) Long[] ids,
HttpServletResponse response) { HttpServletResponse response) {
List<CheckInfoVo> list = checkService.getSelectedCheckInfoList(getToken(),getProduct(),getAppKey(),ids); List<CheckInfoVo> list = checkService.getSelectedCheckInfoList(getToken(), getProduct(), getAppKey(), ids);
String fileName = "巡检记录" + new Date().getTime(); String fileName = "巡检记录" + new Date().getTime();
FileHelper.exportExcel(list, "巡检记录", "巡检记录", CheckInfoVo.class, fileName + ".xls", response); FileHelper.exportExcel(list, "巡检记录", "巡检记录", CheckInfoVo.class, fileName + ".xls", response);
} }
...@@ -239,16 +229,16 @@ public class CheckController extends BaseController { ...@@ -239,16 +229,16 @@ public class CheckController extends BaseController {
public CommonResponse saveCheckRecord( public CommonResponse saveCheckRecord(
@ApiParam(value = "检查信息", required = false) @RequestBody(required = true) CheckRecordParam requestParam) { @ApiParam(value = "检查信息", required = false) @RequestBody(required = true) CheckRecordParam requestParam) {
int statu = -1; int statu = -1;
PlanTask planTask =null; PlanTask planTask = null;
if(requestParam.getPlanTaskId()!=null){ if (requestParam.getPlanTaskId() != null) {
planTask = planTaskService.selectPlanTaskStatus(requestParam.getPlanTaskId()); planTask = planTaskService.selectPlanTaskStatus(requestParam.getPlanTaskId());
} }
AgencyUserModel user = getUserInfo(); AgencyUserModel user = getUserInfo();
String userId = user.getUserId(); String userId = user.getUserId();
String realName = user.getRealName(); String realName = user.getRealName();
requestParam.setIsOffline(requestParam.getIsOffline()==null?false:requestParam.getIsOffline()); requestParam.setIsOffline(requestParam.getIsOffline() == null ? false : requestParam.getIsOffline());
try { try {
if (planTask != null) { if (planTask != null) {
//竞争修改 //竞争修改
...@@ -295,15 +285,15 @@ public class CheckController extends BaseController { ...@@ -295,15 +285,15 @@ public class CheckController extends BaseController {
asyncTask.pushCheckRecordMessage(checkDto.getCheckId(), realName, map); asyncTask.pushCheckRecordMessage(checkDto.getCheckId(), realName, map);
//推送到风险系统 //推送到风险系统
asyncTask.pushCheckInfoTo3D(checkDto.getCheckId()); asyncTask.pushCheckInfoTo3D(checkDto.getCheckId());
//推送银行首页 //推送银行首页
//增建已超时,推送 //增建已超时,推送
asyncTask.pushChartResulplantask(); asyncTask.pushChartResulplantask();
// //推送首页统计 // //推送首页统计
// asyncTask.pushChartResult(); // asyncTask.pushChartResult();
if (!CollectionUtils.isEmpty(checkDto.getUnCheckInputList())) { if (!CollectionUtils.isEmpty(checkDto.getUnCheckInputList())) {
//取消隐患添加 //取消隐患添加
checkDto.setUnCheckInputList(null); checkDto.setUnCheckInputList(null);
asyncTask.pushNoPassCheckRecordMessage(checkDto.getCheckId(), realName, map); asyncTask.pushNoPassCheckRecordMessage(checkDto.getCheckId(), realName, map);
} }
remoteWebSocketServer.wsDataRefresh("check"); remoteWebSocketServer.wsDataRefresh("check");
...@@ -334,74 +324,74 @@ public class CheckController extends BaseController { ...@@ -334,74 +324,74 @@ public class CheckController extends BaseController {
@RequestMapping(value = "/uploadCheckImg", produces = "application/json;charset=UTF-8", method = RequestMethod.POST) @RequestMapping(value = "/uploadCheckImg", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
public CommonResponse uploadCheckImg( public CommonResponse uploadCheckImg(
@ApiParam(value = "检查图片", required = true) @RequestBody(required = true) MultipartFile file) { @ApiParam(value = "检查图片", required = true) @RequestBody(required = true) MultipartFile file) {
synchronized (CheckController.class) { synchronized (CheckController.class) {
CheckImgParam checkImgParam = new CheckImgParam(); CheckImgParam checkImgParam = new CheckImgParam();
//扩展分类id //扩展分类id
String classifyId = request.getParameter("classifyId"); String classifyId = request.getParameter("classifyId");
String classifyIdPathString = ""; String classifyIdPathString = "";
if (null != classifyId && !"".equals(classifyId) && !"null".equals(classifyId)) { if (null != classifyId && !"".equals(classifyId) && !"null".equals(classifyId)) {
checkImgParam.setClassifyId(Long.parseLong(request.getParameter("classifyId"))); checkImgParam.setClassifyId(Long.parseLong(request.getParameter("classifyId")));
classifyIdPathString = "/" + request.getParameter("classifyId"); classifyIdPathString = "/" + request.getParameter("classifyId");
} }
checkImgParam.setCheckId(Long.parseLong(request.getParameter("checkId"))); checkImgParam.setCheckId(Long.parseLong(request.getParameter("checkId")));
if (!ObjectUtils.isEmpty(request.getParameter("inputItemId"))) { if (!ObjectUtils.isEmpty(request.getParameter("inputItemId"))) {
checkImgParam.setInputItemId(Long.parseLong(request.getParameter("inputItemId"))); checkImgParam.setInputItemId(Long.parseLong(request.getParameter("inputItemId")));
} }
checkImgParam.setPointId(Long.parseLong(request.getParameter("pointId"))); checkImgParam.setPointId(Long.parseLong(request.getParameter("pointId")));
checkImgParam.setName(request.getParameter("name")); checkImgParam.setName(request.getParameter("name"));
Point point = iPointService.queryPointById(checkImgParam.getPointId()); Point point = iPointService.queryPointById(checkImgParam.getPointId());
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
ReginParams reginParams = getSelectedOrgInfo(); ReginParams reginParams = getSelectedOrgInfo();
String loginOrgCode = getLoginOrgCode(reginParams); String loginOrgCode = getLoginOrgCode(reginParams);
String[] companys = loginOrgCode.split("\\*"); String[] companys = loginOrgCode.split("\\*");
String path = "/" + companys[companys.length - 1] + "/" String path = "/" + companys[companys.length - 1] + "/"
+ sdf.format(new Date()) + "/" + point.getName() + "/" + sdf.format(new Date()) + "/" + point.getName() + "/"
+ checkImgParam.getCheckId(); + checkImgParam.getCheckId();
if(!"".equals(classifyIdPathString)) { if (!"".equals(classifyIdPathString)) {
path += classifyIdPathString; path += classifyIdPathString;
} }
String filePath = uploadRootPath + path; String filePath = uploadRootPath + path;
if (file.isEmpty()) { if (file.isEmpty()) {
return CommonResponseUtil.failure("上传文件失败"); return CommonResponseUtil.failure("上传文件失败");
} }
String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
String fileName = ObjectUtils.isEmpty(checkImgParam.getName()) ? "/" + file.getOriginalFilename() String fileName = ObjectUtils.isEmpty(checkImgParam.getName()) ? "/" + file.getOriginalFilename()
: "/" + checkImgParam.getName()+UUID.randomUUID() + fileType; : "/" + checkImgParam.getName() + UUID.randomUUID() + fileType;
try { try {
File dest = new File(filePath + "/" + fileName); File dest = new File(filePath + "/" + fileName);
if (!dest.exists()) { if (!dest.exists()) {
if (dest.getParentFile() != null && !dest.getParentFile().exists()) { if (dest.getParentFile() != null && !dest.getParentFile().exists()) {
dest.getParentFile().mkdirs(); dest.getParentFile().mkdirs();
} }
dest.createNewFile(); dest.createNewFile();
} }
file.transferTo(dest); file.transferTo(dest);
} catch (IOException e) { } catch (IOException e) {
return CommonResponseUtil.failure("上传文件失败"); return CommonResponseUtil.failure("上传文件失败");
} }
CheckShot img = new CheckShot(); CheckShot img = new CheckShot();
String photoFile = path + fileName; String photoFile = path + fileName;
img.setPhotoData(photoFile); img.setPhotoData(photoFile);
img.setCheckId(Integer.valueOf(checkImgParam.getCheckId() + "")); img.setCheckId(Integer.valueOf(checkImgParam.getCheckId() + ""));
img.setOrgCode(loginOrgCode); img.setOrgCode(loginOrgCode);
img.setCreateDate(new Date()); img.setCreateDate(new Date());
img.setPointName(checkImgParam.getName()); img.setPointName(checkImgParam.getName());
img.setCheckInputId(checkImgParam.getInputItemId()); img.setCheckInputId(checkImgParam.getInputItemId());
img.setShotType("1".equals(point.getIsFixed()) ? "定点" : "普通"); img.setShotType("1".equals(point.getIsFixed()) ? "定点" : "普通");
img.setClassifyId(checkImgParam.getClassifyId()); img.setClassifyId(checkImgParam.getClassifyId());
checkService.saveCheckImg(img); checkService.saveCheckImg(img);
} }
return CommonResponseUtil.success(); return CommonResponseUtil.success();
} }
...@@ -435,12 +425,12 @@ public class CheckController extends BaseController { ...@@ -435,12 +425,12 @@ public class CheckController extends BaseController {
} }
// @Authorization(ingore = true) // @Authorization(ingore = true)
@ApiOperation(value = "获取巡检计划巡检点(已完成或漏检的巡检点)详情信息<font color='blue'>手机app</font>", notes = "获取巡检计划巡检点(已完成或漏检的巡检点)详情信息<font color='blue'>手机app</font>") @ApiOperation(value = "获取巡检计划巡检点(已完成或漏检的巡检点)详情信息<font color='blue'>手机app</font>", notes = "获取巡检计划巡检点(已完成或漏检的巡检点)详情信息<font color='blue'>手机app</font>")
@RequestMapping(value = "/queryCheckPointDetail", produces = "application/json;charset=UTF-8", method = RequestMethod.GET) @RequestMapping(value = "/queryCheckPointDetail", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public CommonResponse queryCheckPointDetail(@RequestParam(required = true) long checkId) { public CommonResponse queryCheckPointDetail(@RequestParam(required = true) long checkId) {
try { try {
AppPointCheckRespone pointCheckRespone = checkService.queryCheckPointDetail(getToken(),getProduct(),getAppKey(),checkId); AppPointCheckRespone pointCheckRespone = checkService.queryCheckPointDetail(getToken(), getProduct(), getAppKey(), checkId);
return CommonResponseUtil.success(pointCheckRespone); return CommonResponseUtil.success(pointCheckRespone);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
...@@ -492,12 +482,12 @@ public class CheckController extends BaseController { ...@@ -492,12 +482,12 @@ public class CheckController extends BaseController {
// req.put("userId", userId); // req.put("userId", userId);
// } // }
if (XJConstant.CCPC_PERSONAL.equals(roleTypeName)) { if (XJConstant.CCPC_PERSONAL.equals(roleTypeName)) {
//一线技术,一线业务只能看自己的 //一线技术,一线业务只能看自己的
req.put("userId", getUserId()); req.put("userId", getUserId());
req.put("orgCode", loginOrgCode); req.put("orgCode", loginOrgCode);
} else { } else {
//管理员 //管理员
req.put("orgCode", loginOrgCode); req.put("orgCode", loginOrgCode);
} }
Map<String, Object> map = checkService.queryRecordByPointId(req); Map<String, Object> map = checkService.queryRecordByPointId(req);
return CommonResponseUtil.success(map); return CommonResponseUtil.success(map);
...@@ -590,14 +580,14 @@ public class CheckController extends BaseController { ...@@ -590,14 +580,14 @@ public class CheckController extends BaseController {
@ApiParam(value = "查询条件", required = false) @RequestBody(required = false) CheckStatisticalParam queryRequests) { @ApiParam(value = "查询条件", required = false) @RequestBody(required = false) CheckStatisticalParam queryRequests) {
String userId = getUserId(); String userId = getUserId();
ReginParams reginParams = getSelectedOrgInfo(); ReginParams reginParams = getSelectedOrgInfo();
//String loginOrgCode = getLoginOrgCode(reginParams); //String loginOrgCode = getLoginOrgCode(reginParams);
//权限放到公司级别 //权限放到公司级别
String loginOrgCode =reginParams.getCompany().getOrgCode(); String loginOrgCode = reginParams.getCompany().getOrgCode();
queryRequests.setOrgCode(loginOrgCode); queryRequests.setOrgCode(loginOrgCode);
List<CheckAnalysisVo> list = checkService.getCheckStatisticalAnalysis(getToken(),getProduct(),getAppKey(),queryRequests); List<CheckAnalysisVo> list = checkService.getCheckStatisticalAnalysis(getToken(), getProduct(), getAppKey(), queryRequests);
return CommonResponseUtil.success(list); return CommonResponseUtil.success(list);
} }
...@@ -608,22 +598,49 @@ public class CheckController extends BaseController { ...@@ -608,22 +598,49 @@ public class CheckController extends BaseController {
HttpServletResponse response) { HttpServletResponse response) {
String userId = getUserId(); String userId = getUserId();
ReginParams reginParams = getSelectedOrgInfo(); ReginParams reginParams = getSelectedOrgInfo();
//String loginOrgCode = getLoginOrgCode(reginParams); //String loginOrgCode = getLoginOrgCode(reginParams);
//权限放到公司级别 //权限放到公司级别
String loginOrgCode =reginParams.getCompany().getOrgCode(); queryRequests.setOrgCode(loginOrgCode); String loginOrgCode = reginParams.getCompany().getOrgCode();
List<CheckAnalysisVo> list = checkService.getCheckStatisticalAnalysis(getToken(),getProduct(),getAppKey(),queryRequests); queryRequests.setOrgCode(loginOrgCode);
List<CheckAnalysisVo> list = checkService.getCheckStatisticalAnalysis(getToken(), getProduct(), getAppKey(), queryRequests);
String fileName = "巡检记录" + new Date().getTime(); String fileName = "巡检记录" + new Date().getTime();
FileHelper.exportExcel(list, "巡检情况统计分析", "巡检情况统计分析", CheckAnalysisVo.class, fileName + ".xls", response); FileHelper.exportExcel(list, "巡检情况统计分析", "巡检情况统计分析", CheckAnalysisVo.class, fileName + ".xls", response);
} }
// @Authorization(ingore = true) @ApiOperation(value = "月度巡检情况", notes = "月度巡检情况")
// @ApiOperation(value = "111111(<font color='blue'>release</font>)", notes = "11111") @RequestMapping(value = "/statisticalByMonth", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
// @RequestMapping(value = "/ids", method = RequestMethod.GET, produces = "application/json;charset=UTF-8") public CommonResponse getCheckStatisticalByMonth(
// public CommonResponse getIds() { @ApiParam(value = "查询条件", required = false) @RequestBody(required = false) CheckStatisticalParam queryRequests) {
// is.pointCheckInfoPush((long) 28); ReginParams reginParams = getSelectedOrgInfo();
// return CommonResponseUtil.success(); String loginOrgCode = reginParams.getCompany().getOrgCode();
// } String companyId = reginParams.getCompany().getSequenceNbr();
queryRequests.setOrgCode(loginOrgCode);
Map<String, Object> result = checkService.getCheckStatisticalByMonth(getToken(), getProduct(), getAppKey(), queryRequests, companyId);
return CommonResponseUtil.success(result);
}
@ApiOperation(value = "导出月度巡检情况", notes = "导出月度巡检情况")
@RequestMapping(value = "/exportStatisticalByMonth", method = RequestMethod.POST, produces = "application/vnd.ms-excel;charset=UTF-8")
public void exportStatisticalByMonth(
@ApiParam(value = "查询条件", required = false) @RequestBody(required = false) CheckStatisticalParam queryRequests,
HttpServletResponse response) {
ReginParams reginParams = getSelectedOrgInfo();
String loginOrgCode = reginParams.getCompany().getOrgCode();
String companyId = reginParams.getCompany().getSequenceNbr();
queryRequests.setOrgCode(loginOrgCode);
Map<String, Object> map = checkService.getCheckStatisticalByMonth(getToken(), getProduct(), getAppKey(), queryRequests, companyId);
TemplateExportParams params = new TemplateExportParams("temp/monthExportTemplate.xls");
try {
FileHelper.writToResponse(map, response, params, "月度巡检情况报表.xls");
} catch (Exception e) {
e.printStackTrace();
}
}
/** /**
* 根据检查项ID和检查输入项ID查询图片, 如果输入项ID位0时,查询巡检现场照片, 如果不为0查询检查项照片 * 根据检查项ID和检查输入项ID查询图片, 如果输入项ID位0时,查询巡检现场照片, 如果不为0查询检查项照片
...@@ -639,78 +656,56 @@ public class CheckController extends BaseController { ...@@ -639,78 +656,56 @@ public class CheckController extends BaseController {
@ApiParam(value = "扩展分类ID") @RequestParam(required = true) int classifyId, @ApiParam(value = "扩展分类ID") @RequestParam(required = true) int classifyId,
@ApiParam(value = "检查输入项ID") @RequestParam(required = false) int checkInputId) { @ApiParam(value = "检查输入项ID") @RequestParam(required = false) int checkInputId) {
try { try {
List<String> list = checkService.getCheckPhotosByCheckAndInputIdAndClassifyId(checkId, checkInputId,classifyId); List<String> list = checkService.getCheckPhotosByCheckAndInputIdAndClassifyId(checkId, checkInputId, classifyId);
return CommonResponseUtil.success(list); return CommonResponseUtil.success(list);
} catch (Exception e) { } catch (Exception e) {
return CommonResponseUtil.failure(e.getMessage()); return CommonResponseUtil.failure(e.getMessage());
} }
} }
@ApiOperation(value = "test", notes = "test") @ApiOperation(value = "test", notes = "test")
@RequestMapping(value = "/test", method = RequestMethod.GET, produces = "application/json;charset=UTF-8") @RequestMapping(value = "/test", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
public CommonResponse getCheckPhotosByCheckAndInputId() { public CommonResponse getCheckPhotosByCheckAndInputId() {
asyncTask.pushChartResult(); asyncTask.pushChartResult();
return null; return null;
} }
@ApiOperation(value = "视频监控接口", notes = "视频监控接口") @ApiOperation(value = "视频监控接口", notes = "视频监控接口")
@RequestMapping(value = "/getvideo/{parentId}/{current}/{pageSize}", method = RequestMethod.POST, produces = "application/vnd.ms-excel;charset=UTF-8") @RequestMapping(value = "/getvideo/{parentId}/{current}/{pageSize}", method = RequestMethod.POST, produces = "application/vnd.ms-excel;charset=UTF-8")
public String getvideo( @ApiParam(value = "父节点ID(给默认9)") @PathVariable(required = true) Long parentId, public String getvideo(@ApiParam(value = "父节点ID(给默认9)") @PathVariable(required = true) Long parentId,
@ApiParam(value = "父节点ID(给默认9)") @PathVariable(required = true) Integer current, @ApiParam(value = "父节点ID(给默认9)") @PathVariable(required = true) Integer current,
@ApiParam(value = "父节点ID(给默认9)") @PathVariable(required = true) Integer pageSize @ApiParam(value = "父节点ID(给默认9)") @PathVariable(required = true) Integer pageSize
) { ) {
CommonResponse lis = amosBankFeign.getVideos(getSelectedOrgInfo().getCompany().getOrgCode(), current, pageSize, parentId);
/* MultiValueMap<String, Object> param = new LinkedMultiValueMap<>(); String resultString = "";
param.add("current", current); resultString = JSONObject.toJSONString(lis);
param.add("pageSize", pageSize);
param.add("parentId", parentId); return resultString;
MonitorParam dd=new MonitorParam();
dd.setParentId(parentId);
dd.setPageSize(pageSize);
dd.setCurrent(current);*/
CommonResponse lis= amosBankFeign.getVideos(getSelectedOrgInfo().getCompany().getOrgCode(),current, pageSize, parentId);
String resultString = "";
resultString = JSONObject.toJSONString(lis);
/* CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
HttpPost httpPost = new HttpPost(videourl);
StringEntity entity = new StringEntity(JSON.toJSONString(param), ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
return resultString;
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return resultString;
}
}*/
return resultString;
} }
@ApiOperation(value = "视屏页面接口", notes = "视屏页面接口") @ApiOperation(value = "视屏页面接口", notes = "视屏页面接口")
@RequestMapping(value = "/tokenurl", method = RequestMethod.GET, produces = "application/json;charset=UTF-8") @RequestMapping(value = "/tokenurl", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
public CommonResponse getvideoToke() { public CommonResponse getvideoToke() {
return CommonResponseUtil.success(tokenurl); return CommonResponseUtil.success(tokenurl);
}
@ApiOperation(value = "生成报表", notes = "生成报表")
@RequestMapping(value = "/exportByDept", method = RequestMethod.POST)
public void exportCheckByDept(
@ApiParam(value = "查询条件") @RequestBody(required = false) List<CommonRequest> queryRequests,
HttpServletResponse response) {
ReginParams reginParams = getSelectedOrgInfo();
String orgCode = getLoginOrgCode(reginParams);
String roleTypeName = getRoleTypeName(reginParams);
HashMap<String, Object> paramMap = buildMybatisDaoCriterias(orgCode, roleTypeName);
CheckInfoPageParam param = CheckPageParamUtil.fillCheckInfoParam(queryRequests, null, paramMap);
param.setPageSize(-1);
param.setOrderBy("checkDate DESC");
Assert.notNull(param.getDepartmentId(), "部门不能为空");
checkService.getCheckInfoListResult(getToken(), getProduct(), getAppKey(), param, response);
} }
} }
...@@ -99,7 +99,6 @@ public class ExcelExportController extends BaseController { ...@@ -99,7 +99,6 @@ public class ExcelExportController extends BaseController {
private void writToResponse(Map data, HttpServletResponse response, String templateFileName, String outFileName) throws Exception { private void writToResponse(Map data, HttpServletResponse response, String templateFileName, String outFileName) throws Exception {
Resource resource = new ClassPathResource(templateFileName); Resource resource = new ClassPathResource(templateFileName);
File file = resource.getFile(); File file = resource.getFile();
TemplateExportParams params = new TemplateExportParams(file.getAbsolutePath(), true); TemplateExportParams params = new TemplateExportParams(file.getAbsolutePath(), true);
ByteArrayOutputStream bout = new ByteArrayOutputStream(); ByteArrayOutputStream bout = new ByteArrayOutputStream();
...@@ -113,6 +112,4 @@ public class ExcelExportController extends BaseController { ...@@ -113,6 +112,4 @@ public class ExcelExportController extends BaseController {
response.getOutputStream().flush(); response.getOutputStream().flush();
response.getOutputStream().close(); response.getOutputStream().close();
} }
} }
...@@ -29,6 +29,10 @@ public interface CheckMapper extends BaseMapper { ...@@ -29,6 +29,10 @@ public interface CheckMapper extends BaseMapper {
List<CheckInfoVo> getCheckInfo(CheckInfoPageParam param); List<CheckInfoVo> getCheckInfo(CheckInfoPageParam param);
List<CheckInputBo> getCheckInfoGroup(CheckInfoPageParam param);
List<CheckInputBo> getCheckInfoGroupCheckDate(CheckInfoPageParam param);
List<Map> queryUnqualifiedInputItem(@Param(value = "checkId") int checkId); List<Map> queryUnqualifiedInputItem(@Param(value = "checkId") int checkId);
List<Map> queryCheckPointInputItem(@Param(value = "planTaskId") int planTaskId, @Param(value = "pointId") int pointId); List<Map> queryCheckPointInputItem(@Param(value = "planTaskId") int planTaskId, @Param(value = "pointId") int pointId);
...@@ -227,6 +231,20 @@ public interface CheckMapper extends BaseMapper { ...@@ -227,6 +231,20 @@ public interface CheckMapper extends BaseMapper {
List<CheckAnalysisVo> getCheckStatisticalAnalysis(CheckStatisticalParam param); List<CheckAnalysisVo> getCheckStatisticalAnalysis(CheckStatisticalParam param);
/** /**
* 月度巡检情况(巡检点)
*
* @param param
* @return
*/
List<CheckAnalysisVo> getCheckStatisticalByCheck(CheckStatisticalParam param);
/**
* 月度巡检情况(巡检计划)
*
* @param param
* @return
*/
List<CheckAnalysisVo> getCheckStatisticalByPlanTask(CheckStatisticalParam param);
/**
* 根据orgCode查询公司累计巡检次数 * 根据orgCode查询公司累计巡检次数
* *
* @param loginOrgCode * @param loginOrgCode
......
...@@ -41,7 +41,6 @@ public class CheckInfoPageParam extends CommonPageable { ...@@ -41,7 +41,6 @@ public class CheckInfoPageParam extends CommonPageable {
* 点分类 0-移动 1-固定 * 点分类 0-移动 1-固定
*/ */
private String isFixed; private String isFixed;
/** /**
* 执行情况:0-计划外完成 1-按时完成 * 执行情况:0-计划外完成 1-按时完成
*/ */
...@@ -54,7 +53,6 @@ public class CheckInfoPageParam extends CommonPageable { ...@@ -54,7 +53,6 @@ public class CheckInfoPageParam extends CommonPageable {
* 所属计划 * 所属计划
*/ */
private String planId; private String planId;
/** /**
* 所属路线 * 所属路线
*/ */
...@@ -64,25 +62,25 @@ public class CheckInfoPageParam extends CommonPageable { ...@@ -64,25 +62,25 @@ public class CheckInfoPageParam extends CommonPageable {
* 机构 * 机构
*/ */
private String orgCode; private String orgCode;
/** /**
* 分类id * 分类id
*/ */
private String catalogId; private String catalogId;
private String orderBy ; private String orderBy ;
/** /**
* 部门id * 部门id
*/ */
private String departmentId; private String departmentId;
/** /**
* 其他部门人员id集合 * 其他部门人员id集合
*/ */
private List ids; private List ids;
/**
* 模板类型
*/
private String statement;
public String getOrderBy() { public String getOrderBy() {
return orderBy; return orderBy;
} }
...@@ -219,4 +217,11 @@ public class CheckInfoPageParam extends CommonPageable { ...@@ -219,4 +217,11 @@ public class CheckInfoPageParam extends CommonPageable {
this.ids = ids; this.ids = ids;
} }
public String getStatement() {
return statement;
}
public void setStatement(String statement) {
this.statement = statement;
}
} }
...@@ -13,6 +13,7 @@ public class CheckStatisticalParam { ...@@ -13,6 +13,7 @@ public class CheckStatisticalParam {
private String startTime; private String startTime;
private String endTime; private String endTime;
private String orgCode; private String orgCode;
private String queryMonth;
public String getOrgCode() { public String getOrgCode() {
return orgCode; return orgCode;
...@@ -86,6 +87,12 @@ public class CheckStatisticalParam { ...@@ -86,6 +87,12 @@ public class CheckStatisticalParam {
public void setEndTime(String endTime) { public void setEndTime(String endTime) {
this.endTime = endTime; this.endTime = endTime;
} }
public String getQueryMonth() {
return queryMonth;
}
public void setQueryMonth(String queryMonth) {
this.queryMonth = queryMonth;
}
} }
package com.yeejoin.amos.patrol.service.business.service.impl; package com.yeejoin.amos.patrol.service.business.service.impl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Joiner; import com.google.common.base.Joiner;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel; import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.DepartmentModel; import com.yeejoin.amos.feign.privilege.model.DepartmentModel;
import com.yeejoin.amos.patrol.common.core.response.AppCheckInputRespone; import com.yeejoin.amos.patrol.common.core.response.*;
import com.yeejoin.amos.patrol.common.core.response.AppPointCheckRespone;
import com.yeejoin.amos.patrol.common.core.response.CalendarStatusCountRespone;
import com.yeejoin.amos.patrol.common.core.response.CommonPage;
import com.yeejoin.amos.patrol.common.core.response.GraphInitDataResponse;
import com.yeejoin.amos.patrol.common.core.response.PatrolUserRespone;
import com.yeejoin.amos.patrol.common.core.response.PointCheckInfoRespone;
import com.yeejoin.amos.patrol.common.core.response.PointInfoResponse;
import com.yeejoin.amos.patrol.common.core.response.PointPositionInfoSyn3DRespone;
import com.yeejoin.amos.patrol.common.core.response.QueryCriteriaRespone;
import com.yeejoin.amos.patrol.common.core.response.RouteResponse;
import com.yeejoin.amos.patrol.common.core.response.bo.DepartmentBo; import com.yeejoin.amos.patrol.common.core.response.bo.DepartmentBo;
import com.yeejoin.amos.patrol.common.entity.Check; import com.yeejoin.amos.patrol.common.entity.*;
import com.yeejoin.amos.patrol.common.entity.CheckInput; import com.yeejoin.amos.patrol.common.enums.*;
import com.yeejoin.amos.patrol.common.entity.CheckShot; import com.yeejoin.amos.patrol.service.business.bo.patrol.*;
import com.yeejoin.amos.patrol.common.entity.InputItem;
import com.yeejoin.amos.patrol.common.entity.PlanTask;
import com.yeejoin.amos.patrol.common.entity.PointClassify;
import com.yeejoin.amos.patrol.common.entity.UserModel;
import com.yeejoin.amos.patrol.common.enums.CheckStatusEnum;
import com.yeejoin.amos.patrol.common.enums.PointLevelEnum;
import com.yeejoin.amos.patrol.common.enums.PointStatusEnum;
import com.yeejoin.amos.patrol.service.business.bo.patrol.CheckDetailBo;
import com.yeejoin.amos.patrol.service.business.bo.patrol.CheckInfoBo;
import com.yeejoin.amos.patrol.service.business.bo.patrol.CheckInputBo;
import com.yeejoin.amos.patrol.service.business.bo.patrol.CheckTraListBo;
import com.yeejoin.amos.patrol.service.business.bo.patrol.CheckUserBo;
import com.yeejoin.amos.patrol.service.business.bo.patrol.PlanRoutePointBo;
import com.yeejoin.amos.patrol.service.business.bo.patrol.PointCheckDetailBo;
import com.yeejoin.amos.patrol.service.business.dao.mapper.CheckMapper; import com.yeejoin.amos.patrol.service.business.dao.mapper.CheckMapper;
import com.yeejoin.amos.patrol.service.business.dao.mapper.PlanTaskDetailMapper; import com.yeejoin.amos.patrol.service.business.dao.mapper.PlanTaskDetailMapper;
import com.yeejoin.amos.patrol.service.business.dao.mapper.PlanTaskMapper; import com.yeejoin.amos.patrol.service.business.dao.mapper.PlanTaskMapper;
import com.yeejoin.amos.patrol.service.business.dao.repository.ICatalogTreeDao; import com.yeejoin.amos.patrol.service.business.dao.repository.*;
import com.yeejoin.amos.patrol.service.business.dao.repository.ICheckDao;
import com.yeejoin.amos.patrol.service.business.dao.repository.ICheckInputDao;
import com.yeejoin.amos.patrol.service.business.dao.repository.ICheckShotDao;
import com.yeejoin.amos.patrol.service.business.dao.repository.IInputItemDao;
import com.yeejoin.amos.patrol.service.business.dao.repository.IPlanDao;
import com.yeejoin.amos.patrol.service.business.dao.repository.IPlanTaskDao;
import com.yeejoin.amos.patrol.service.business.dao.repository.IPointClassifyDao;
import com.yeejoin.amos.patrol.service.business.dto.CheckDto; import com.yeejoin.amos.patrol.service.business.dto.CheckDto;
import com.yeejoin.amos.patrol.service.business.param.CheckInfoListPageParam; import com.yeejoin.amos.patrol.service.business.param.*;
import com.yeejoin.amos.patrol.service.business.param.CheckInfoPageParam;
import com.yeejoin.amos.patrol.service.business.param.CheckInputParam;
import com.yeejoin.amos.patrol.service.business.param.CheckPtListPageParam;
import com.yeejoin.amos.patrol.service.business.param.CheckRecordParam;
import com.yeejoin.amos.patrol.service.business.param.CheckStatisticalParam;
import com.yeejoin.amos.patrol.service.business.service.intfc.ICheckService; import com.yeejoin.amos.patrol.service.business.service.intfc.ICheckService;
import com.yeejoin.amos.patrol.service.business.service.intfc.IPointService;
import com.yeejoin.amos.patrol.service.business.util.CheckDetailInputPageParam; import com.yeejoin.amos.patrol.service.business.util.CheckDetailInputPageParam;
import com.yeejoin.amos.patrol.service.business.vo.CheckAnalysisVo; import com.yeejoin.amos.patrol.service.business.vo.CheckAnalysisVo;
import com.yeejoin.amos.patrol.service.business.vo.CheckInfoVo; import com.yeejoin.amos.patrol.service.business.vo.CheckInfoVo;
import com.yeejoin.amos.patrol.service.constants.XJConstant; import com.yeejoin.amos.patrol.service.constants.XJConstant;
import com.yeejoin.amos.patrol.service.core.async.AsyncTask; import com.yeejoin.amos.patrol.service.core.async.AsyncTask;
import com.yeejoin.amos.patrol.service.core.util.DateUtil; import com.yeejoin.amos.patrol.service.core.util.DateUtil;
import com.yeejoin.amos.patrol.service.core.util.ReflectUtil;
import com.yeejoin.amos.patrol.service.core.util.StringUtil; import com.yeejoin.amos.patrol.service.core.util.StringUtil;
import com.yeejoin.amos.patrol.service.remote.RemoteSecurityService; import com.yeejoin.amos.patrol.service.remote.RemoteSecurityService;
//import com.yeejoin.amos.security.common.model.UserModel;
import net.sf.json.JSONArray; import net.sf.json.JSONArray;
import net.sf.json.JSONObject; import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
...@@ -76,18 +47,13 @@ import org.springframework.stereotype.Service; ...@@ -76,18 +47,13 @@ import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional; import javax.transaction.Transactional;
import java.io.File; import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.*;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static com.yeejoin.amos.patrol.service.constants.XJConstant.*; import static com.yeejoin.amos.patrol.service.constants.XJConstant.*;
...@@ -129,6 +95,9 @@ public class CheckServiceImpl implements ICheckService { ...@@ -129,6 +95,9 @@ public class CheckServiceImpl implements ICheckService {
private IPointClassifyDao iPointClassifyDao; private IPointClassifyDao iPointClassifyDao;
@Autowired @Autowired
private IPointService iPointService;
@Autowired
private AsyncTask asyncTask; private AsyncTask asyncTask;
@Value("${upload.server.address}") @Value("${upload.server.address}")
...@@ -309,7 +278,7 @@ public class CheckServiceImpl implements ICheckService { ...@@ -309,7 +278,7 @@ public class CheckServiceImpl implements ICheckService {
checkInput.setPointClassifyName(pointClassifyName); checkInput.setPointClassifyName(pointClassifyName);
checkItemList.add(checkInput); checkItemList.add(checkInput);
} }
if (isPushFlag){ if (isPushFlag) {
asyncTask.pushChartResulPaytask();//更新支付业务刷新标识 asyncTask.pushChartResulPaytask();//更新支付业务刷新标识
} }
if (!ObjectUtils.isEmpty(error) && error.endsWith(";")) { if (!ObjectUtils.isEmpty(error) && error.endsWith(";")) {
...@@ -385,7 +354,9 @@ public class CheckServiceImpl implements ICheckService { ...@@ -385,7 +354,9 @@ public class CheckServiceImpl implements ICheckService {
score = jsonObject.getInt(XJConstant.INPUT_ITEM_OK_SCORE); score = jsonObject.getInt(XJConstant.INPUT_ITEM_OK_SCORE);
} }
} }
if (XJConstant.YES.equals(isScore)) checkInput.setScore(score); if (XJConstant.YES.equals(isScore)) {
checkInput.setScore(score);
}
return checkInput; return checkInput;
} }
...@@ -426,7 +397,9 @@ public class CheckServiceImpl implements ICheckService { ...@@ -426,7 +397,9 @@ public class CheckServiceImpl implements ICheckService {
checkInput.setIsOk(XJConstant.OK); checkInput.setIsOk(XJConstant.OK);
score = OkScore; score = OkScore;
} }
if (XJConstant.YES.equals(isScore)) checkInput.setScore(score); if (XJConstant.YES.equals(isScore)) {
checkInput.setScore(score);
}
return checkInput; return checkInput;
} }
...@@ -455,7 +428,9 @@ public class CheckServiceImpl implements ICheckService { ...@@ -455,7 +428,9 @@ public class CheckServiceImpl implements ICheckService {
} }
} }
} }
if (XJConstant.YES.equals(isScore)) checkInput.setScore(score); if (XJConstant.YES.equals(isScore)) {
checkInput.setScore(score);
}
return checkInput; return checkInput;
} }
...@@ -997,83 +972,57 @@ public class CheckServiceImpl implements ICheckService { ...@@ -997,83 +972,57 @@ public class CheckServiceImpl implements ICheckService {
} }
} }
} }
} }
return pointInfoResponseList; return pointInfoResponseList;
} }
@Override @Override
public List<CheckAnalysisVo> getCheckStatisticalAnalysis(String toke,String product,String appKey,CheckStatisticalParam param) { public List<CheckAnalysisVo> getCheckStatisticalAnalysis(String toke, String product, String appKey, CheckStatisticalParam param) {
List<CheckAnalysisVo> checkAnalysisVos = checkMapper.getCheckStatisticalAnalysis(param); List<CheckAnalysisVo> checkAnalysisVos = checkMapper.getCheckStatisticalAnalysis(param);
if(param.getStatisticsTyle()==4){ if (param.getStatisticsTyle() == 4) {
//处理用户信息
String userIds = "";
//处理用户信息
String userIds="";
Set<String> set = new HashSet<>(); Set<String> set = new HashSet<>();
checkAnalysisVos.forEach(s -> { checkAnalysisVos.forEach(s -> {
set.add(s.getName().toString());
set.add(s.getName().toString());
}); });
List<String> list1 = new ArrayList<>(set); List<String> list1 = new ArrayList<>(set);
userIds = String.join(",", list1); userIds = String.join(",", list1);
List<AgencyUserModel> listd = remoteSecurityService.listUserByUserIds(toke, product, appKey, userIds);
List<AgencyUserModel> listd=remoteSecurityService.listUserByUserIds( toke, product, appKey, userIds);
//新安全 //新安全
checkAnalysisVos.forEach(s -> { checkAnalysisVos.forEach(s -> {
listd.forEach(s1 -> { listd.forEach(s1 -> {
if (s.getName().equals(s1.getUserId())) {
if(s.getName().equals(s1.getUserId())){ s.setName(s1.getUserName());
}
s.setName(s1.getUserName()); } });
});
}); } else if (param.getStatisticsTyle() == 3) {
}); String dep = "";
Set<String> set = new HashSet<>();
checkAnalysisVos.forEach(s -> {
}else if(param.getStatisticsTyle()==3){ set.add(s.getName().toString());
});
String dep="";
Set<String> set = new HashSet<>(); List<String> list1 = new ArrayList<>(set);
checkAnalysisVos.forEach(s -> { dep = String.join(",", list1);
set.add(s.getName().toString()); List<LinkedHashMap> listd = remoteSecurityService.listDepartmentByDeptIds(toke, product, appKey, dep);
}); //新安全
checkAnalysisVos.forEach(s -> {
List<String> list1 = new ArrayList<>(set); listd.forEach(s1 -> {
dep = String.join(",", list1); if (s.getName().equals(s1.get("sequenceNbr") + "")) {
s.setName(s1.get("departmentName") + "");
}
List<LinkedHashMap> listd=remoteSecurityService.listDepartmentByDeptIds( toke, product, appKey, dep); });
});
//新安全
checkAnalysisVos.forEach(s -> {
listd.forEach(s1 -> {
if(s.getName().equals(s1.get("sequenceNbr")+"")){
s.setName(s1.get("departmentName")+""); }
});
});
} }
CheckAnalysisVo countVo = new CheckAnalysisVo(); CheckAnalysisVo countVo = new CheckAnalysisVo();
int planTaskCount = 0; int planTaskCount = 0;
int checkCount = 0; int checkCount = 0;
...@@ -1100,21 +1049,66 @@ public class CheckServiceImpl implements ICheckService { ...@@ -1100,21 +1049,66 @@ public class CheckServiceImpl implements ICheckService {
countVo.setOk(String.valueOf(ok)); countVo.setOk(String.valueOf(ok));
countVo.setFaild(String.valueOf(faild)); countVo.setFaild(String.valueOf(faild));
countVo.setMissed(String.valueOf(missed)); countVo.setMissed(String.valueOf(missed));
if(size==0){ if (size == 0) {
countVo.setScore("0"); countVo.setScore("0");
countVo.setMissedRate("0"); countVo.setMissedRate("0");
countVo.setFaildRate("0"); countVo.setFaildRate("0");
}else{ } else {
countVo.setScore(String.valueOf(score / size)); countVo.setScore(String.valueOf(score / size));
countVo.setMissedRate(String.valueOf(missedRate / size)); countVo.setMissedRate(String.valueOf(missedRate / size));
countVo.setFaildRate(String.valueOf(faildRate / size)); countVo.setFaildRate(String.valueOf(faildRate / size));
} }
checkAnalysisVos.add(countVo); checkAnalysisVos.add(countVo);
return checkAnalysisVos; return checkAnalysisVos;
} }
@Override @Override
public Map<String, Object> getCheckStatisticalByMonth(String toke, String product, String appKey, CheckStatisticalParam param, String companyId) {
Map<String, Object> map = new HashMap<>();
List<DepartmentModel> treeBos = remoteSecurityService.getDepartmentTreeByCompanyId(toke, product, appKey, companyId);
List<CheckAnalysisVo> checkAnalysisVos = null;
if (param.getStatisticsTyle() == 0) {
checkAnalysisVos = checkMapper.getCheckStatisticalByPlanTask(param);
} else {
checkAnalysisVos = checkMapper.getCheckStatisticalByCheck(param);
}
List<String> dayByMonth = DateUtil.getDayByMonth(param.getStartTime(), param.getEndTime());
String dep = "";
Set<String> set = new HashSet<>();
checkAnalysisVos.forEach(s -> {
if (!ObjectUtils.isEmpty(s.getName())){
set.add(s.getName().toString());
}
});
List<String> list1 = new ArrayList<>(set);
dep = String.join(",", list1);
List<LinkedHashMap> listd = remoteSecurityService.listDepartmentByDeptIds(toke, product, appKey, dep);
//新安全
checkAnalysisVos.forEach(s -> {
listd.forEach(s1 -> {
if (!ObjectUtils.isEmpty(s.getName()) && s.getName().equals(s1.get("sequenceNbr"))) {
s.setName(DeptEnum.getEnumCode(s1.get("departmentName") + ""));
}
});
});
List<Map<String, Object>> result = getResult(treeBos, checkAnalysisVos, dayByMonth);
String[] split = param.getQueryMonth().split("-");
map.put("year", split[0]);
map.put("month", split[1]);
map.put("titles", getList(treeBos));
map.put("content", result);
return map;
}
@Override
public long getCumulativeCheckCountByOrgCode(String loginOrgCode) { public long getCumulativeCheckCountByOrgCode(String loginOrgCode) {
return checkMapper.getCumulativeCheckCountByOrgCode(loginOrgCode); return checkMapper.getCumulativeCheckCountByOrgCode(loginOrgCode);
} }
...@@ -1139,5 +1133,494 @@ public class CheckServiceImpl implements ICheckService { ...@@ -1139,5 +1133,494 @@ public class CheckServiceImpl implements ICheckService {
return checkMapper.getCheckPhotosByCheckAndInputIdAndClassifyId(checkId, checkInputId, classifyId); return checkMapper.getCheckPhotosByCheckAndInputIdAndClassifyId(checkId, checkInputId, classifyId);
} }
@Override
public void getCheckInfoListResult(String toke, String product, String appKey, CheckInfoPageParam param, HttpServletResponse response) {
Map<String, Object> map = new HashMap<>();
List<CheckInputBo> checkInfoList = checkMapper.getCheckInfoGroup(param);
List<Map<String, Object>> list = new ArrayList<>();
List<String> titles = Lists.newArrayList();//标题
String[] sp = new String[0];
int mergeNum = 4;//合并列
String template = null;
if (param.getStatement().equals(ExcelEnum.TECHNOLOGY.getType())) {
template = "技术模板";
titles.add("巡检点");
titles.add("分类");
titles.add("检查内容");
String beginTimeStr = checkMapper.getCheckInfoGroupCheckDate(param).get(0).getBeginTimeStr();
sp = beginTimeStr.split(",");
for (int i = 0; i < sp.length; i++) {
titles.add(sp[i].substring(11, sp[i].length()));
}
String[] finalSp = sp;
mergeNum = finalSp.length + 2;
checkInfoList.forEach(
x -> {
Map<String, Object> properties = Maps.newHashMap();
Map<String, Object> stateMap = getStateMap(x.getIdStateStr());
for (int i = 0; i < finalSp.length; i++) {
if (!stateMap.containsKey(finalSp[i])) {
properties.put(finalSp[i], "");
} else {
properties.put(finalSp[i], CheckStatusEnum.getEnum(stateMap.get(finalSp[i]).toString()).getName());
}
}
try {
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> target = JSONUtil.toMap(mapper.writeValueAsString(ReflectUtil.getObject(x, properties)));
list.add(target);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
stateMap.clear();
}
);
} else {
template = "业务模板";
titles.add("检查时间");
titles.add("巡检点");
titles.add("分类");
titles.add("检查内容");
titles.add("检查结果");
}
List<LinkedHashMap> listd = remoteSecurityService.listDepartmentByDeptIds(toke, product, appKey, param.getDepartmentId());
LinkedHashMap linkMap = listd.get(0);
String companyName = remoteSecurityService.getCompanyName(toke, product, appKey, linkMap.get("companySeq").toString());
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet(template);
//表头字体
Font headerFont = wb.createFont();
headerFont.setFontName("微软雅黑");
headerFont.setFontHeightInPoints((short) 14);
headerFont.setBoldweight(Font.BOLDWEIGHT_NORMAL);
headerFont.setColor(HSSFColor.BLACK.index);
//正文字体
Font contextFont = wb.createFont();
contextFont.setFontName("微软雅黑");
contextFont.setFontHeightInPoints((short) 10);
contextFont.setBoldweight(Font.BOLDWEIGHT_NORMAL);
contextFont.setColor(HSSFColor.BLACK.index);
//表头样式,左右上下居中
CellStyle headerStyle = wb.createCellStyle();
headerStyle.setFont(headerFont);
headerStyle.setAlignment(CellStyle.ALIGN_CENTER);// 左右居中
headerStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 上下居中
headerStyle.setLocked(true);
headerStyle.setWrapText(false);// 自动换行
headerStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
headerStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
headerStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
headerStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
//内容样式
CellStyle contentStyle = wb.createCellStyle();
contentStyle.setFont(contextFont);
contentStyle.setAlignment(CellStyle.ALIGN_CENTER);// 左右居中
contentStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 上下居中
contentStyle.setLocked(true);
contentStyle.setWrapText(false);// 自动换行
contentStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
contentStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
contentStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
contentStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
//内容样式左对齐
CellStyle alignLeftStyle = wb.createCellStyle();
alignLeftStyle.setFont(contextFont);
alignLeftStyle.setAlignment(CellStyle.ALIGN_LEFT);// 左对齐
alignLeftStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 上下居中
alignLeftStyle.setLocked(true);
alignLeftStyle.setWrapText(false);// 自动换行
alignLeftStyle.setAlignment(CellStyle.ALIGN_LEFT);// 左对齐
alignLeftStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
alignLeftStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
alignLeftStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
alignLeftStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
// 行号
int rowNum = 0;
//设置列宽
if (param.getStatement().equals(ExcelEnum.TECHNOLOGY.getType())) {
for (int i = 0; i < 3; i++) {
if (i >= 0 && i < 2) {
sheet.setColumnWidth(i, 6000);
} else if (i == 2) {
sheet.setColumnWidth(i, 8000);
} else {
sheet.setColumnWidth(i, 3000);
}
}
} else {
for (int i = 0; i < 5; i++) {
if (i == 2) {
sheet.setColumnWidth(i, 8000);
} else {
sheet.setColumnWidth(i, 6000);
}
}
}
//合并单元格
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, mergeNum));
sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, mergeNum));
//第一行
HSSFRow head = sheet.createRow(rowNum++);
head.setHeightInPoints(30);
HSSFCell hssfCell = head.createCell(0);
hssfCell.setCellValue(String.format("%s %s 每日巡检情况表", companyName, linkMap.get("departmentName").toString()));
hssfCell.setCellStyle(headerStyle);
//第二行
HSSFRow nextHead = sheet.createRow(rowNum++);
nextHead.setHeightInPoints(30);
HSSFCell nextHssfCell = nextHead.createCell(0);
nextHssfCell.setCellValue("巡检人:____________ 日期: 年___月___日至___日");
nextHssfCell.setCellStyle(headerStyle);
HSSFRow row = sheet.createRow(rowNum++);
HSSFCell cell = null;
//创建标题
for (int i = 0; i < titles.size(); i++) {
cell = row.createCell(i);
cell.setCellValue(titles.get(i));
cell.setCellStyle(contentStyle);
}
if (param.getStatement().equals(ExcelEnum.TECHNOLOGY.getType())) {
setRowTechnology(list, sheet, contentStyle, alignLeftStyle, sp);
} else {
setRow(checkInfoList, sheet, contentStyle, alignLeftStyle);
}
try {
OutputStream out = response.getOutputStream();
wb.write(out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private Map<String, Object> getStateMap(String idState){
Map<String, Object> idStateMap = Maps.newHashMap();
String[] split = idState.split(",");
for (int i = 0; i < split.length; i++) {
String[] sp = split[i].split("_");
idStateMap.put(sp[0], sp[1]);
}
return idStateMap;
}
/**
* 业务模板设置
*/
private void setRow(List<CheckInputBo> checkInfoList, HSSFSheet sheet, CellStyle contentStyle, CellStyle alignLeftStyle) {
int num = 3;
HSSFRow row = sheet.createRow(num);
//创建内容
List<String> tempDate = new ArrayList<>();
//初始化起始行和结束行
int startRow1 = num;
int endRow1 = num;
int temNum1 = num;
int startRow2 = num;
int endRow2 = num;
int temNum2 = num;
int startRow3 = num;
int endRow3 = num;
int temNum3 = num;
//当前日期
String lastDate = "";
String lastPointName = "";
String lastClassifyName = "";
//用来记录是否是第一次循环
boolean flag1 = true;
boolean flag2 = true;
boolean flag3 = true;
for (int i = 0; i < checkInfoList.size(); i++) {
String checkDate = checkInfoList.get(i).getCheckDate();
String pointName = checkInfoList.get(i).getPointName();
String classifyName = checkInfoList.get(i).getClassifyName();
if (flag1) {
lastDate = checkDate;
flag1 = false;
}
if (i != 0 && lastDate.equals(checkDate)) {
endRow1++;
} else {
//两者不相同时,融合之前相同的行
if (endRow1 > startRow1) {
sheet.addMergedRegion(new CellRangeAddress(startRow1, endRow1, 0, 0));
}
startRow1 = temNum1;
endRow1 = startRow1;
lastDate = checkDate;
}
temNum1++;
if (i == checkInfoList.size() - 1 && startRow1 != endRow1) {
//融合最后相同的行
sheet.addMergedRegion(new CellRangeAddress(startRow1, endRow1, 0, 0));
}
if (flag2) {
lastPointName = pointName;
flag2 = false;
}
if (i != 0 && lastPointName.equals(pointName)) {
endRow2++;
} else {
//两者不相同时,融合之前相同的行
if (endRow2 > startRow2) {
sheet.addMergedRegion(new CellRangeAddress(startRow2, endRow2, 1, 1));
}
startRow2 = temNum2;
endRow2 = startRow2;
lastPointName = pointName;
}
temNum2++;
if (i == checkInfoList.size() - 1 && startRow2 != endRow2) {
//融合最后相同的行
sheet.addMergedRegion(new CellRangeAddress(startRow2, endRow2, 1, 1));
}
if (flag3) {
lastClassifyName = classifyName;
flag3 = false;
}
if (i != 0 && lastClassifyName.equals(classifyName)) {
endRow3++;
} else {
//两者不相同时,融合之前相同的行
if (endRow3 > startRow3) {
sheet.addMergedRegion(new CellRangeAddress(startRow3, endRow3, 2, 2));
}
startRow3 = temNum3;
endRow3 = startRow3;
lastClassifyName = classifyName;
}
temNum3++;
if (i == checkInfoList.size() - 1 && startRow3 != endRow3) {
//融合最后相同的行
sheet.addMergedRegion(new CellRangeAddress(startRow3, endRow3, 2, 2));
}
row = sheet.createRow(i + 3);
HSSFCell cell = row.createCell(0);
if (ObjectUtils.isEmpty(checkInfoList.get(i).getBeginTime())){
cell.setCellValue(DateUtil.splitDate(checkInfoList.get(i).getCheckDate()));
} else {
cell.setCellValue(DateUtil.splitDate(checkInfoList.get(i).getBeginTime()));
}
cell.setCellStyle(contentStyle);
HSSFCell cell1 = row.createCell(1);
cell1.setCellValue(checkInfoList.get(i).getPointName());
cell1.setCellStyle(contentStyle);
HSSFCell cell2 = row.createCell(2);
cell2.setCellStyle(contentStyle);
cell2.setCellValue(checkInfoList.get(i).getClassifyName());
HSSFCell cell3 = row.createCell(3);
cell3.setCellValue(checkInfoList.get(i).getInputItemName());
cell3.setCellStyle(alignLeftStyle);
HSSFCell cell4 = row.createCell(4);
cell4.setCellValue(checkInfoList.get(i).getIsOK());
cell4.setCellStyle(alignLeftStyle);
}
}
/**
* 技术模板设置
*/
private void setRowTechnology(List<Map<String, Object>> checkInfoList, HSSFSheet sheet, CellStyle contentStyle, CellStyle alignLeftStyle, String[] sp) {
int num = 3;
HSSFRow row = sheet.createRow(num);
//创建内容
List<String> tempDate = new ArrayList<>();
//初始化起始行和结束行
int startRow1 = num;
int endRow1 = num;
int temNum1 = num;
int startRow2 = num;
int endRow2 = num;
int temNum2 = num;
//当前日期
String lastPointName = "";
String lastClassifyName = "";
//用来记录是否是第一次循环
boolean flag1 = true;
boolean flag2 = true;
for (int i = 0; i < checkInfoList.size(); i++) {
String pointName = checkInfoList.get(i).get("pointName").toString();
String classifyName = checkInfoList.get(i).get("classifyName").toString();
if (flag1) {
lastPointName = pointName;
flag1 = false;
}
if (i != 0 && lastPointName.equals(pointName)) {
endRow1++;
} else {
//两者不相同时,融合之前相同的行
if (endRow1 > startRow1) {
sheet.addMergedRegion(new CellRangeAddress(startRow1, endRow1, 0, 0));
}
startRow1 = temNum1;
endRow1 = startRow1;
lastPointName = pointName;
}
temNum1++;
if (i == checkInfoList.size() - 1 && startRow1 != endRow1) {
//融合最后相同的行
sheet.addMergedRegion(new CellRangeAddress(startRow1, endRow1, 0, 0));
}
if (flag2) {
lastClassifyName = classifyName;
flag2 = false;
}
if (i != 0 && lastClassifyName.equals(classifyName)) {
endRow2++;
} else {
//两者不相同时,融合之前相同的行
if (endRow2 > startRow2) {
sheet.addMergedRegion(new CellRangeAddress(startRow2, endRow2, 1, 1));
}
startRow2 = temNum2;
endRow2 = startRow2;
lastClassifyName = classifyName;
}
temNum2++;
if (i == checkInfoList.size() - 1 && startRow2 != endRow2) {
//融合最后相同的行
sheet.addMergedRegion(new CellRangeAddress(startRow2, endRow2, 1, 1));
}
row = sheet.createRow(i + 3);
HSSFCell cell = row.createCell(0);
cell.setCellValue(checkInfoList.get(i).get("pointName").toString());
cell.setCellStyle(contentStyle);
HSSFCell cell1 = row.createCell(1);
cell1.setCellValue(checkInfoList.get(i).get("classifyName").toString());
cell1.setCellStyle(contentStyle);
HSSFCell cell2 = row.createCell(2);
cell2.setCellStyle(contentStyle);
cell2.setCellValue(checkInfoList.get(i).get("inputItemName").toString());
for (int j = 0; j < sp.length; j++) {
Map<String, Object> checkInfoMap = checkInfoList.get(i);
HSSFCell cellA = row.createCell(3 + j);
cellA.setCellValue(checkInfoMap.get(sp[j]).toString());
cellA.setCellStyle(alignLeftStyle);
}
}
}
private List<Map<String, Object>> getList(List<DepartmentModel> treeBos) {
List<Map<String, Object>> list = new ArrayList<>();
treeBos.forEach(
x -> {
if (!ObjectUtils.isEmpty(x.getChildren())) {
Collection<Map> children = x.getChildren();
children.forEach(
y -> {
Map<String, Object> map = new HashMap<>();
String key = DeptEnum.getEnumCode(y.get("departmentName").toString());
map.put("key", key);
map.put("label", y.get("departmentName").toString());
list.add(map);
}
);
}
}
);
return list;
}
/**
* 转化Map
*
* @param treeBos
* @param checkAnalysisVos
* @return
*/
private List<Map<String, Object>> getResult(List<DepartmentModel> treeBos, List<CheckAnalysisVo> checkAnalysisVos, List<String> dayByMonth) {
List<Map<String, Object>> result = new ArrayList<>();
Map<String, Object> totalMap = new HashMap<>();
totalMap.put("month", "合计");
List<CheckAnalysisVo> totals = checkAnalysisVos.stream().filter(x -> "合计".equals(x.getName())).collect(Collectors.toList());
dayByMonth.forEach(
day -> {
Map<String, Object> mapX = new HashMap<>();
mapX.put("month", day);
treeBos.forEach(
x -> {
if (!ObjectUtils.isEmpty(x.getChildren())) {
Collection<Map> children = x.getChildren();
children.forEach(
y -> {
String key = DeptEnum.getEnumCode(y.get("departmentName").toString());
List<CheckAnalysisVo> collect = checkAnalysisVos.stream().filter(z -> key.equals(z.getName()) && z.getCheckTime().equals(day)).collect(Collectors.toList());
String plantaskCount = getCount(collect, PLANTASK_COUNT);
String checkCount = getCount(collect, CHECK_COUNT);
String missed = getCount(collect, MISSED);
String faild = getCount(collect, FAILD);
mapX.put(PLANTASK_COUNT + key, plantaskCount);
mapX.put(CHECK_COUNT + key, checkCount);
mapX.put(MISSED + key, missed);
mapX.put(FAILD + key, faild);
getTotal(totalMap, PLANTASK_COUNT, key, Long.valueOf(plantaskCount));
getTotal(totalMap, CHECK_COUNT, key, Long.valueOf(checkCount));
getTotal(totalMap, MISSED, key, Long.valueOf(missed));
getTotal(totalMap, FAILD, key, Long.valueOf(faild));
}
);
}
}
);
result.add(mapX);
}
);
result.add(totalMap);
return result;
}
private String getCount(List<CheckAnalysisVo> collect, String field) {
String num = "0";
if (!ObjectUtils.isEmpty(collect)) {
switch (field) {
case PLANTASK_COUNT:
num = collect.get(0).getPlanTaskCount();
break;
case CHECK_COUNT:
num = collect.get(0).getCheckCount();
break;
case MISSED:
num = collect.get(0).getMissed();
break;
case FAILD:
num = collect.get(0).getFaild();
break;
}
}
return num;
}
/**
* 统计总数
*/
private void getTotal(Map<String, Object> totalMap, String type, String key, Long num) {
long total = 0;
if (!ObjectUtils.isEmpty(totalMap.get(type + key))) {
total = Long.valueOf(totalMap.get(type + key).toString());
}
num += total;
totalMap.put(type + key, num.toString());
}
} }
...@@ -28,7 +28,9 @@ import com.yeejoin.amos.patrol.service.business.vo.CheckInfoVo; ...@@ -28,7 +28,9 @@ import com.yeejoin.amos.patrol.service.business.vo.CheckInfoVo;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap; import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
...@@ -193,7 +195,6 @@ public interface ICheckService { ...@@ -193,7 +195,6 @@ public interface ICheckService {
* @return * @return
*/ */
QueryCriteriaRespone findCheckSystemInit(String toke,String product,String appKey,String type, String orgCode, String roleTypeName, String departmentId, String companyId); QueryCriteriaRespone findCheckSystemInit(String toke,String product,String appKey,String type, String orgCode, String roleTypeName, String departmentId, String companyId);
/** /**
* 巡检记录查询 * 巡检记录查询
* *
...@@ -203,14 +204,12 @@ public interface ICheckService { ...@@ -203,14 +204,12 @@ public interface ICheckService {
Page<CheckInfoBo> getCheckInfoList(CheckInfoListPageParam params); Page<CheckInfoBo> getCheckInfoList(CheckInfoListPageParam params);
Page<PointCheckInfoRespone> getCheckInfoList1(CheckInfoListPageParam params); Page<PointCheckInfoRespone> getCheckInfoList1(CheckInfoListPageParam params);
/** /**
* 视图模块初始化数据 * 视图模块初始化数据
* *
* @return * @return
*/ */
public GraphInitDataResponse getViewModuleInitData(); public GraphInitDataResponse getViewModuleInitData();
/** /**
* 巡检情况统计分析 * 巡检情况统计分析
* *
...@@ -218,7 +217,13 @@ public interface ICheckService { ...@@ -218,7 +217,13 @@ public interface ICheckService {
* @return * @return
*/ */
List<CheckAnalysisVo> getCheckStatisticalAnalysis(String toke,String product,String appKey,CheckStatisticalParam queryRequests); List<CheckAnalysisVo> getCheckStatisticalAnalysis(String toke,String product,String appKey,CheckStatisticalParam queryRequests);
/**
* 月度巡检情况
*
* @param queryRequests
* @return
*/
Map<String, Object> getCheckStatisticalByMonth(String toke, String product, String appKey, CheckStatisticalParam queryRequests, String companyId);
/** /**
* 根据orgcODE获取巡检累计个数 * 根据orgcODE获取巡检累计个数
* *
...@@ -226,7 +231,6 @@ public interface ICheckService { ...@@ -226,7 +231,6 @@ public interface ICheckService {
* @return * @return
*/ */
long getCumulativeCheckCountByOrgCode(String loginOrgCode); long getCumulativeCheckCountByOrgCode(String loginOrgCode);
/** /**
* 根据条件查询日巡检统计情况 * 根据条件查询日巡检统计情况
* *
...@@ -240,4 +244,6 @@ public interface ICheckService { ...@@ -240,4 +244,6 @@ public interface ICheckService {
List<String> getLivePhotos(Long checkID); List<String> getLivePhotos(Long checkID);
List<String> getCheckPhotosByCheckAndInputIdAndClassifyId(int checkId, int checkInputId, int classifyId); List<String> getCheckPhotosByCheckAndInputIdAndClassifyId(int checkId, int checkInputId, int classifyId);
void getCheckInfoListResult(String toke,String product,String appKey,CheckInfoPageParam param, HttpServletResponse response);
} }
...@@ -52,6 +52,10 @@ public class CheckPageParamUtil { ...@@ -52,6 +52,10 @@ public class CheckPageParamUtil {
param.setDepartmentId(toString(queryRequests.get(i).getValue())); param.setDepartmentId(toString(queryRequests.get(i).getValue()));
} else if ("planId".equals(name)) { } else if ("planId".equals(name)) {
param.setPlanId(toString(queryRequests.get(i).getValue())); param.setPlanId(toString(queryRequests.get(i).getValue()));
} else if ("deptId".equals(name)) {
param.setDepartmentId(toString(queryRequests.get(i).getValue()));
} else if ("statement".equals(name)) {
param.setStatement(toString(queryRequests.get(i).getValue()));
} }
} }
if (param.getBeginDate() != null && param.getEndDate() == null) { if (param.getBeginDate() != null && param.getEndDate() == null) {
......
package com.yeejoin.amos.patrol.service.business.util; package com.yeejoin.amos.patrol.service.business.util;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.io.BufferedInputStream; import java.io.*;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.channels.Channel; import java.nio.channels.Channel;
...@@ -35,6 +20,8 @@ import javax.imageio.ImageIO; ...@@ -35,6 +20,8 @@ import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.excel.export.template.ExcelExportOfTemplateUtil;
import com.yeejoin.amos.patrol.service.exception.YeeException; import com.yeejoin.amos.patrol.service.exception.YeeException;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
...@@ -78,1136 +65,1140 @@ import cn.afterturn.easypoi.excel.entity.ExportParams; ...@@ -78,1136 +65,1140 @@ import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams; import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType; import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
/** /**
*
* 类描述: 包括功能、用途、现存BUG,以及其它别人可能感兴趣的介绍。 * 类描述: 包括功能、用途、现存BUG,以及其它别人可能感兴趣的介绍。
* *
* @see 需要参见的其它类(可选) * @author <a href="mailto:Ydm@nationsky.com">Ydm</a>
* @version 1.0 * @version 1.0
* @date 2016年7月27日 * @date 2016年7月27日
* @author <a href="mailto:Ydm@nationsky.com">Ydm</a> * @see 需要参见的其它类(可选)
* @since JDK 1.7 * @since JDK 1.7
*/ */
public class FileHelper { public class FileHelper {
private static final Logger log = Logger.getLogger(FileHelper.class); private static final Logger log = Logger.getLogger(FileHelper.class);
/** /**
* * @param file
* @param file * @return
* @return */
*/ public static boolean isExcel2003(File file) {
public static boolean isExcel2003(File file) { InputStream is = null;
InputStream is = null; Workbook wb = null;
Workbook wb = null; try {
try { is = new FileInputStream(file);
is = new FileInputStream(file); wb = WorkbookFactory.create(is);
wb = WorkbookFactory.create(is); if (wb instanceof XSSFWorkbook) {
if (wb instanceof XSSFWorkbook) { return false;
return false; } else if (wb instanceof HSSFWorkbook) {
} else if (wb instanceof HSSFWorkbook) { return true;
}
} catch (Exception e) {
return false;
} finally {
try {
if (null != is) {
is.close();
}
if (null != wb) {
wb.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return true; return true;
} }
} catch (Exception e) {
return false; /**
} finally { * @param file
try { * @return
if (null != is) { */
is.close(); public static boolean isWord2003(File file) {
InputStream is = null;
try {
is = new FileInputStream(file);
new HWPFDocument(is);
} catch (Exception e) {
return false;
} finally {
try {
if (null != is) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
} }
if (null != wb) { return true;
wb.close(); }
public static boolean isWord2007(File file) {
InputStream is = null;
try {
is = new FileInputStream(file);
new XWPFDocument(is).close();
} catch (Exception e) {
return false;
} finally {
try {
if (null != is) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
} }
} catch (IOException e) { return true;
e.printStackTrace();
}
} }
return true;
} /**
* @param file
/** * @return
* */
* @param file public static boolean isPPT2003(File file) {
* @return InputStream is = null;
*/ HSLFSlideShow ppt = null;
public static boolean isWord2003(File file) { try {
InputStream is = null; is = new FileInputStream(file);
try { ppt = new HSLFSlideShow(is);
is = new FileInputStream(file); } catch (Exception e) {
new HWPFDocument(is); return false;
} catch (Exception e) { } finally {
return false; try {
} finally { if (null != is) {
try { is.close();
if (null != is) { }
is.close(); if (null != ppt) {
ppt.close();
}
} catch (IOException e) {
e.printStackTrace();
}
} }
} catch (IOException e) { return true;
e.printStackTrace();
}
} }
return true;
} /**
* @param path
public static boolean isWord2007(File file) { * @return
InputStream is = null; */
try { public static StringBuffer readFile(String path) {
is = new FileInputStream(file); StringBuffer buffer = new StringBuffer();
new XWPFDocument(is).close(); InputStream is = null;
} catch (Exception e) { BufferedReader br = null;
return false; try {
} finally { File file = new File(path);
try { if (file.exists()) {
if (null != is) { is = new FileInputStream(file);
is.close(); br = new BufferedReader(new InputStreamReader(is));
String content = br.readLine();
while (null != content) {
buffer.append(content);
content = br.readLine();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != is) {
is.close();
}
if (null != br) {
br.close();
}
} catch (Exception e) {
e.printStackTrace();
}
} }
} catch (IOException e) {
e.printStackTrace(); return buffer;
}
} }
return true;
} /**
* 读取文件,并按照指定的分割符保存文件
/** *
* * @param path 文件的路径
* @param file * @param split 分割内容的标识
* @return * @return 按照传入的分割符,标识的字符串
*/ */
public static boolean isPPT2003(File file) { public static StringBuffer readFile(String path, String split) {
InputStream is = null; StringBuffer buffer = new StringBuffer();
HSLFSlideShow ppt = null; InputStream is = null;
try { BufferedReader br = null;
is = new FileInputStream(file); try {
ppt = new HSLFSlideShow(is); File file = new File(path);
} catch (Exception e) { if (file.exists()) {
return false; is = new FileInputStream(file);
} finally { br = new BufferedReader(new InputStreamReader(is));
try { String content = br.readLine();
if (null != is) { while (null != content) {
is.close(); buffer.append(content).append(split);
content = br.readLine();
}
}
} catch (Exception exception) {
exception.printStackTrace();
} finally {
try {
if (null != is) {
is.close();
}
if (null != br) {
br.close();
}
} catch (Exception exception2) {
exception2.printStackTrace();
}
} }
if (null != ppt) {
ppt.close(); return buffer;
}
/**
* 将传入的字符串写入到指定的路径的文件下
*
* @param content 将要写入文件的内容
* @param path 写入内容的文件路径
*/
public static void writeFile(String content, String path) {
OutputStream fos = null;
BufferedWriter bw = null;
try {
File file = new File(path);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
fos = new FileOutputStream(file);
bw = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8"));
bw.write(content);
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (bw != null) {
bw.close();
}
} catch (IOException ioException) {
System.err.println(ioException.getMessage());
}
} }
} catch (IOException e) {
e.printStackTrace();
}
} }
return true;
} /**
* 将图片写成html文件
/** *
* * @param size 图片数量
* @param path * @param path 保存html文件全路径
* @return * @param fileName 图片路径
*/ */
public static StringBuffer readFile(String path) { public static void writeHtmlFile(int size, String path, String fileName) {
StringBuffer buffer = new StringBuffer(); StringBuffer buffer = new StringBuffer();
InputStream is = null; buffer.append("<!DOCTYPE html><html><head>");
BufferedReader br = null; buffer.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>");
try { buffer.append("<meta name=\"viewport\" ");
File file = new File(path); buffer.append("content=\"width=device-width,minimum-scale=1,maximum-scale=1,user-scalable=no,minimal-ui\"/>");
if (file.exists()) { buffer.append("<meta name=\"format-detection\" content=\"telephone=no\"/>");
is = new FileInputStream(file); buffer.append("<meta http-equiv=\"Access-Control-Allow-Origin\" content=\"*\"/>");
br = new BufferedReader(new InputStreamReader(is)); buffer.append("<title>touch</title>");
String content = br.readLine(); buffer.append("<meta name=\"keywords\" content=\"\"/>");
while (null != content) { buffer.append("<meta name=\"description\" content=\"\"/>");
buffer.append(content); buffer.append(
content = br.readLine(); "<style type=\"text/css\">body{width:100%;height:auto;position:relative;}img{max-width:100%;height:auto;margin:0 auto;}</style>");
buffer.append("</head>");
buffer.append("<body>");
for (int offset = 0; offset < size; offset++) {
buffer.append("<img src=\"" + fileName + "/" + (offset + 1) + ".png\" />");
buffer.append("<br />");
} }
} buffer.append("</body></html>");
} catch (Exception e) { // System.out.println(buffer.toString());
e.printStackTrace(); writeFile(buffer.toString(), path + ".html");
} finally { }
try {
if (null != is) { public static void writeHtmlFile(String path, String fileName) {
is.close(); StringBuffer buffer = new StringBuffer();
buffer.append("<!DOCTYPE html><html><head>");
buffer.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>");
buffer.append(
"<meta name=\"viewport\" content=\"width=device-width,minimum-scale=1,maximum-scale=1,user-scalable=no,minimal-ui\"/>");
buffer.append("<meta name=\"format-detection\" content=\"telephone=no\"/>");
buffer.append("<meta http-equiv=\"Access-Control-Allow-Origin\" content=\"*\"/>");
buffer.append("<title>touch</title>");
buffer.append("<meta name=\"keywords\" content=\"\"/>");
buffer.append("<meta name=\"description\" content=\"\"/>");
buffer.append(
"<style type=\"text/css\">body{width:100%;height:auto;position:relative;}img{max-width:100%;height:auto;margin:0 auto;}</style>");
buffer.append("</head>");
buffer.append("<body>");
buffer.append("<img src=\"" + fileName + "/" + fileName + ".png\" />");
buffer.append("<br />");
buffer.append("</body></html>");
// System.out.println(buffer.toString());
writeFile(buffer.toString(), path + ".html");
}
public static void write2Html(StringBuffer content, String path) {
StringBuffer buffer = new StringBuffer();
buffer.append(
"<html><head><meta http-equiv=\"Access-Control-Allow-Origin\" content=\"*\"></head><body><div align=\"left\">");
buffer.append("<p>" + content + "</p>");
buffer.append("</div></body></html>");
// System.out.println(buffer.toString());
writeFile(buffer.toString(), path + ".html");
}
public static void mkdirFiles(String filePath, String fileType) {
File file = new File(filePath + "/" + fileType);
if (!file.exists()) {
file.mkdirs();
} }
if (null != br) { }
br.close();
/**
* 删除文件空行
*
* @param content
* @param outPutFile
* @throws IOException
*/
public static void rmrBlankLines(String inputFile, String outPutFile) throws IOException {
File htmFile = new File(inputFile);
// 以GB2312读取文件
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(htmFile));
bw = new BufferedWriter(new FileWriter(new File(outPutFile)));
String result = null;
while (null != (result = br.readLine())) {
if (!"".equals(result.trim())) {
bw.write(result + "\r\n");
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != br) {
br.close();
}
if (null != bw) {
bw.close();
}
} catch (Exception e) {
}
} }
} catch (Exception e) {
e.printStackTrace();
}
} }
return buffer; /**
} * @param htmFilePath
* @throws IOException
/** */
* 读取文件,并按照指定的分割符保存文件 public static void parseH2(String htmFilePath) throws IOException {
* @param path 文件的路径 File htmFile = new File(htmFilePath);
* @param split 分割内容的标识 Document doc = Jsoup.parse(htmFile, "UTF-8");
* @return 按照传入的分割符,标识的字符串 doc.getElementsByAttribute("h2");
*/ Elements content = doc.getElementsByTag("h2");
public static StringBuffer readFile(String path, String split) { for (Element meta : content) {
StringBuffer buffer = new StringBuffer(); meta.attr("style", "text-align:center");
InputStream is = null;
BufferedReader br = null;
try {
File file = new File(path);
if (file.exists()) {
is = new FileInputStream(file);
br = new BufferedReader(new InputStreamReader(is));
String content = br.readLine();
while (null != content) {
buffer.append(content).append(split);
content = br.readLine();
} }
} FileUtils.writeStringToFile(htmFile, doc.html(), "UTF-8");
} catch (Exception exception) { }
exception.printStackTrace();
} finally { /**
try { * @param htmFilePath
if (null != is) { * @throws IOException
is.close(); */
public static void parseCharset(String htmFilePath) throws IOException {
File htmFile = new File(htmFilePath);
// 以GB2312读取文件
Document doc = Jsoup.parse(htmFile, "utf-8");
// 获取html节点
Elements content = doc.getElementsByAttributeValueStarting("content", "text/html;");
Elements brs = doc.getElementsByTag("<br>");
for (Element br : brs) {
br.before("<br />");
br.remove();
} }
if (null != br) {
br.close();
for (Element meta : content) {
// 获取content节点,修改charset属性
meta.attr("content", "text/html; charset=utf-8");
break;
} }
} catch (Exception exception2) { // 转换成utf-8编码的文件写入
exception2.printStackTrace(); System.out.println(doc.html());
} FileUtils.writeStringToFile(htmFile, doc.html(), "utf-8");
} }
return buffer; /**
} * @param htmFilePath
* @throws IOException
/** */
* 将传入的字符串写入到指定的路径的文件下 public static void parse(String htmFilePath) throws IOException {
* @param content 将要写入文件的内容 File htmFile = new File(htmFilePath);
* @param path 写入内容的文件路径 // 以GB2312读取文件
*/ Document doc = Jsoup.parse(htmFile, "utf-8");
public static void writeFile(String content, String path) { String xmlns = doc.getElementsByTag("html").attr("xmlns");
OutputStream fos = null; if (null == xmlns || "".equals(xmlns)) {
BufferedWriter bw = null; return;
try {
File file = new File(path);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
fos = new FileOutputStream(file);
bw = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8"));
bw.write(content);
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (bw != null) {
bw.close();
} }
} catch (IOException ioException) { doc.getElementsByTag("html").removeAttr("xmlns");
System.err.println(ioException.getMessage()); Element head = doc.head();
} /*
} * Elements headChildren = head.children(); for(Element children : headChildren) { Elements
} * metas = children.getElementsByTag("meta"); for(Element meta : metas) { meta.remove(); } }
*/
/** head.appendElement("meta").attr("name", "viewport").attr("content",
* 将图片写成html文件 "width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no");
* @param size 图片数量
* @param path 保存html文件全路径 // 获取html节点
* @param fileName 图片路径 Element element = doc.body();
*/ Elements content = head.getElementsByAttributeValueStarting("name", "meta:page-count");
public static void writeHtmlFile(int size, String path, String fileName) { for (Element meta : content) {
StringBuffer buffer = new StringBuffer(); String value = meta.attr("content");
buffer.append("<!DOCTYPE html><html><head>"); try {
buffer.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>"); Integer count = Integer.valueOf(value);
buffer.append("<meta name=\"viewport\" "); Elements ps = element.getElementsByTag("p");
buffer.append("content=\"width=device-width,minimum-scale=1,maximum-scale=1,user-scalable=no,minimal-ui\"/>"); Iterator<Element> iterator = ps.iterator();
buffer.append("<meta name=\"format-detection\" content=\"telephone=no\"/>"); while (iterator.hasNext()) {
buffer.append("<meta http-equiv=\"Access-Control-Allow-Origin\" content=\"*\"/>"); Element p = iterator.next();
buffer.append("<title>touch</title>"); String text = p.text();
buffer.append("<meta name=\"keywords\" content=\"\"/>"); if (text.equals("- " + count + " -")) {
buffer.append("<meta name=\"description\" content=\"\"/>"); for (int offset = count; offset > 0; offset--) {
buffer.append( p.remove();
"<style type=\"text/css\">body{width:100%;height:auto;position:relative;}img{max-width:100%;height:auto;margin:0 auto;}</style>"); p = iterator.next();
text = p.text();
buffer.append("</head>"); }
buffer.append("<body>"); }
if (text.equals("")) {
for (int offset = 0; offset < size; offset++) { p.remove();
buffer.append("<img src=\"" + fileName + "/" + (offset + 1) + ".png\" />"); p = iterator.next();
buffer.append("<br />"); }
} p.attr("align", "center");
buffer.append("</body></html>"); p.attr("style", "font-size:1.5rem;");
// System.out.println(buffer.toString()); break;
writeFile(buffer.toString(), path + ".html"); }
} } catch (Exception e) {
public static void writeHtmlFile(String path, String fileName) { }
StringBuffer buffer = new StringBuffer(); // 获取content节点,修改charset属性
buffer.append("<!DOCTYPE html><html><head>"); // meta.attr("content", "text/html; charset=utf-8");
buffer.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>"); break;
buffer.append( }
"<meta name=\"viewport\" content=\"width=device-width,minimum-scale=1,maximum-scale=1,user-scalable=no,minimal-ui\"/>");
buffer.append("<meta name=\"format-detection\" content=\"telephone=no\"/>");
buffer.append("<meta http-equiv=\"Access-Control-Allow-Origin\" content=\"*\"/>"); // 转换成utf-8编码的文件写入
buffer.append("<title>touch</title>"); FileUtils.writeStringToFile(htmFile, "<!DOCTYPE html>" + doc.html(), "utf-8");
buffer.append("<meta name=\"keywords\" content=\"\"/>");
buffer.append("<meta name=\"description\" content=\"\"/>");
buffer.append(
"<style type=\"text/css\">body{width:100%;height:auto;position:relative;}img{max-width:100%;height:auto;margin:0 auto;}</style>");
buffer.append("</head>");
buffer.append("<body>");
buffer.append("<img src=\"" + fileName + "/" + fileName + ".png\" />");
buffer.append("<br />");
buffer.append("</body></html>");
// System.out.println(buffer.toString());
writeFile(buffer.toString(), path + ".html");
}
public static void write2Html(StringBuffer content, String path) {
StringBuffer buffer = new StringBuffer();
buffer.append(
"<html><head><meta http-equiv=\"Access-Control-Allow-Origin\" content=\"*\"></head><body><div align=\"left\">");
buffer.append("<p>" + content + "</p>");
buffer.append("</div></body></html>");
// System.out.println(buffer.toString());
writeFile(buffer.toString(), path + ".html");
}
public static void mkdirFiles(String filePath, String fileType) {
File file = new File(filePath + "/" + fileType);
if (!file.exists()) {
file.mkdirs();
} }
}
public static void checkHtmlEndTag(String htmFilePath) throws IOException {
/** File htmFile = new File(htmFilePath);
* 删除文件空行 // 以GB2312读取文件
* Document doc = Jsoup.parse(htmFile, "utf-8");
* @param content Elements all = doc.getElementsByTag("html");
* @param outPutFile for (Element element : all) {
* @throws IOException parseElements(all, element);
*/
public static void rmrBlankLines(String inputFile, String outPutFile) throws IOException {
File htmFile = new File(inputFile);
// 以GB2312读取文件
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(htmFile));
bw = new BufferedWriter(new FileWriter(new File(outPutFile)));
String result = null;
while (null != (result = br.readLine())) {
if (!"".equals(result.trim())) {
bw.write(result + "\r\n");
} }
} FileUtils.writeStringToFile(htmFile, doc.html(), "utf-8");
} catch (Exception e) { }
e.printStackTrace();
} finally { public static void parseElements(Elements elements, Element element) {
try { int childNodeSize = elements.size();
if (null != br) { if (0 < childNodeSize) {
br.close(); for (int offset = 0; offset < childNodeSize; offset++) {
parseElements(elements.get(offset).children(), elements.get(offset));
}
} else {
String tagName = element.tagName();
String content = element.toString();
if (tagName.length() + 3 > content.length()) {
element.text("");
} else {
try {
String endTag =
content.substring(content.length() - tagName.length() - 3, content.length());
if (!("</" + tagName + ">").equals(endTag)) {
element.text("");
}
} catch (Exception w) {
}
}
} }
if (null != bw) { }
bw.close();
public static void changeImageType(String htmFilePath) throws IOException {
File htmFile = new File(htmFilePath);
// 以GB2312读取文件
Document doc = Jsoup.parse(htmFile, "utf-8");
Elements elements = doc.getElementsByTag("img");
String imgPath = "";
for (Element element : elements) {
String src = element.attr("src");
String[] sp = src.split("\\.");
String newSrc = htmFile.getParent() + File.separator + sp[0] + ".jpg";
imgPath = src;
element.attr("src", newSrc);
} }
} catch (Exception e) { FileUtils.writeStringToFile(htmFile, doc.html(), "utf-8");
String name = htmFile.getName();
htmFilePath = htmFilePath.substring(0, htmFilePath.length() - name.length()) + imgPath;
}
}
File file = new File(htmFilePath);
} File[] files = file.getParentFile().listFiles();
for (File file2 : files) {
String filePath = file2.getPath();
String[] sp = filePath.split("\\.");
String newSrc = sp[0] + ".jpg";
FileHelper.copyFile(filePath, newSrc, true);
}
/**
* @param htmFilePath
* @throws IOException
*/
public static void parseH2(String htmFilePath) throws IOException {
File htmFile = new File(htmFilePath);
Document doc = Jsoup.parse(htmFile, "UTF-8");
doc.getElementsByAttribute("h2");
Elements content = doc.getElementsByTag("h2");
for (Element meta : content) {
meta.attr("style", "text-align:center");
} }
FileUtils.writeStringToFile(htmFile, doc.html(), "UTF-8");
} public static void nioTransferCopy(File source, File target) {
FileChannel in = null;
/** FileChannel out = null;
* @param htmFilePath FileInputStream inStream = null;
* @throws IOException FileOutputStream outStream = null;
*/ try {
public static void parseCharset(String htmFilePath) throws IOException { inStream = new FileInputStream(source);
File htmFile = new File(htmFilePath); outStream = new FileOutputStream(target);
// 以GB2312读取文件 in = inStream.getChannel();
Document doc = Jsoup.parse(htmFile, "utf-8"); out = outStream.getChannel();
// 获取html节点 in.transferTo(0, in.size(), out);
Elements content = doc.getElementsByAttributeValueStarting("content", "text/html;"); } catch (IOException e) {
Elements brs = doc.getElementsByTag("<br>"); e.printStackTrace();
} finally {
for (Element br : brs) { close(inStream);
br.before("<br />"); close(in);
br.remove(); close(outStream);
close(out);
}
} }
for (Element meta : content) { private static boolean nioBufferCopy(File source, File target) {
// 获取content节点,修改charset属性 FileChannel in = null;
meta.attr("content", "text/html; charset=utf-8"); FileChannel out = null;
break; FileInputStream inStream = null;
FileOutputStream outStream = null;
try {
inStream = new FileInputStream(source);
outStream = new FileOutputStream(target);
in = inStream.getChannel();
out = outStream.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(4096);
while (in.read(buffer) != -1) {
buffer.flip();
out.write(buffer);
buffer.clear();
}
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
close(inStream);
close(in);
close(outStream);
close(out);
}
return true;
} }
// 转换成utf-8编码的文件写入
System.out.println(doc.html());
FileUtils.writeStringToFile(htmFile, doc.html(), "utf-8"); public static void customBufferStreamCopy(File source, File target) {
} InputStream fis = null;
OutputStream fos = null;
/** try {
* @param htmFilePath fis = new FileInputStream(source);
* @throws IOException fos = new FileOutputStream(target);
*/ byte[] buf = new byte[4096];
public static void parse(String htmFilePath) throws IOException { int i;
File htmFile = new File(htmFilePath); while ((i = fis.read(buf)) != -1) {
// 以GB2312读取文件 fos.write(buf, 0, i);
Document doc = Jsoup.parse(htmFile, "utf-8"); }
String xmlns = doc.getElementsByTag("html").attr("xmlns"); } catch (Exception e) {
if (null == xmlns || "".equals(xmlns)) { e.printStackTrace();
return; } finally {
close(fis);
close(fos);
}
} }
doc.getElementsByTag("html").removeAttr("xmlns");
Element head = doc.head();
/* /**
* Elements headChildren = head.children(); for(Element children : headChildren) { Elements * 复制单个文件
* metas = children.getElementsByTag("meta"); for(Element meta : metas) { meta.remove(); } } *
* @param srcFileName 待复制的文件名
* @param destFileName 目标文件名
* @param overlay 如果目标文件存在,是否覆盖
* @return 如果复制成功返回true,否则返回false
*/ */
head.appendElement("meta").attr("name", "viewport").attr("content", public static boolean copyFile(String srcFileName, String destFileName, boolean overlay) {
"width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"); File srcFile = new File(srcFileName);
// 判断源文件是否存在
// 获取html节点 if (!srcFile.exists()) {
Element element = doc.body(); log.info("input file not null");
Elements content = head.getElementsByAttributeValueStarting("name", "meta:page-count"); return false;
for (Element meta : content) { } else if (!srcFile.isFile()) {
String value = meta.attr("content"); log.info("input file is not file");
try { return false;
Integer count = Integer.valueOf(value); }
Elements ps = element.getElementsByTag("p");
Iterator<Element> iterator = ps.iterator(); // 判断目标文件是否存在
while (iterator.hasNext()) { File destFile = new File(destFileName);
Element p = iterator.next(); if (destFile.exists()) {
String text = p.text(); // 如果目标文件存在并允许覆盖
if (text.equals("- " + count + " -")) { if (overlay) {
for (int offset = count; offset > 0; offset--) { // 删除已经存在的目标文件,无论目标文件是目录还是单个文件
p.remove(); new File(destFileName).delete();
p = iterator.next(); }
text = p.text(); } else {
// 如果目标文件所在目录不存在,则创建目录
if (!destFile.getParentFile().exists()) {
// 目标文件所在目录不存在
if (!destFile.getParentFile().mkdirs()) {
// 复制文件失败:创建目标文件所在目录失败
return false;
}
} }
}
if (text.equals("")) {
p.remove();
p = iterator.next();
}
p.attr("align", "center");
p.attr("style", "font-size:1.5rem;");
break;
} }
} catch (Exception e) {
} boolean result = nioBufferCopy(srcFile, destFile);
// 获取content节点,修改charset属性
// meta.attr("content", "text/html; charset=utf-8"); return result;
break;
} }
/**
* 复制整个目录的内容
*
* @param srcDirName 待复制目录的目录名
* @param destDirName 目标目录名
* @param overlay 如果目标目录存在,是否覆盖
* @return 如果复制成功返回true,否则返回false
*/
public static boolean copyDirectory(String srcDirName, String destDirName, boolean overlay) {
// 判断源目录是否存在
File srcDir = new File(srcDirName);
if (!srcDir.exists()) {
log.info("srcDir not found");
return false;
} else if (!srcDir.isDirectory()) {
log.info("srcDir not Directory");
return false;
}
// 转换成utf-8编码的文件写入 // 如果目标目录名不是以文件分隔符结尾,则加上文件分隔符
FileUtils.writeStringToFile(htmFile, "<!DOCTYPE html>" + doc.html(), "utf-8"); if (!destDirName.endsWith(File.separator)) {
} destDirName = destDirName + File.separator;
}
File destDir = new File(destDirName);
// 如果目标文件夹存在
if (destDir.exists()) {
// 如果允许覆盖则删除已存在的目标目录
if (overlay) {
new File(destDirName).delete();
} else {
log.info("");
return false;
}
} else {
// 创建目的目录
System.out.println("目的目录不存在,准备创建。。。");
if (!destDir.mkdirs()) {
System.out.println("复制目录失败:创建目的目录失败!");
return false;
}
}
public static void checkHtmlEndTag(String htmFilePath) throws IOException { boolean flag = true;
File htmFile = new File(htmFilePath); File[] files = srcDir.listFiles();
// 以GB2312读取文件 for (int i = 0; i < files.length; i++) {
Document doc = Jsoup.parse(htmFile, "utf-8"); // 复制文件
Elements all = doc.getElementsByTag("html"); if (files[i].isFile()) {
for (Element element : all) { flag = FileHelper.copyFile(files[i].getAbsolutePath(), destDirName + files[i].getName(),
parseElements(all, element); overlay);
if (!flag) {
break;
}
} else if (files[i].isDirectory()) {
flag = FileHelper.copyDirectory(files[i].getAbsolutePath(),
destDirName + files[i].getName(), overlay);
if (!flag) {
break;
}
}
}
if (!flag) {
log.info("copy Directory fail");
return false;
} else {
return true;
}
} }
FileUtils.writeStringToFile(htmFile, doc.html(), "utf-8");
} /**
* 关闭资源
public static void parseElements(Elements elements, Element element) { *
int childNodeSize = elements.size(); * @param object 需要关闭的对象
if (0 < childNodeSize) { */
for (int offset = 0; offset < childNodeSize; offset++) { public static void close(Object object) {
parseElements(elements.get(offset).children(), elements.get(offset)); if (null == object) {
} return;
} else { }
String tagName = element.tagName();
String content = element.toString();
if (tagName.length() + 3 > content.length()) {
element.text("");
} else {
try { try {
String endTag = if (object instanceof InputStream) {
content.substring(content.length() - tagName.length() - 3, content.length()); ((InputStream) object).close();
if (!("</" + tagName + ">").equals(endTag)) { } else if (object instanceof OutputStream) {
element.text(""); ((OutputStream) object).close();
} } else if (object instanceof Channel) {
} catch (Exception w) {} ((Channel) object).close();
} }
} } catch (Exception exce) {
} System.err.println(exce.getMessage());
}
public static void changeImageType(String htmFilePath) throws IOException {
File htmFile = new File(htmFilePath);
// 以GB2312读取文件
Document doc = Jsoup.parse(htmFile, "utf-8");
Elements elements = doc.getElementsByTag("img");
String imgPath = "";
for (Element element : elements) {
String src = element.attr("src");
String[] sp = src.split("\\.");
String newSrc = htmFile.getParent() + File.separator + sp[0] + ".jpg";
imgPath = src;
element.attr("src", newSrc);
} }
FileUtils.writeStringToFile(htmFile, doc.html(), "utf-8");
String name = htmFile.getName();
htmFilePath = htmFilePath.substring(0, htmFilePath.length() - name.length()) + imgPath; /**
* 合并excel表格的sheet
*
* @param htmFilePath html文件路径
* @throws IOException 打开文件异常
*/
public static void mergeTable(String htmFilePath) throws IOException {
File htmFile = new File(htmFilePath);
// 以GB2312读取文件
Document doc = Jsoup.parse(htmFile, "utf-8");
Integer tableMaxSize = getMaxTableSize(doc);
Elements allTable = doc.getElementsByTag("tbody");
Element max = null;
for (Element table : allTable) {
Elements elements = table.children();
if (0 >= elements.size()) {
table.parent().remove();
continue;
}
int size = elements.first().children().size();
if (size >= tableMaxSize) {
max = table;
continue;
}
for (Element tr : elements) {
Elements td = tr.children();
for (int offset = tableMaxSize; offset > td.size(); offset--) {
Element tdd = doc.createElement("td");
tr.appendChild(tdd);
}
max.appendChild(tr);
}
table.parent().remove();
}
FileUtils.writeStringToFile(htmFile, doc.html(), "utf-8");
}
private static Integer getMaxTableSize(Document doc) {
Elements allTable = doc.getElementsByTag("tbody");
TreeSet<Integer> tableSize = new TreeSet<Integer>();
for (Element table : allTable) {
Elements elements = table.children();
int size = 0;
try {
size = elements.first().children().size();
} catch (Exception e) {
size = -1;
}
if (tableSize.contains(size)) {
size--;
}
tableSize.add(size);
}
return tableSize.last();
}
/**
* 获取文件css样式
*
* @param src 文件
* @return 文件css样式
* @throws IOException 打开文件异常
*/
public static final StringBuffer getHtmlCss(String src) throws IOException {
File htmFile = new File(src);
// 以GB2312读取文件
Document doc = Jsoup.parse(htmFile, "utf-8");
Elements styles = doc.getElementsByTag("style");
StringBuffer csStringBuffer = new StringBuffer();
for (Element style : styles) {
csStringBuffer.append(style.toString().replace("<style>", "").replace("</style>", ""));
}
Elements links = doc.getElementsByTag("link");
for (Element style : links) {
String href = style.attr("href");
String realPath = src + File.separator + href;
StringBuffer link = FileHelper.readFile(realPath);
csStringBuffer.append(link);
}
File file = new File(htmFilePath); return csStringBuffer;
File[] files = file.getParentFile().listFiles();
for (File file2 : files) {
String filePath = file2.getPath();
String[] sp = filePath.split("\\.");
String newSrc = sp[0] + ".jpg";
FileHelper.copyFile(filePath, newSrc, true);
} }
}
public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response) {
public static void nioTransferCopy(File source, File target) { ExportParams exportParams = new ExportParams(title, sheetName);
FileChannel in = null; exportParams.setCreateHeadRows(isCreateHeader);
FileChannel out = null; defaultExport(list, pojoClass, fileName, response, exportParams);
FileInputStream inStream = null;
FileOutputStream outStream = null;
try {
inStream = new FileInputStream(source);
outStream = new FileOutputStream(target);
in = inStream.getChannel();
out = outStream.getChannel();
in.transferTo(0, in.size(), out);
} catch (IOException e) {
e.printStackTrace();
} finally {
close(inStream);
close(in);
close(outStream);
close(out);
} }
}
public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response) {
defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
private static boolean nioBufferCopy(File source, File target) {
FileChannel in = null;
FileChannel out = null;
FileInputStream inStream = null;
FileOutputStream outStream = null;
try {
inStream = new FileInputStream(source);
outStream = new FileOutputStream(target);
in = inStream.getChannel();
out = outStream.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(4096);
while (in.read(buffer) != -1) {
buffer.flip();
out.write(buffer);
buffer.clear();
}
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
close(inStream);
close(in);
close(outStream);
close(out);
} }
return true;
} public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
defaultExport(list, fileName, response);
public static void customBufferStreamCopy(File source, File target) {
InputStream fis = null;
OutputStream fos = null;
try {
fis = new FileInputStream(source);
fos = new FileOutputStream(target);
byte[] buf = new byte[4096];
int i;
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close(fis);
close(fos);
} }
}
private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) {
Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
if (workbook != null) ;
/** downLoadExcel(fileName, response, workbook);
* 复制单个文件
*
* @param srcFileName 待复制的文件名
* @param destFileName 目标文件名
* @param overlay 如果目标文件存在,是否覆盖
* @return 如果复制成功返回true,否则返回false
*/
public static boolean copyFile(String srcFileName, String destFileName, boolean overlay) {
File srcFile = new File(srcFileName);
// 判断源文件是否存在
if (!srcFile.exists()) {
log.info("input file not null");
return false;
} else if (!srcFile.isFile()) {
log.info("input file is not file");
return false;
} }
// 判断目标文件是否存在 private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
File destFile = new File(destFileName); try {
if (destFile.exists()) { String name = new String(fileName.getBytes("UTF-8"), "ISO8859_1");
// 如果目标文件存在并允许覆盖 response.setHeader("content-Type", "application/vnd.ms-excel");
if (overlay) { response.setHeader("Content-Disposition",
// 删除已经存在的目标文件,无论目标文件是目录还是单个文件 "attachment;filename=" + name);
new File(destFileName).delete();
} workbook.write(response.getOutputStream());
} else { } catch (IOException e) {
// 如果目标文件所在目录不存在,则创建目录 throw new YeeException(e.getMessage());
if (!destFile.getParentFile().exists()) {
// 目标文件所在目录不存在
if (!destFile.getParentFile().mkdirs()) {
// 复制文件失败:创建目标文件所在目录失败
return false;
} }
}
} }
boolean result = nioBufferCopy(srcFile, destFile); private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
return result; if (workbook != null) ;
} downLoadExcel(fileName, response, workbook);
/**
* 复制整个目录的内容
*
* @param srcDirName 待复制目录的目录名
* @param destDirName 目标目录名
* @param overlay 如果目标目录存在,是否覆盖
* @return 如果复制成功返回true,否则返回false
*/
public static boolean copyDirectory(String srcDirName, String destDirName, boolean overlay) {
// 判断源目录是否存在
File srcDir = new File(srcDirName);
if (!srcDir.exists()) {
log.info("srcDir not found");
return false;
} else if (!srcDir.isDirectory()) {
log.info("srcDir not Directory");
return false;
} }
// 如果目标目录名不是以文件分隔符结尾,则加上文件分隔符 public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
if (!destDirName.endsWith(File.separator)) { if (ObjectUtils.isEmpty(filePath)) {
destDirName = destDirName + File.separator; return null;
} }
File destDir = new File(destDirName); ImportParams params = new ImportParams();
// 如果目标文件夹存在 params.setTitleRows(titleRows);
if (destDir.exists()) { params.setHeadRows(headerRows);
// 如果允许覆盖则删除已存在的目标目录 List<T> list = null;
if (overlay) { try {
new File(destDirName).delete(); list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
} else { } catch (NoSuchElementException e) {
log.info(""); throw new YeeException("模板不能为空");
return false; } catch (Exception e) {
} e.printStackTrace();
} else { throw new YeeException(e.getMessage());
// 创建目的目录 }
System.out.println("目的目录不存在,准备创建。。。"); return list;
if (!destDir.mkdirs()) {
System.out.println("复制目录失败:创建目的目录失败!");
return false;
}
} }
boolean flag = true; public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
File[] files = srcDir.listFiles(); if (file == null) {
for (int i = 0; i < files.length; i++) { return null;
// 复制文件
if (files[i].isFile()) {
flag = FileHelper.copyFile(files[i].getAbsolutePath(), destDirName + files[i].getName(),
overlay);
if (!flag) {
break;
} }
} else if (files[i].isDirectory()) { ImportParams params = new ImportParams();
flag = FileHelper.copyDirectory(files[i].getAbsolutePath(), params.setTitleRows(titleRows);
destDirName + files[i].getName(), overlay); params.setHeadRows(headerRows);
if (!flag) { List<T> list = null;
break; try {
list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
} catch (NoSuchElementException e) {
throw new YeeException("excel文件不能为空");
} catch (Exception e) {
e.printStackTrace();
throw new YeeException(e.getMessage());
} }
} return list;
} }
if (!flag) {
log.info("copy Directory fail"); public static void exportZip(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
return false; try {
} else { response.setContentType("multipart/form-data");
return true; response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new YeeException("下载文件名编码时出现错误.");
}
OutputStream outputStream = null;
ZipOutputStream zos = null;
try {
outputStream = response.getOutputStream();
zos = new ZipOutputStream(outputStream);
downloadZip(fileName.replace(".zip", ""), zos, list);
} catch (IOException e) {
} finally {
if (zos != null) {
try {
zos.close();
} catch (Exception e2) {
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (Exception e2) {
}
}
}
} }
}
/** public static void exportQRCode(List<PointVo> pointList, String fileNmae, HttpServletResponse response) {
* 关闭资源 try {
* @param object 需要关闭的对象 response.setContentType("multipart/form-data");
*/ response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileNmae, "UTF-8"));
public static void close(Object object) { } catch (UnsupportedEncodingException e) {
if (null == object) { throw new YeeException("下载文件名编码时出现错误.");
return; }
OutputStream outputStream = null;
ZipOutputStream zos = null;
try {
outputStream = response.getOutputStream();
zos = new ZipOutputStream(outputStream);
downloadQRCodeZip(fileNmae.replace(".zip", ""), zos, pointList);
} catch (IOException e) {
} finally {
if (zos != null) {
try {
zos.close();
} catch (Exception e2) {
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (Exception e2) {
}
}
}
} }
try {
if (object instanceof InputStream) {
((InputStream) object).close(); public static void downloadZip(String baseDir, ZipOutputStream zos, List<Map<String, Object>> list) {
} else if (object instanceof OutputStream) { for (Map<String, Object> map : list) {
((OutputStream) object).close(); String checkId = map.get("id").toString();
} else if (object instanceof Channel) { //文件名称(带后缀)
((Channel) object).close(); String fileName = map.get("photoData").toString();
} InputStream is = null;
} catch (Exception exce) { BufferedInputStream in = null;
System.err.println(exce.getMessage()); byte[] buffer = new byte[1024];
int len;
//创建zip实体(一个文件对应一个ZipEntry)
ZipEntry entry = new ZipEntry(baseDir + fileName.substring(fileName.lastIndexOf(File.separator), fileName.length()));
try {
//获取需要下载的文件流
File file = new File(fileName);
is = new FileInputStream(file);
in = new BufferedInputStream(is);
zos.putNextEntry(entry);
//文件流循环写入ZipOutputStream
while ((len = in.read(buffer)) != -1) {
zos.write(buffer, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (entry != null) {
try {
zos.closeEntry();
} catch (Exception e2) {
}
}
if (in != null) {
try {
in.close();
} catch (Exception e2) {
}
}
if (is != null) {
try {
is.close();
} catch (Exception e) {
}
}
}
}
} }
}
public static void downloadQRCodeZip(String baseDir, ZipOutputStream zos, List<PointVo> pointList) {
Map<String, Object> map1 = new HashMap<String, Object>();
/** for (PointVo map : pointList) {
* 合并excel表格的sheet
* map1.put(map.getPointNo(), map);
* @param htmFilePath html文件路径
* @throws IOException 打开文件异常
*/
public static void mergeTable(String htmFilePath) throws IOException {
File htmFile = new File(htmFilePath);
// 以GB2312读取文件
Document doc = Jsoup.parse(htmFile, "utf-8");
Integer tableMaxSize = getMaxTableSize(doc);
Elements allTable = doc.getElementsByTag("tbody");
Element max = null;
for (Element table : allTable) {
Elements elements = table.children();
if (0 >= elements.size()) {
table.parent().remove();
continue;
}
int size = elements.first().children().size();
if (size >= tableMaxSize) {
max = table;
continue;
}
for (Element tr : elements) {
Elements td = tr.children();
for (int offset = tableMaxSize; offset > td.size(); offset--) {
Element tdd = doc.createElement("td");
tr.appendChild(tdd);
} }
max.appendChild(tr); pointList.clear();
}
table.parent().remove(); for (String key : map1.keySet()) {
} pointList.add((PointVo) map1.get(key));
FileUtils.writeStringToFile(htmFile, doc.html(), "utf-8"); }
}
private static Integer getMaxTableSize(Document doc) {
Elements allTable = doc.getElementsByTag("tbody");
TreeSet<Integer> tableSize = new TreeSet<Integer>();
for (Element table : allTable) {
Elements elements = table.children();
int size = 0;
try {
size = elements.first().children().size();
} catch (Exception e) {
size = -1;
}
if (tableSize.contains(size)) {
size--;
}
tableSize.add(size);
}
return tableSize.last();
}
/**
* 获取文件css样式
* @param src 文件
* @return 文件css样式
* @throws IOException 打开文件异常
*/
public static final StringBuffer getHtmlCss(String src) throws IOException {
File htmFile = new File(src);
// 以GB2312读取文件
Document doc = Jsoup.parse(htmFile, "utf-8");
Elements styles = doc.getElementsByTag("style");
StringBuffer csStringBuffer = new StringBuffer();
for (Element style : styles) {
csStringBuffer.append(style.toString().replace("<style>", "").replace("</style>", ""));
}
Elements links = doc.getElementsByTag("link");
for (Element style : links) {
String href = style.attr("href");
String realPath = src + File.separator + href;
StringBuffer link = FileHelper.readFile(realPath);
csStringBuffer.append(link);
}
return csStringBuffer;
for (PointVo map : pointList) {
} String pointName = map.getName();
//文件名称(带后缀)
String pointNo = map.getPointNo();
public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,String fileName,boolean isCreateHeader, HttpServletResponse response){ InputStream is = null;
ExportParams exportParams = new ExportParams(title, sheetName); BufferedInputStream in = null;
exportParams.setCreateHeadRows(isCreateHeader); //创建zip实体(一个文件对应一个ZipEntry)
defaultExport(list, pojoClass, fileName, response, exportParams); ZipEntry entry = new ZipEntry(baseDir + "/" + pointName + ".png");
try {
} BitMatrix bitMatrix = new MultiFormatWriter().encode(/*"AMOS#PATROL#01#" + */pointNo, BarcodeFormat.QR_CODE, 300, 300);
public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,String fileName, HttpServletResponse response){
defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
}
public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response){
defaultExport(list, fileName, response);
}
private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) {
Workbook workbook = ExcelExportUtil.exportExcel(exportParams,pojoClass,list);
if (workbook != null);
downLoadExcel(fileName, response, workbook);
}
private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
try {
String name = new String(fileName.getBytes("UTF-8"), "ISO8859_1");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition",
"attachment;filename=" + name);
workbook.write(response.getOutputStream());
} catch (IOException e) {
throw new YeeException(e.getMessage());
}
}
private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
if (workbook != null);
downLoadExcel(fileName, response, workbook);
}
public static <T> List<T> importExcel(String filePath,Integer titleRows,Integer headerRows, Class<T> pojoClass){
if (ObjectUtils.isEmpty(filePath)){
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
List<T> list = null;
try {
list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
}catch (NoSuchElementException e){
throw new YeeException("模板不能为空");
} catch (Exception e) {
e.printStackTrace();
throw new YeeException(e.getMessage());
}
return list;
}
public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass){
if (file == null){
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
List<T> list = null;
try {
list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
}catch (NoSuchElementException e){
throw new YeeException("excel文件不能为空");
} catch (Exception e) {
e.printStackTrace();
throw new YeeException(e.getMessage());
}
return list;
}
public static void exportZip(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
try {
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new YeeException("下载文件名编码时出现错误.");
}
OutputStream outputStream = null;
ZipOutputStream zos = null;
try {
outputStream = response.getOutputStream();
zos = new ZipOutputStream(outputStream);
downloadZip(fileName.replace(".zip", ""), zos, list);
} catch (IOException e) {
} finally {
if(zos != null) {
try {
zos.close();
} catch (Exception e2) {
}
}
if(outputStream != null) {
try {
outputStream.close();
} catch (Exception e2) {
}
}
}
}
public static void exportQRCode(List<PointVo> pointList, String fileNmae, HttpServletResponse response) {
try {
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileNmae, "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new YeeException("下载文件名编码时出现错误.");
}
OutputStream outputStream = null;
ZipOutputStream zos = null;
try {
outputStream = response.getOutputStream();
zos = new ZipOutputStream(outputStream);
downloadQRCodeZip(fileNmae.replace(".zip", ""), zos, pointList);
} catch (IOException e) {
} finally {
if(zos != null) {
try {
zos.close();
} catch (Exception e2) {
}
}
if(outputStream != null) {
try {
outputStream.close();
} catch (Exception e2) {
}
}
}
}
public static void downloadZip(String baseDir, ZipOutputStream zos, List<Map<String, Object>> list) {
for (Map<String, Object> map : list) {
String checkId = map.get("id").toString();
//文件名称(带后缀)
String fileName = map.get("photoData").toString();
InputStream is = null;
BufferedInputStream in = null;
byte[] buffer = new byte[1024];
int len;
//创建zip实体(一个文件对应一个ZipEntry)
ZipEntry entry = new ZipEntry(baseDir + fileName.substring(fileName.lastIndexOf(File.separator), fileName.length()));
try {
//获取需要下载的文件流
File file = new File(fileName);
is = new FileInputStream(file);
in = new BufferedInputStream(is);
zos.putNextEntry(entry);
//文件流循环写入ZipOutputStream
while ((len = in.read(buffer)) != -1 ) {
zos.write(buffer, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if(entry != null) {
try {
zos.closeEntry();
} catch (Exception e2) {
}
}
if(in != null) {
try {
in.close();
} catch (Exception e2) {
}
}
if(is != null) {
try {
is.close();
}catch (Exception e) {
}
}
}
}
}
public static void downloadQRCodeZip(String baseDir, ZipOutputStream zos, List<PointVo> pointList) {
Map<String, Object> map1= new HashMap<String, Object>();
for (PointVo map : pointList) {
map1.put(map.getPointNo(), map);
}
pointList.clear();
for(String key:map1.keySet()){
pointList.add((PointVo)map1.get(key));
}
for (PointVo map : pointList) {
String pointName = map.getName();
//文件名称(带后缀)
String pointNo = map.getPointNo();
InputStream is = null;
BufferedInputStream in = null;
//创建zip实体(一个文件对应一个ZipEntry)
ZipEntry entry = new ZipEntry(baseDir + "/" + pointName + ".png");
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(/*"AMOS#PATROL#01#" + */pointNo, BarcodeFormat.QR_CODE, 300, 300);
BufferedImage buffImg = MatrixToImageWriter.toBufferedImage(bitMatrix); BufferedImage buffImg = MatrixToImageWriter.toBufferedImage(bitMatrix);
zos.putNextEntry(entry); zos.putNextEntry(entry);
ImageIO.write(buffImg, "png", zos); ImageIO.write(buffImg, "png", zos);
zos.flush(); zos.flush();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
}finally { } finally {
if(entry != null) { if (entry != null) {
try { try {
zos.closeEntry(); zos.closeEntry();
} catch (Exception e2) { } catch (Exception e2) {
} }
} }
if(in != null) { if (in != null) {
try { try {
in.close(); in.close();
} catch (Exception e2) { } catch (Exception e2) {
} }
} }
if(is != null) { if (is != null) {
try { try {
is.close(); is.close();
}catch (Exception e) { } catch (Exception e) {
} }
} }
} }
} }
} }
/** /**
* @Title: createExcelTemplate
* @Description: 生成Excel导入模板
* @param @param filePath Excel文件路径 * @param @param filePath Excel文件路径
* @param @param handers Excel列标题(数组) * @param @param handers Excel列标题(数组)
* @param @param downData 下拉框数据(数组) * @param @param downData 下拉框数据(数组)
* @param @param downRows 下拉列的序号(数组,序号从0开始) * @param @param downRows 下拉列的序号(数组,序号从0开始)
* @return void * @return void
* @throws * @throws
* @Title: createExcelTemplate
* @Description: 生成Excel导入模板
*/ */
public static void createExcelTemplate(String fileName, String[] handers, public static void createExcelTemplate(String fileName, String[] handers,
List<String[]> downData, String[] downRows, HttpServletResponse response){ List<String[]> downData, String[] downRows, HttpServletResponse response) {
HSSFWorkbook wb = new HSSFWorkbook();//创建工作薄 HSSFWorkbook wb = new HSSFWorkbook();//创建工作薄
//表头样式 //表头样式
HSSFCellStyle style = wb.createCellStyle(); HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式 style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
//字体样式 //字体样式
HSSFFont fontStyle = wb.createFont(); HSSFFont fontStyle = wb.createFont();
fontStyle.setFontName("微软雅黑"); fontStyle.setFontName("微软雅黑");
fontStyle.setFontHeightInPoints((short)12); fontStyle.setFontHeightInPoints((short) 12);
fontStyle.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); fontStyle.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
style.setFont(fontStyle); style.setFont(fontStyle);
//新建sheet //新建sheet
HSSFSheet sheet1 = wb.createSheet("Sheet1"); HSSFSheet sheet1 = wb.createSheet("Sheet1");
HSSFSheet sheet2 = wb.createSheet("Sheet2"); HSSFSheet sheet2 = wb.createSheet("Sheet2");
HSSFSheet sheet3 = wb.createSheet("Sheet3"); HSSFSheet sheet3 = wb.createSheet("Sheet3");
//生成sheet1内容 //生成sheet1内容
HSSFRow rowFirst = sheet1.createRow(0);//第一个sheet的第一行为标题 HSSFRow rowFirst = sheet1.createRow(0);//第一个sheet的第一行为标题
//写标题 //写标题
for(int i=0;i<handers.length;i++){ for (int i = 0; i < handers.length; i++) {
HSSFCell cell = rowFirst.createCell(i); //获取第一行的每个单元格 HSSFCell cell = rowFirst.createCell(i); //获取第一行的每个单元格
sheet1.setColumnWidth(i, 4000); //设置每列的列宽 sheet1.setColumnWidth(i, 4000); //设置每列的列宽
cell.setCellStyle(style); //加样式 cell.setCellStyle(style); //加样式
cell.setCellValue(handers[i]); //往单元格里写数据 cell.setCellValue(handers[i]); //往单元格里写数据
} }
//设置下拉框数据 //设置下拉框数据
String[] arr = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"}; String[] arr = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
int index = 0; int index = 0;
HSSFRow row = null; HSSFRow row = null;
for(int r=0;r<downRows.length;r++){ for (int r = 0; r < downRows.length; r++) {
String[] dlData = downData.get(r);//获取下拉对象 String[] dlData = downData.get(r);//获取下拉对象
int rownum = Integer.parseInt(downRows[r]); int rownum = Integer.parseInt(downRows[r]);
if(dlData.length<5){ //255以内的下拉 if (dlData.length < 5) { //255以内的下拉
//255以内的下拉,参数分别是:作用的sheet、下拉内容数组、起始行、终止行、起始列、终止列 //255以内的下拉,参数分别是:作用的sheet、下拉内容数组、起始行、终止行、起始列、终止列
sheet1.addValidationData(setDataValidation(sheet1, dlData, 1, 30000, rownum ,rownum)); //超过255个报错 sheet1.addValidationData(setDataValidation(sheet1, dlData, 1, 30000, rownum, rownum)); //超过255个报错
} else { //255以上的下拉,即下拉列表元素很多的情况 } else { //255以上的下拉,即下拉列表元素很多的情况
//1、设置有效性 //1、设置有效性
//String strFormula = "Sheet2!$A$1:$A$5000" ; //Sheet2第A1到A5000作为下拉列表来源数据 //String strFormula = "Sheet2!$A$1:$A$5000" ; //Sheet2第A1到A5000作为下拉列表来源数据
String strFormula = "Sheet2!$"+arr[index]+"$1:$"+arr[index]+"$5000"; //Sheet2第A1到A5000作为下拉列表来源数据 String strFormula = "Sheet2!$" + arr[index] + "$1:$" + arr[index] + "$5000"; //Sheet2第A1到A5000作为下拉列表来源数据
sheet2.setColumnWidth(r, 4000); //设置每列的列宽 sheet2.setColumnWidth(r, 4000); //设置每列的列宽
//设置数据有效性加载在哪个单元格上,参数分别是:从sheet2获取A1到A5000作为一个下拉的数据、起始行、终止行、起始列、终止列 //设置数据有效性加载在哪个单元格上,参数分别是:从sheet2获取A1到A5000作为一个下拉的数据、起始行、终止行、起始列、终止列
sheet1.addValidationData(SetDataValidation(strFormula, 1, 30000, rownum, rownum)); //下拉列表元素很多的情况 sheet1.addValidationData(SetDataValidation(strFormula, 1, 30000, rownum, rownum)); //下拉列表元素很多的情况
//2、生成sheet2内容 //2、生成sheet2内容
for(int j=0;j<dlData.length;j++){ for (int j = 0; j < dlData.length; j++) {
if(index==0){ //第1个下拉选项,直接创建行、列 if (index == 0) { //第1个下拉选项,直接创建行、列
row = sheet2.createRow(j); //创建数据行 row = sheet2.createRow(j); //创建数据行
sheet2.setColumnWidth(j, 4000); //设置每列的列宽 sheet2.setColumnWidth(j, 4000); //设置每列的列宽
row.createCell(0).setCellValue(dlData[j]); //设置对应单元格的值 row.createCell(0).setCellValue(dlData[j]); //设置对应单元格的值
} else { //非第1个下拉选项 } else { //非第1个下拉选项
int rowCount = sheet2.getLastRowNum(); int rowCount = sheet2.getLastRowNum();
//System.out.println("========== LastRowNum =========" + rowCount); //System.out.println("========== LastRowNum =========" + rowCount);
if(j<=rowCount){ //前面创建过的行,直接获取行,创建列 if (j <= rowCount) { //前面创建过的行,直接获取行,创建列
//获取行,创建列 //获取行,创建列
sheet2.getRow(j).createCell(index).setCellValue(dlData[j]); //设置对应单元格的值 sheet2.getRow(j).createCell(index).setCellValue(dlData[j]); //设置对应单元格的值
} else { //未创建过的行,直接创建行、创建列 } else { //未创建过的行,直接创建行、创建列
sheet2.setColumnWidth(j, 4000); //设置每列的列宽 sheet2.setColumnWidth(j, 4000); //设置每列的列宽
//创建行、创建列 //创建行、创建列
...@@ -1215,53 +1206,52 @@ private static void defaultExport(List<Map<String, Object>> list, String fileNam ...@@ -1215,53 +1206,52 @@ private static void defaultExport(List<Map<String, Object>> list, String fileNam
} }
} }
} }
index++; index++;
} }
} }
downLoadExcel(fileName, response, wb); downLoadExcel(fileName, response, wb);
} }
/** /**
* * @param @param strFormula
* @Title: SetDataValidation * @param @param firstRow 起始行
* @Description: 下拉列表元素很多的情况 (255以上的下拉) * @param @param endRow 终止行
* @param @param strFormula * @param @param firstCol 起始列
* @param @param firstRow 起始行 * @param @param endCol 终止列
* @param @param endRow 终止行
* @param @param firstCol 起始列
* @param @param endCol 终止列
* @param @return * @param @return
* @return HSSFDataValidation * @return HSSFDataValidation
* @throws * @throws
* @Title: SetDataValidation
* @Description: 下拉列表元素很多的情况 (255以上的下拉)
*/ */
private static HSSFDataValidation SetDataValidation(String strFormula, private static HSSFDataValidation SetDataValidation(String strFormula,
int firstRow, int endRow, int firstCol, int endCol) { int firstRow, int endRow, int firstCol, int endCol) {
// 设置数据有效性加载在哪个单元格上。四个参数分别是:起始行、终止行、起始列、终止列 // 设置数据有效性加载在哪个单元格上。四个参数分别是:起始行、终止行、起始列、终止列
CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol); CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
DVConstraint constraint = DVConstraint.createFormulaListConstraint(strFormula); DVConstraint constraint = DVConstraint.createFormulaListConstraint(strFormula);
HSSFDataValidation dataValidation = new HSSFDataValidation(regions,constraint); HSSFDataValidation dataValidation = new HSSFDataValidation(regions, constraint);
dataValidation.createErrorBox("Error", "Error"); dataValidation.createErrorBox("Error", "Error");
dataValidation.createPromptBox("", null); dataValidation.createPromptBox("", null);
return dataValidation; return dataValidation;
} }
/** /**
* * @param @param sheet
* @Title: setDataValidation * @param @param textList
* @Description: 下拉列表元素不多的情况(255以内的下拉) * @param @param firstRow
* @param @param sheet * @param @param endRow
* @param @param textList * @param @param firstCol
* @param @param firstRow * @param @param endCol
* @param @param endRow
* @param @param firstCol
* @param @param endCol
* @param @return * @param @return
* @return DataValidation * @return DataValidation
* @throws * @throws
* @Title: setDataValidation
* @Description: 下拉列表元素不多的情况(255以内的下拉)
*/ */
private static DataValidation setDataValidation(Sheet sheet, String[] textList, int firstRow, int endRow, int firstCol, int endCol) { private static DataValidation setDataValidation(Sheet sheet, String[] textList, int firstRow, int endRow, int firstCol, int endCol) {
...@@ -1270,79 +1260,78 @@ private static void defaultExport(List<Map<String, Object>> list, String fileNam ...@@ -1270,79 +1260,78 @@ private static void defaultExport(List<Map<String, Object>> list, String fileNam
DataValidationConstraint constraint = helper.createExplicitListConstraint(textList); DataValidationConstraint constraint = helper.createExplicitListConstraint(textList);
//DVConstraint constraint = new DVConstraint(); //DVConstraint constraint = new DVConstraint();
constraint.setExplicitListValues(textList); constraint.setExplicitListValues(textList);
//设置数据有效性加载在哪个单元格上。四个参数分别是:起始行、终止行、起始列、终止列 //设置数据有效性加载在哪个单元格上。四个参数分别是:起始行、终止行、起始列、终止列
CellRangeAddressList regions = new CellRangeAddressList((short) firstRow, (short) endRow, (short) firstCol, (short) endCol); CellRangeAddressList regions = new CellRangeAddressList((short) firstRow, (short) endRow, (short) firstCol, (short) endCol);
//数据有效性对象 //数据有效性对象
DataValidation data_validation = helper.createValidation(constraint, regions); DataValidation data_validation = helper.createValidation(constraint, regions);
//DataValidation data_validation = new DataValidation(regions, constraint); //DataValidation data_validation = new DataValidation(regions, constraint);
return data_validation; return data_validation;
} }
/** /**
* @Title: getExcel
* @Description: 下载指定路径的Excel文件
* @param @param url 文件路径 * @param @param url 文件路径
* @param @param fileName 文件名 * @param @param fileName 文件名
* @param @param response * @param @param response
* @return void * @return void
* @throws * @throws
* @Title: getExcel
* @Description: 下载指定路径的Excel文件
*/ */
public static void getExcel(String url, String fileName, HttpServletResponse response,HttpServletRequest request){ public static void getExcel(String url, String fileName, HttpServletResponse response, HttpServletRequest request) {
try { try {
//1.设置文件ContentType类型,这样设置,会自动判断下载文件类型 //1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
response.setContentType("multipart/form-data"); response.setContentType("multipart/form-data");
//2.设置文件头:最后一个参数是设置下载文件名 //2.设置文件头:最后一个参数是设置下载文件名
response.setHeader("Content-disposition", "attachment; filename=\"" response.setHeader("Content-disposition", "attachment; filename=\""
+ encodeChineseDownloadFileName(request, fileName+".xls") +"\""); + encodeChineseDownloadFileName(request, fileName + ".xls") + "\"");
// response.setHeader("Content-Disposition", "attachment;filename=" // response.setHeader("Content-Disposition", "attachment;filename="
// + new String(fileName.getBytes("UTF-8"), "ISO-8859-1") + ".xls"); //中文文件名 // + new String(fileName.getBytes("UTF-8"), "ISO-8859-1") + ".xls"); //中文文件名
//通过文件路径获得File对象 //通过文件路径获得File对象
File file = new File(url); File file = new File(url);
FileInputStream in = new FileInputStream(file); FileInputStream in = new FileInputStream(file);
//3.通过response获取OutputStream对象(out) //3.通过response获取OutputStream对象(out)
OutputStream out = new BufferedOutputStream(response.getOutputStream()); OutputStream out = new BufferedOutputStream(response.getOutputStream());
int b = 0; int b = 0;
byte[] buffer = new byte[2048]; byte[] buffer = new byte[2048];
while ((b=in.read(buffer)) != -1){ while ((b = in.read(buffer)) != -1) {
out.write(buffer,0,b); //4.写到输出流(out)中 out.write(buffer, 0, b); //4.写到输出流(out)中
} }
in.close(); in.close();
out.flush(); out.flush();
out.close(); out.close();
} catch (IOException e) { } catch (IOException e) {
log.error("下载Excel模板异常", e); log.error("下载Excel模板异常", e);
} }
} }
/** /**
* * @param @param request
* @Title: encodeChineseDownloadFileName * @param @param pFileName
* @Description: TODO(这里用一句话描述这个方法的作用)
* @param @param request
* @param @param pFileName
* @param @return * @param @return
* @param @throws UnsupportedEncodingException * @param @throws UnsupportedEncodingException
* @return String * @return String
* @throws * @throws
* @Title: encodeChineseDownloadFileName
* @Description: TODO(这里用一句话描述这个方法的作用)
*/ */
private static String encodeChineseDownloadFileName(HttpServletRequest request, String pFileName) private static String encodeChineseDownloadFileName(HttpServletRequest request, String pFileName)
throws UnsupportedEncodingException { throws UnsupportedEncodingException {
String filename = null; String filename = null;
String agent = request.getHeader("USER-AGENT"); String agent = request.getHeader("USER-AGENT");
//System.out.println("agent==========》"+agent); //System.out.println("agent==========》"+agent);
if (null != agent) { if (null != agent) {
if (-1 != agent.indexOf("Firefox")) {//Firefox if (-1 != agent.indexOf("Firefox")) {//Firefox
filename = "=?UTF-8?B?" + (new String(org.apache.commons.codec.binary.Base64.encodeBase64(pFileName.getBytes("UTF-8")))) + "?="; filename = "=?UTF-8?B?" + (new String(org.apache.commons.codec.binary.Base64.encodeBase64(pFileName.getBytes("UTF-8")))) + "?=";
...@@ -1355,20 +1344,67 @@ private static void defaultExport(List<Map<String, Object>> list, String fileNam ...@@ -1355,20 +1344,67 @@ private static void defaultExport(List<Map<String, Object>> list, String fileNam
} else { } else {
filename = pFileName; filename = pFileName;
} }
return filename; return filename;
} }
/** /**
* @Title: delFile
* @Description: 删除文件
* @param @param filePath 文件路径 * @param @param filePath 文件路径
* @return void * @return void
* @throws * @throws
* @Title: delFile
* @Description: 删除文件
*/ */
public static void delFile(String filePath) { public static void delFile(String filePath) {
java.io.File delFile = new java.io.File(filePath); java.io.File delFile = new java.io.File(filePath);
delFile.delete(); delFile.delete();
}
public static void writToResponse(Map data, HttpServletResponse response, TemplateExportParams params, String outFileName) throws Exception {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
Workbook book = ExcelExportUtil.exportExcel(params, data);
book.write(bout);
response.setHeader("Content-Disposition", "attachment; filename=" + outFileName);
response.setHeader("content-length", bout.size() + "");
response.getOutputStream().write(bout.toByteArray());
response.getOutputStream().flush();
response.getOutputStream().close();
}
/**
* 导出Excel
*
* @param workbook workbook流
* @param fileName 文件名
* @param response 响应
*/
public static void exportExcel(Workbook workbook, String fileName, HttpServletResponse response) {
//输出文件
try (OutputStream out = response.getOutputStream()) {
//获取文件名并转码
String name = URLEncoder.encode(fileName, "UTF-8");
//编码
response.setCharacterEncoding("UTF-8");
// 设置强制下载不打开
response.setContentType("application/force-download");
// 下载文件的默认名称
response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
//输出表格
workbook.write(out);
} catch (IOException e) {
log.error("文件导出异常,详情如下:", e);
} finally {
try {
if (workbook != null) {
//关闭输出流
workbook.close();
}
} catch (IOException e) {
log.error("文件导出异常,详情如下:", e);
}
}
} }
} }
...@@ -21,6 +21,7 @@ public class CheckAnalysisVo { ...@@ -21,6 +21,7 @@ public class CheckAnalysisVo {
private String missedRate; private String missedRate;
@Excel(name = "不合格率%", orderNum = "8") @Excel(name = "不合格率%", orderNum = "8")
private String faildRate; private String faildRate;
private String checkTime;
public String getName() { public String getName() {
return name; return name;
} }
...@@ -75,7 +76,12 @@ public class CheckAnalysisVo { ...@@ -75,7 +76,12 @@ public class CheckAnalysisVo {
public void setFaildRate(String faildRate) { public void setFaildRate(String faildRate) {
this.faildRate = faildRate; this.faildRate = faildRate;
} }
public String getCheckTime() {
return checkTime;
}
public void setCheckTime(String checkTime) {
this.checkTime = checkTime;
}
} }
...@@ -2,6 +2,9 @@ package com.yeejoin.amos.patrol.service.business.vo; ...@@ -2,6 +2,9 @@ package com.yeejoin.amos.patrol.service.business.vo;
import cn.afterturn.easypoi.excel.annotation.Excel; import cn.afterturn.easypoi.excel.annotation.Excel;
import java.util.List;
import java.util.Map;
public class CheckInfoVo { public class CheckInfoVo {
private String id; private String id;
...@@ -43,6 +46,11 @@ public class CheckInfoVo { ...@@ -43,6 +46,11 @@ public class CheckInfoVo {
private String error; private String error;
@Excel(name = "备注说明", orderNum = "14") @Excel(name = "备注说明", orderNum = "14")
private String remark; private String remark;
/**
* 检查项
*/
private Map<String, PointClassifyVo> checkInfoMap;
public String getId() { public String getId() {
return id; return id;
...@@ -171,4 +179,11 @@ public class CheckInfoVo { ...@@ -171,4 +179,11 @@ public class CheckInfoVo {
this.depId = depId; this.depId = depId;
} }
public Map<String, PointClassifyVo> getCheckInfoMap() {
return checkInfoMap;
}
public void setCheckInfoMap(Map<String, PointClassifyVo> checkInfoMap) {
this.checkInfoMap = checkInfoMap;
}
} }
...@@ -405,4 +405,9 @@ public class XJConstant { ...@@ -405,4 +405,9 @@ public class XJConstant {
public static final String INPUT_ITEM_XEXT= "小额"; public static final String INPUT_ITEM_XEXT= "小额";
public static final String INPUT_ITEM_WYXT = "网银"; public static final String INPUT_ITEM_WYXT = "网银";
public static final String INPUT_ITEM_JWXT = "境外"; public static final String INPUT_ITEM_JWXT = "境外";
public static final String PLANTASK_COUNT = "planTaskCount";
public static final String CHECK_COUNT = "checkCount";
public static final String MISSED = "missed";
public static final String FAILD = "faild";
} }
...@@ -6,9 +6,7 @@ import java.text.ParsePosition; ...@@ -6,9 +6,7 @@ import java.text.ParsePosition;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.Period; import java.time.Period;
import java.util.Calendar; import java.util.*;
import java.util.Date;
import java.util.TimeZone;
import com.yeejoin.amos.patrol.service.exception.YeeException; import com.yeejoin.amos.patrol.service.exception.YeeException;
...@@ -25,6 +23,9 @@ public class DateUtil { ...@@ -25,6 +23,9 @@ public class DateUtil {
public static String MID_PATTERN = "yyyy-MM-dd HH:mm"; public static String MID_PATTERN = "yyyy-MM-dd HH:mm";
public static String SHORT_PATTERN = "yyyy-MM-dd"; public static String SHORT_PATTERN = "yyyy-MM-dd";
private static final SimpleDateFormat monthSdf = new SimpleDateFormat("yyyy-MM");
private static final SimpleDateFormat shortSdf = new SimpleDateFormat("yyyy-MM-dd");
private static final SimpleDateFormat longSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static long THREE_DAY_MILLSEC = 259200000L; public static long THREE_DAY_MILLSEC = 259200000L;
public static long ONE_DAY_MILLSEC = 86400000L; public static long ONE_DAY_MILLSEC = 86400000L;
...@@ -632,4 +633,78 @@ public class DateUtil { ...@@ -632,4 +633,78 @@ public class DateUtil {
Date date = new Date(); Date date = new Date();
return date; return date;
} }
/**
* 获得本月的开始时间,即2012-01-01 00:00:00
*
* @return
*/
public static String getCurrentMonthStartTime(String str) {
Date now = null;
try {
Date date = monthSdf.parse(str);
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.DATE, 1);
now = shortSdf.parse(shortSdf.format(c.getTime()) + " 00:00:00");
} catch (ParseException e) {
e.printStackTrace();
}
return longSdf.format(now);
}
/**
* 当前月的结束时间,即2012-01-31 23:59:59
*
* @return
*/
public static String getCurrentMonthEndTime(String str) {
Date now = null;
try {
Date date = monthSdf.parse(str);
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.DATE, 1);
c.add(Calendar.MONTH, 1);
c.add(Calendar.DATE, -1);
now = longSdf.parse(shortSdf.format(c.getTime()) + " 23:59:59");
} catch (ParseException e) {
e.printStackTrace();
}
return longSdf.format(now);
}
/**
* 获取某月的日期List
*
* @return
*/
public static List<String> getDayByMonth(String startDate, String endDate) {
List list = new ArrayList();
try {
long startTime = shortSdf.parse(startDate).getTime();
long endTime = shortSdf.parse(endDate).getTime();
long day = 1000 * 60 * 60 * 24;
for (long i = startTime; i <= endTime; i += day) {
list.add(shortSdf.format(new Date(i)));
}
} catch (ParseException e) {
e.printStackTrace();
}
return list;
}
public static Date strToDateShort(String dateStr) {
try {
return monthSdf.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
//日期返回时分秒
public static String splitDate(String Date){
return Date.substring(11, Date.length());
}
} }
package com.yeejoin.amos.patrol.service.core.util;
import com.google.common.collect.Maps;
import com.yeejoin.amos.patrol.common.entity.DynamicBean;
import org.apache.commons.beanutils.PropertyUtilsBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.beans.PropertyDescriptor;
import java.util.Date;
import java.util.Map;
/**
* @Author: xinglei
* @Description:
* @Date: 2020/8/20 20:10
*/
public class ReflectUtil {
private static Logger logger = LoggerFactory.getLogger(ReflectUtil.class);
public static Object getObject(Object dest, Map<String, Object> addProperties) {
PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(dest);
Map<String, Class> propertyMap = Maps.newHashMap();
for (PropertyDescriptor d : descriptors) {
if (!"class".equalsIgnoreCase(d.getName())) {
propertyMap.put(d.getName(), d.getPropertyType());
}
}
addProperties.forEach((k, v) -> {
String sclass = v.getClass().toString();
if(sclass.equals("class java.util.Date")) {//对日期进行处理
propertyMap.put(k, Long.class);
}else {
propertyMap.put(k, v.getClass());
}
});
DynamicBean dynamicBean = new DynamicBean(dest.getClass(), propertyMap);
propertyMap.forEach((k, v) -> {
try {
if (!addProperties.containsKey(k)) {
dynamicBean.setValue(k, propertyUtilsBean.getNestedProperty(dest, k));
}
} catch (Exception e) {
logger.error("动态添加字段出错", e);
}
});
addProperties.forEach((k, v) -> {
try {
String sclass = v.getClass().toString();
if(sclass.equals("class java.util.Date")) {//动态添加的字段为date类型需要进行处理
Date date = (Date) v;
dynamicBean.setValue(k, date.getTime());
}else {
dynamicBean.setValue(k, v);
}
} catch (Exception e) {
logger.error("动态添加字段值出错", e);
}
});
Object obj = dynamicBean.getTarget();
return obj;
}
}
...@@ -28,7 +28,6 @@ import com.yeejoin.amos.patrol.service.business.util.Toke; ...@@ -28,7 +28,6 @@ import com.yeejoin.amos.patrol.service.business.util.Toke;
import com.yeejoin.amos.patrol.service.remote.feign.AmosBankFeign; import com.yeejoin.amos.patrol.service.remote.feign.AmosBankFeign;
import com.yeejoin.amos.patrol.service.remote.feign.IAMOSSecurityServer; import com.yeejoin.amos.patrol.service.remote.feign.IAMOSSecurityServer;
import org.apache.commons.collections4.map.LinkedMap;
//import com.yeejoin.amos.security.common.model.UserModel; //import com.yeejoin.amos.security.common.model.UserModel;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
...@@ -479,7 +478,6 @@ public class RemoteSecurityService { ...@@ -479,7 +478,6 @@ public class RemoteSecurityService {
} }
public JSONArray listDepartmentUserTree(String toke,String product,String appKey,String companyId) { public JSONArray listDepartmentUserTree(String toke,String product,String appKey,String companyId) {
RequestContext.setToken(toke); RequestContext.setToken(toke);
RequestContext.setProduct(product); RequestContext.setProduct(product);
RequestContext.setAppKey(appKey); RequestContext.setAppKey(appKey);
...@@ -495,15 +493,35 @@ public class RemoteSecurityService { ...@@ -495,15 +493,35 @@ public class RemoteSecurityService {
if (companyModel != null ) { if (companyModel != null ) {
String jsonStr =null; String jsonStr =null;
jsonStr = JSON.toJSONString(companyModel.getChildren()); jsonStr = JSON.toJSONString(companyModel.getChildren());
return JSONArray.parseArray(jsonStr); return JSONArray.parseArray(jsonStr);
} }
return null; return null;
} }
/**
* 查询公司名称
* @return
*/
public String getCompanyName(String toke,String product,String appKey,String companyId) {
String companyName = null;
RequestContext.setToken(toke);
RequestContext.setProduct(product);
RequestContext.setAppKey(appKey);
CompanyModel companyModel=null;
FeignClientResult feignClientResult;
try {
feignClientResult = Privilege.companyClient.withDeptAndUsers(Long.valueOf(companyId));
companyModel = (CompanyModel)feignClientResult.getResult();
} catch (InnerInvokException e) {
e.printStackTrace();
}
if (companyModel != null ) {
companyName = companyModel.getCompanyName();
}
return companyName;
}
public boolean editPassword(String toke,String product,String appKey,String userId, String oldPassword, String newPassword) throws InnerInvokException { public boolean editPassword(String toke,String product,String appKey,String userId, String oldPassword, String newPassword) throws InnerInvokException {
boolean flag=false; boolean flag=false;
......
...@@ -152,6 +152,132 @@ ...@@ -152,6 +152,132 @@
</choose> </choose>
</select> </select>
<!-- 部门分组查询(报表导出) -->
<select id="getCheckInfoGroup" resultMap="checkInputResultMap">
<choose>
<when test="statement != null and statement == 'business'">
SELECT
c.point_id pointId,
c.dep_id departmentId,
p.`name` pointName,
c.org_code orgCode,
date_format(
c.check_time,
'%Y-%m-%d %H:%i:%s'
) AS `checkDate`,
pt.id planTaskId,
pt.begin_time beginTime,
ci.id checkInputId,
ci.input_id inputId,
ci.input_value AS InputValue,
(
CASE ci.is_ok
WHEN 1 THEN
'合格'
WHEN 2 THEN
'不合格'
WHEN 3 THEN
'漏检'
END
) AS IsOK,
ii.`name` AS inputItemName,
c.upload_time AS UploadTime,
u.`name` AS RealName,
ci.score AS Score,
ci.point_classify_id classifyId,
ci.point_classify_name classifyName,
ci.remark,
(
SELECT
count(id)
FROM
p_check_shot pcs
WHERE
pcs.check_input_id = ci.input_id
AND pcs.check_id = ci.check_id
AND pcs.classify_id = IFNULL(ci.point_classify_id, 0)
) imgCount
FROM
p_check_input ci
LEFT JOIN p_input_item ii ON ci.input_id = ii.id
LEFT JOIN p_check c ON ci.check_id = c.id
LEFT JOIN s_user u ON c.user_id = u.id
LEFT JOIN p_point p ON c.point_id = p.id
LEFT JOIN p_plan_task_detail ptd ON c.plan_task_detail_id = ptd.id
LEFT JOIN p_plan_task pt ON pt.id = ptd.task_no
<trim prefix="WHERE" prefixOverrides="AND ">
<if test="beginDate!=null and endDate!=null">and c.check_time BETWEEN #{beginDate} and #{endDate}</if>
<if test="orgCode!=null">and c.org_Code like concat(#{orgCode},"%")</if>
<if test="departmentId!=null">and c.dep_id = #{departmentId}</if>
</trim>
GROUP BY inputId, classifyId
ORDER BY
checkDate ASC, pointId ASC, classifyId ASC
</when>
<otherwise>
select
c.point_id pointId,
p.`name` pointName,
c.dep_id departmentId,
c.org_code orgCode,
date_format(
c.check_time,
'%Y-%m-%d %H:%i:%s'
) AS `checkDate`,
c.upload_time AS UploadTime,
pt.id planTaskId,
pt.begin_time beginTime,
GROUP_CONCAT(DISTINCT pt.begin_time, '_', ci.is_ok) as idStateStr,
ci.id checkInputId,
ci.input_id inputId,
(
CASE ci.is_ok
WHEN 1 THEN
'合格'
WHEN 2 THEN
'不合格'
WHEN 3 THEN
'漏检'
END
) AS IsOK,
ii.`name` AS inputItemName,
ci.point_classify_id classifyId,
ci.point_classify_name classifyName
FROM
p_check c
LEFT JOIN p_point p ON c.point_id = p.id
LEFT JOIN p_plan_task_detail ptd ON c.plan_task_detail_id = ptd.id
LEFT JOIN p_check_input ci ON c.id = ci.check_id
LEFT JOIN p_input_item ii ON ci.input_id = ii.id
LEFT JOIN p_plan_task pt ON pt.id = ptd.task_no
<trim prefix="WHERE" prefixOverrides="AND ">
<if test="beginDate!=null and endDate!=null">and c.check_time BETWEEN #{beginDate} and #{endDate}</if>
<if test="orgCode!=null">and c.org_Code like concat(#{orgCode},"%")</if>
<if test="departmentId!=null">and c.dep_id = #{departmentId}</if>
and (pt.id is NOT NULL or pt.id = '')
</trim>
group by pointId, inputId
order BY pointId
</otherwise>
</choose>
</select>
<select id="getCheckInfoGroupCheckDate" resultMap="checkInputResultMap">
SELECT
GROUP_CONCAT(DISTINCT a.begin_Time order by a.begin_Time desc) as beginTimeStr
FROM
p_plan_task_detail b
LEFT JOIN p_plan_task a ON a.id = b.task_no
LEFT JOIN p_plan c ON c.id = a.plan_id
LEFT JOIN p_point d ON d.id = b.point_id
LEFT JOIN p_route e ON e.id = a.route_id
<trim prefix="WHERE" prefixOverrides="AND ">
<if test="beginDate!=null and endDate!=null">and a.begin_Time BETWEEN #{beginDate} and #{endDate}</if>
<if test="orgCode!=null">and a.org_Code like concat(#{orgCode},"%")</if>
<if test="departmentId!=null">and c.dept_id = #{departmentId}</if>
</trim>
</select>
<select id="queryUnqualifiedInputItem" resultType="Map" parameterType="int"> <select id="queryUnqualifiedInputItem" resultType="Map" parameterType="int">
SELECT SELECT
ii.name, ii.name,
...@@ -798,7 +924,14 @@ ...@@ -798,7 +924,14 @@
<resultMap id="checkInputResultMap" <resultMap id="checkInputResultMap"
type="com.yeejoin.amos.patrol.service.business.bo.patrol.CheckInputBo"> type="com.yeejoin.amos.patrol.service.business.bo.patrol.CheckInputBo">
<result property="inputItemName" column="Name"/> <result property="pointId" column="pointId"/>
<result property="pointName" column="pointName"/>
<result property="orgCode" column="orgCode"/>
<result property="checkDate" column="checkDate"/>
<result property="beginTime" column="beginTime"/>
<result property="beginTimeStr" column="beginTimeStr"/>
<result property="idStateStr" column="idStateStr"/>
<result property="inputItemName" column="inputItemName"/>
<result property="inputValue" column="InputValue"/> <result property="inputValue" column="InputValue"/>
<result property="isOK" column="IsOK"/> <result property="isOK" column="IsOK"/>
<result property="uploadTime" column="UploadTime"/> <result property="uploadTime" column="UploadTime"/>
...@@ -1698,6 +1831,168 @@ ...@@ -1698,6 +1831,168 @@
</choose> </choose>
</select> </select>
<select id="getCheckStatisticalByCheck" resultType="com.yeejoin.amos.patrol.service.business.vo.CheckAnalysisVo">
select
a.deptName name,
count(a.checkId) planTaskCount,
sum(a.finish ) checkCount,
sum(a.ok) ok,
sum(a.faild) faild,
sum(a.missed) missed,
sum(a.score) score,
sum(a.missed) / count(a.checkId) * 100 missedRate,
sum(a.faild) / count(a.checkId) * 100 faildRate,
a.checkTime
FROM
(
SELECT
CASE
WHEN c.plan_id = 0 THEN
'计划外'
ELSE
p. NAME
END planName,
c.plan_id planId,
r. NAME routeName,
r.id routeId,
pt. NAME pointName,
pt.id pointId,
c.user_id userId,
c.score,
c.dep_id departmentId,
c.dep_id deptName ,
c.user_id userName ,
c.id checkId,
c.plan_task_detail_id taskDetailId,
c.is_ok isOk,
c.plan_task_id,
DATE_FORMAT(c.check_time,'%Y-%m-%d') checkTime,
DATE_FORMAT(c.check_time,'%Y-%m') checkMonth,
CASE
WHEN c.is_ok = 1 THEN
1
ELSE
0
END ok,
CASE
WHEN c.is_ok = 2 THEN
1
ELSE
0
END faild,
CASE
WHEN c.is_ok = 3 THEN
1
ELSE
0
END missed,
CASE
WHEN c.is_ok = 3 THEN
0
ELSE
1
END finish
FROM
p_check c
LEFT JOIN p_plan p ON c.plan_id = p.id
LEFT JOIN p_plan_task pnt ON c.plan_task_id = pnt.id
LEFT JOIN p_route r ON c.route_id = r.id
LEFT JOIN p_point pt ON c.point_id = pt.id
WHERE c.org_code LIKE CONCAT(#{orgCode}, '%')
<if test="userName !=null and userName != '' ">and c.user_name like CONCAT('%', #{userName}, '%')</if>
<if test="pointNo !=null and pointNo != '' ">and pt.point_no like CONCAT('%', #{pointNo}, '%')</if>
<if test="pointName !=null and pointName != '' ">and pt.name like CONCAT('%', #{pointName}, '%')</if>
<if test="isFixed !=null and isFixed != '' ">and pt.is_fixed = #{isFixed}</if>
<choose>
<when test=" processType > 0 and processType == 4 ">
and <![CDATA[ c.plan_id = 0 ]]>
</when>
<when test="processType > 0 and processType != 4 ">
and pnt.status = #{processType}
</when>
</choose>
<if test="isOk !=null and isOk != '' ">and c.isOk = #{isOk}</if>
<if test="planId !=null and planId != '' ">and c.plan_id = #{planId}</if>
<if test="routeId !=null and routeId != '' ">and c.route_id = #{routeId}</if>
<if test="startTime !=null and startTime!= '' "> <![CDATA[ AND c.check_time >= #{startTime} ]]> </if>
<if test="endTime !=null and endTime!='' "><![CDATA[AND c.check_time <= #{endTime} ]]></if>
) a
GROUP BY
a.deptName,
a.checkTime
</select>
<select id="getCheckStatisticalByPlanTask" resultType="com.yeejoin.amos.patrol.service.business.vo.CheckAnalysisVo">
select
a.deptName name,
count(a.checkId) planTaskCount,
sum(a.finish ) checkCount,
sum(a.ok) ok,
sum(a.faild) faild,
sum(a.missed) missed,
a.checkTime
FROM
( SELECT
CASE
WHEN pnt.plan_id = 0 THEN
'计划外'
ELSE
p. NAME
END planName,
pnt.plan_id planId,
r. NAME routeName,
r.id routeId,
p.dept_id departmentId,
p.dept_id deptName,
pnt.finish_status isOk,
pnt.id checkId,
DATE_FORMAT(pnt.check_date, '%Y-%m-%d') checkTime,
DATE_FORMAT(pnt.check_date, '%Y-%m') checkMonth,
CASE
WHEN pnt.finish_status = 1 THEN
1
ELSE
0
END ok,
CASE
WHEN pnt.finish_status = 2 THEN
1
ELSE
0
END faild,
CASE
WHEN pnt.finish_status = 3 THEN
1
ELSE
0
END missed,
CASE
WHEN pnt.finish_status = 3 THEN
0
ELSE
1
END finish
FROM
p_plan_task pnt
LEFT JOIN p_plan p ON pnt.plan_id = p.id
LEFT JOIN p_route r ON pnt.route_id = r.id
WHERE pnt.org_code LIKE CONCAT(#{orgCode}, '%')
<choose>
<when test=" processType > 0 and processType == 4 ">
and <![CDATA[ c.plan_id = 0 ]]>
</when>
<when test="processType > 0 and processType != 4 ">
and pnt.status = #{processType}
</when>
</choose>
<if test="isOk !=null and isOk != '' ">and c.isOk = #{isOk}</if>
<if test="startTime !=null and startTime!= '' "> <![CDATA[ AND pnt.check_date >= #{startTime} ]]> </if>
<if test="endTime !=null and endTime!='' "><![CDATA[AND pnt.check_date <= #{endTime} ]]></if>
) a
GROUP BY
a.deptName,
a.checkTime
</select>
<select id="getCumulativeCheckCountByOrgCode" resultType="Long"> <select id="getCumulativeCheckCountByOrgCode" resultType="Long">
select count(1) total from p_check c where c.org_code like concat(#{orgCode},"%") and c.is_ok != '3' select count(1) total from p_check c where c.org_code like concat(#{orgCode},"%") and c.is_ok != '3'
......
...@@ -171,6 +171,11 @@ ...@@ -171,6 +171,11 @@
<version>3.3.1</version> <version>3.3.1</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>3.2.4</version>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId> <groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId> <artifactId>HikariCP</artifactId>
</dependency> </dependency>
...@@ -244,11 +249,6 @@ ...@@ -244,11 +249,6 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.poi</groupId> <groupId>org.apache.poi</groupId>
<artifactId>ooxml-schemas</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId> <artifactId>poi-ooxml</artifactId>
<version>3.14</version> <version>3.14</version>
</dependency> </dependency>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment