package com.bocloud.sms.service; import com.bocloud.sms.entity.Business; import com.bocloud.sms.entity.Project; import com.bocloud.sms.interfaces.BusinessService; import com.bocloud.sms.model.BusinessModel; import com.bocloud.sms.model.ImpExpBusinessExcelModel; import com.bocloud.sms.repository.BusinessRepository; import com.bocloud.sms.repository.ProjectRepository; import com.megatron.common.model.*; import com.megatron.common.utils.Common; import com.megatron.common.utils.ListTool; import com.megatron.framework.lock.AutoCloseLock; import com.megatron.framework.lock.LockFactory; import jakarta.servlet.http.HttpServletResponse; import lombok.extern.slf4j.Slf4j; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.*; import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Service; import org.springframework.util.Assert; import org.springframework.web.multipart.MultipartFile; import java.io.InputStream; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import static com.bocloud.sms.service.utils.ExportUtil.*; /** * @author tyl * @time 2020/6/2 周二 16:16 */ @Service("businessService") @Slf4j public class BusinessServiceImpl implements BusinessService { private final BusinessRepository businessRepository; private final ProjectRepository projectRepository; private final LockFactory lockFactory; public BusinessServiceImpl(BusinessRepository businessRepository, ProjectRepository projectRepository, LockFactory lockFactory) { this.businessRepository = businessRepository; this.projectRepository = projectRepository; this.lockFactory = lockFactory; } @Override public GeneralResult> list(Pager pager, RequestContext requestContext) { try { GridBean gridBean; List params = Optional.ofNullable(pager.getParams()).orElse(new ArrayList<>()); Map sorter = Optional.ofNullable(pager.getSorter()).orElse(new HashMap<>(16, 0.75F)); sorter.put("gmtCreate", Common.ONE); sorter.put("id", Common.ONE); int total = businessRepository.count(params); if (Boolean.TRUE.equals(pager.getSimple())) { List beans = businessRepository.list(params, sorter); gridBean = new GridBean(1, 1, total, beans); } else { List beans = businessRepository.list(pager.getPage(), pager.getRows(), params, sorter); for (Business bean : beans) { List projects = projectRepository.businessProjects(bean.getId()); List projectIds = projects.stream().map(Project::getId).collect(Collectors.toList()); bean.setProjectIds(projectIds); StringBuilder builder = new StringBuilder(); for (Project project : projects) { builder.append(project.getName()).append(","); } if (builder.length() > 0) { bean.setProjects(builder.substring(0, builder.length() - 1)); } bean.setProjectNum(projects.size()); } gridBean = new GridBean<>(pager.getPage(), pager.getRows(), total, beans); } return new GeneralResult<>(true, gridBean, "查询成功"); } catch (Exception e) { log.error("Query Business list fail:", e); return new GeneralResult<>(false, "查询失败:" + e.getMessage()); } } @Override public Result create(BusinessModel params, RequestContext requestContext) { try { Business business = new Business(); BeanUtils.copyProperties(params, business); Assert.isTrue(!businessRepository.exist(business.getName()), "名称已存在"); Assert.isNull(businessRepository.queryByCode(business.getCode()), "该业务编码已存在"); business.setCreatorId(requestContext.getTarget()); business.setMenderId(requestContext.getTarget()); business.setTenantId(requestContext.getTenant()); businessRepository.save(business); List projectIds = Optional.ofNullable(params.getProjectIds()).orElse(new ArrayList<>()); if (!projectIds.isEmpty()) { List projects = projectRepository.listByIds(projectIds); projects.forEach(project -> project.setBusinessId(business.getId())); if (!projects.isEmpty()) { projectRepository.batchUpdate(projects, projects.size()); } } return new Result(true, "添加成功"); } catch (Exception e) { log.error("creat Business error:", e); return new Result(false, "添加失败:" + e.getMessage()); } } @Override public Result remove(Long id, RequestContext requestContext) { String path = Business.class.getSimpleName() + "_" + id; try (AutoCloseLock lock = lockFactory.getACLock(path)) { Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时"); Business business = businessRepository.query(id); Assert.notNull(business, "业务数据不存在。"); List projects = projectRepository.listByBusiness(id); Assert.isTrue(ListTool.isEmpty(projects), "有项目正在使用该业务,请先删除项目"); boolean result = businessRepository.remove(id, requestContext.getTarget()); if (result) { return new Result(true, "删除成功"); } else { return new Result(false, "删除失败"); } } catch (Exception e) { log.error("remove Business fail:", e); return new Result(false, "删除业务失败" + e.getMessage()); } } @Override public Result batchRemove(List ids, RequestContext requestContext) { try { for (Long id : ids) { Business business = businessRepository.query(id); Assert.notNull(business, "业务数据不存在。"); List projects = projectRepository.listByBusiness(id); Assert.isTrue(ListTool.isEmpty(projects), business.getName() + "业务下有项目正在使用该业务,请先删除项目"); } boolean result = businessRepository.batchRemove(ids, requestContext.getTarget()); if (result) { return new Result(true, "批量删除成功"); } else { return new Result(false, "批量删除失败"); } } catch (Exception e) { log.error("batch remove Business fail:", e); return new Result(false, "批量删除业务失败" + e.getMessage()); } } @Override public GeneralResult detail(Long id) { try { Business business = businessRepository.query(id); Assert.notNull(business, "业务不存在"); List projects = projectRepository.businessProjects(business.getId()); List projectIds = projects.stream().map(Project::getId).collect(Collectors.toList()); business.setProjectIds(projectIds); return new GeneralResult<>(true, business, "查询详情成功"); } catch (Exception e) { log.error("query Business detail fail:", e); return new GeneralResult<>(false, "查询业务详情失败:" + e.getMessage()); } } @Override public Result modify(Long id, BusinessModel model, RequestContext requestContext) { String path = Business.class.getSimpleName() + "_" + id; try (AutoCloseLock lock = lockFactory.getACLock(path)) { Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时"); Business business = businessRepository.query(id); Assert.notNull(business, "数据不存在"); if (!business.getName().equals(model.getName()) && businessRepository.exist(model.getName())) { log.warn("Business already exist!"); return new Result(false, "业务名称已存在"); } if (model.getCode() != null && !model.getCode().equals(business.getCode())) { Business queryByCode = businessRepository.queryByCode(model.getCode()); if (queryByCode != null) { log.warn("Business code already exist!"); return new Result(false, "业务编码已存在"); } } business.setName(model.getName()); business.setCode(model.getCode()); business.setRemark(model.getRemark()); business.setMenderId(requestContext.getTarget()); business.setGmtModify(new Date()); businessRepository.update(business); return new Result(true, "修改成功"); } catch (Exception e) { log.error("remove Business fail:", e); return new Result(false, "修改业务失败:" + e.getMessage()); } } /** * 查询业务下的项目 * * @param id * @return */ @Override public GeneralResult> listBusinessProject(Long id) { try { List result = new ArrayList<>(); List projects = projectRepository.listByBusiness(id); for (Project project : projects) { project.setCheck(true); result.add(project); } List noBusinessProjects = projectRepository.getNoBusinessProjects(); for (Project project : noBusinessProjects) { project.setCheck(false); result.add(project); } return new GeneralResult<>(true, result, "获取成功"); } catch (Exception e) { log.error("get business project error", e); return new GeneralResult<>(false, "获取失败:" + e.getMessage()); } } /** * 业务操作 * * @param id * @param projectIds * @return */ @Override public Result businessAction(Long id, List projectIds) { try { List projects = new ArrayList<>(); if (projectIds.isEmpty()) { List businessProject = projectRepository.listByBusiness(id); for (Project project : businessProject) { project.setBusinessId(null); projects.add(project); } } else { List businessProject = projectRepository.listByIds(projectIds); for (Project project : businessProject) { project.setBusinessId(id); projects.add(project); } List oldProjects = projectRepository.listByBusiness(id); for (Project oldProject : oldProjects) { if (!projectIds.contains(oldProject.getId())) { oldProject.setBusinessId(null); projects.add(oldProject); } } } if (!projects.isEmpty()) { projectRepository.batchUpdate(projects, projects.size()); } return new Result(true, "操作成功"); } catch (Exception e) { log.error("business action error", e); return GeneralResult.FAILED("操作失败:" + e.getMessage()); } } @Override public XSSFWorkbook importTemp2(String name, RequestContext requestContext) { //创建一个HSSFWorkbook,对应一个Excel文件 try (XSSFWorkbook wb = new XSSFWorkbook()) { //在workbook中添加一个sheet,对应Excel文件中的主sheet XSSFSheet sheet = wb.createSheet(name); //在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制 XSSFRow row = sheet.createRow(0); //创建单元格,并设置值表头 设置表头居中 XSSFCellStyle style = wb.createCellStyle(); // 创建一个居中格式 style.setAlignment(HorizontalAlignment.CENTER); // 设置为文本格式,防止身份证号变成科学计数法 DataFormat format = wb.createDataFormat(); style.setDataFormat(format.getFormat("@")); String[] title = {"业务名称", "业务描述"}; for (int i = 0; i < title.length; i++) { XSSFCell cell = row.createCell(i); cell.setCellValue(title[i]); cell.setCellStyle(style); sheet.setColumnWidth(i, 20 * 256); sheet.setDefaultColumnStyle(i, style); } return wb; } catch (Exception e) { log.error("get import template error", e); return null; } } @Override public Result importTemp(HttpServletResponse response) { // 导出 Excel boolean exportExcel = exportExcel("业务模板" + System.currentTimeMillis(), "业务模板", response, new ArrayList<>(), ImpExpBusinessExcelModel.class, null); return exportExcel ? new Result(true, "导出业务模板成功") : new Result(false, "导出业务模板失败"); } @Override public Result importData(MultipartFile multipartFile, RequestContext requestContext) { try { String originalFilename = multipartFile.getOriginalFilename(); Assert.notNull(originalFilename, "文件名不能为空"); InputStream inputStream = multipartFile.getInputStream(); Workbook wb = new XSSFWorkbook(inputStream); List businesses = readExcel(wb); Assert.notEmpty(businesses, "导入模板数据不能为空"); int errorNumber = 0; List existNames = businessRepository.list(1, Integer.MAX_VALUE, null, null).stream().map(Business::getName) .collect(Collectors.toList()); ListIterator listIterator = businesses.listIterator(); while (listIterator.hasNext()) { Business business = listIterator.next(); if (existNames.contains(business.getName())) { errorNumber++; listIterator.remove(); log.error("business {} has existed", business.getName()); } } businessRepository.batchSave(businesses, businesses.size()); if (errorNumber != 0) { return new Result(true, "导入成功" + errorNumber + "条记录导入失败,失败原因:业务名称已经存在"); } else { return new Result(true, "导入成功"); } } catch (Exception e) { log.error("import business error:", e); return new Result(false, "导入业务失败:", e.getMessage()); } } private List readExcel(Workbook wb) { Sheet sheet = wb.getSheetAt(0); List businesses = new ArrayList<>(); for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) { Row row = sheet.getRow(rowNum); Business business = new Business(); Cell name = row.getCell(0); business.setName(getCellStringValue(name)); Cell code = row.getCell(1); business.setCode(getCellStringValue(code)); Cell remark = row.getCell(3); business.setRemark(getCellStringValue(remark)); businesses.add(business); } return businesses; } @Override public XSSFWorkbook export(List paramList, RequestContext requestContext) { try { Map sorter = new HashMap<>(4); sorter.put("gmtCreate", Common.ONE); List businesses = businessRepository.list(1, Integer.MAX_VALUE, paramList, sorter); for (Business bean : businesses) { List projects = projectRepository.businessProjects(bean.getId()); List projectIds = projects.stream().map(Project::getId).collect(Collectors.toList()); bean.setProjectIds(projectIds); StringBuilder builder = new StringBuilder(); for (Project project : projects) { builder.append(project.getName()).append(","); } if (builder.length() > 0) { bean.setProjects(builder.substring(0, builder.length() - 1)); } bean.setProjectNum(projects.size()); } // 创建HSSFWorkbook String sheetName = "业务统计数据"; String[] cellTitle = new String[]{"业务名称", "业务编码", "业务描述", "关联项目"}; String[][] rows; if (!ListTool.isEmpty(businesses)) { rows = new String[businesses.size()][cellTitle.length]; for (int i = 0; i < businesses.size(); i++) { Business business = businesses.get(i); rows[i][0] = business.getName(); rows[i][1] = business.getCode(); rows[i][2] = business.getRemark(); rows[i][3] = business.getProjects(); } } else { rows = new String[0][cellTitle.length]; } return getXssfWorkbook(sheetName, cellTitle, rows); } catch (Exception e) { log.error("create business work book fail:", e); return null; } } }