/** * Copyright 2018 人人开源 https://www.renren.io *

* This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. *

* This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. *

* You should have received a copy of the GNU General Public License * along with this program. If not, see . */ package com.epmet.controller; import cn.afterturn.easypoi.excel.ExcelExportUtil; import cn.afterturn.easypoi.excel.entity.TemplateExportParams; import com.alibaba.excel.EasyExcel; import com.alibaba.excel.ExcelWriter; import com.alibaba.excel.enums.WriteDirectionEnum; import com.alibaba.excel.write.metadata.WriteSheet; import com.alibaba.excel.write.metadata.fill.FillConfig; import com.alibaba.excel.write.metadata.fill.FillWrapper; import com.alibaba.fastjson.JSON; import com.epmet.commons.tools.annotation.LoginUser; import com.epmet.commons.tools.aop.NoRepeatSubmit; import com.epmet.commons.tools.constant.NumConstant; import com.epmet.commons.tools.dto.result.CustomerStaffInfoCacheResult; import com.epmet.commons.tools.exception.EpmetErrorCode; import com.epmet.commons.tools.exception.ExceptionUtils; import com.epmet.commons.tools.exception.RenException; import com.epmet.commons.tools.page.PageData; import com.epmet.commons.tools.redis.common.CustomerStaffRedis; import com.epmet.commons.tools.security.dto.TokenDto; import com.epmet.commons.tools.utils.ConvertUtils; import com.epmet.commons.tools.utils.Result; import com.epmet.commons.tools.validator.ValidatorUtils; import com.epmet.dto.IcResiUserDTO; import com.epmet.dto.form.*; import com.epmet.dto.result.*; import com.epmet.feign.OperCustomizeOpenFeignClient; import com.epmet.service.IcResiUserImportService; import com.epmet.service.IcResiUserService; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.poi.ss.usermodel.Workbook; import org.jetbrains.annotations.NotNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URLEncoder; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; /** * 用户基础信息 * * @author generator generator@elink-cn.com * @since v1.0.0 2021-10-26 */ @Slf4j @RestController @RequestMapping("icresiuser") public class IcResiUserController { private static final String BASE_TABLE_NAME = "ic_resi_user"; private Path IC_RESI_UPLOAD_DIR; @Autowired private OperCustomizeOpenFeignClient operCustomizeOpenFeignClient; @Autowired private IcResiUserService icResiUserService; @Autowired private IcResiUserImportService icResiUserImportService; { // 初始化上传目录 String home = System.getProperty("user.home"); Path importDir = Paths.get(home, "epmet_files", "ic_user_import"); if (Files.notExists(importDir)) { try { Files.createDirectories(importDir); } catch (IOException e) { log.error("创建数字赋能平台上传目录失败"); } } IC_RESI_UPLOAD_DIR = importDir; } @PostMapping("delete") public Result delete(@LoginUser TokenDto tokenDto,@RequestBody DelIcResiUserFormDTO formDTO){ formDTO.setCustomerId(tokenDto.getCustomerId()); ValidatorUtils.validateEntity(formDTO,DelIcResiUserFormDTO.IdGroup.class); icResiUserService.delete(formDTO); return new Result(); } /** * @Author sun * @Description 党建互联平台--保存居民信息 **/ @PostMapping("add") public Result add(@LoginUser TokenDto tokenDto, @RequestBody List formDTO) { icResiUserService.add(tokenDto, formDTO); return new Result(); } /** * @Author sun * @Description 党建互联平台--修改居民信息 **/ @PostMapping("edit") public Result edit(@LoginUser TokenDto tokenDto, @RequestBody List formDTO) { icResiUserService.edit(tokenDto, formDTO); return new Result(); } /** * @Description 根据房间号查人 * @Param formDTO * @Return {@link Result>} * @Author zhaoqifeng * @Date 2021/11/1 11:04 */ @PostMapping("getpeoplebyroom") public Result> getPeopleByRoom(@RequestBody IcResiUserDTO formDTO) { return new Result>().ok(icResiUserService.getPeopleByRoom(formDTO.getHomeId())); } @PostMapping("listresi") public Result>> queryListResi1(@LoginUser TokenDto tokenDto, @RequestBody IcResiUserPageFormDTO pageFormDTO) { //pageFormDTO.setCustomerId("45687aa479955f9d06204d415238f7cc"); pageFormDTO.setCustomerId(tokenDto.getCustomerId()); pageFormDTO.setStaffId(tokenDto.getUserId()); ValidatorUtils.validateEntity(pageFormDTO, IcResiUserPageFormDTO.AddUserInternalGroup.class); return new Result>>().ok(icResiUserService.pageResiMap(pageFormDTO)); } /** * 编辑页面,显示居民信息详情 * * @param pageFormDTO * @return com.epmet.commons.tools.utils.Result * @author yinzuomei * @date 2021/10/28 10:29 上午 */ @PostMapping("detail") public Result queryIcResiDetail(@LoginUser TokenDto tokenDto, @RequestBody IcResiDetailFormDTO pageFormDTO) { //pageFormDTO.setCustomerId("45687aa479955f9d06204d415238f7cc"); pageFormDTO.setCustomerId(tokenDto.getCustomerId()); ValidatorUtils.validateEntity(pageFormDTO, IcResiDetailFormDTO.AddUserInternalGroup.class); return new Result().ok(icResiUserService.queryIcResiDetail(pageFormDTO)); } /** * desc :备用 easypoi * @param customerId * @param pageFormDTO * @param response * @throws Exception */ @RequestMapping(value = "/exportExcel2") public void exportExcel(@RequestHeader String customerId,@LoginUser TokenDto tokenDto, @RequestBody IcResiUserPageFormDTO pageFormDTO, HttpServletResponse response) throws Exception { CustomerStaffInfoCacheResult staffInfoCacheResult = CustomerStaffRedis.getStaffInfo(customerId, tokenDto.getUserId()); String staffOrgPath = null; if (StringUtils.isNotBlank(staffInfoCacheResult.getAgencyPIds()) && !NumConstant.ZERO_STR.equals(staffInfoCacheResult.getAgencyPIds())) { staffOrgPath = staffInfoCacheResult.getAgencyPIds().concat(":").concat(staffInfoCacheResult.getAgencyId()); }else{ staffOrgPath=staffInfoCacheResult.getAgencyId(); } pageFormDTO.setCustomerId(customerId); pageFormDTO.setPageFlag(false); CustomerFormResultDTO resiFormItems = getResiFormAddItems(pageFormDTO.getCustomerId()); Map> otherSheetItems = buildItemMap(resiFormItems); Map> resiMainList = icResiUserService.getDataForExport(otherSheetItems.get(BASE_TABLE_NAME),new HashMap<>(), pageFormDTO.getCustomerId(), pageFormDTO.getFormCode(), BASE_TABLE_NAME, pageFormDTO.getConditions(),staffInfoCacheResult.getAgencyId(),staffOrgPath); //resiMainList = (List>)JSON.parse("[{\"IS_BDHJ\":\"1\",\"IS_SPECIAL\":\"1\",\"IS_XFRY\":\"0\",\"REMARKS\":\"beizhu\",\"IS_PARTY\":\"1\",\"icResiUserId\":\"yzmtest2\",\"HOME_ID\":\"中海国际社区一里城1号楼1单元101\",\"HOUSE_TYPE\":\"平房\",\"UNIT_NAME\":\"1单元\",\"GRID_ID\":\"市北区-市北区第三网格3\",\"IS_DB\":\"0\",\"GENDER\":\"男\",\"BIRTHDAY\":\"2021-10-04\",\"IS_VETERANS\":\"0\",\"IS_MB\":\"0\",\"IS_UNEMPLOYED\":\"0\",\"DEMAND_NAME\":null,\"IS_KC\":\"0\",\"IS_ENSURE_HOUSE\":\"0\",\"IS_SD\":\"0\",\"NAME\":\"尹作梅\",\"RDSJ\":null,\"IS_VOLUNTEER\":\"1\",\"GRID_ID_VALUE\":\"e74829ffc43d5470eba6b5e060c11e63\",\"IS_SZ\":\"0\",\"IS_CJ\":\"0\",\"HOME_ID_VALUE\":\"200\",\"DEMAND_CATEGORY_IDS\":null,\"VILLAGE_NAME\":\"中海国际社区一里城\",\"IS_DBH\":\"0\",\"IS_SN\":\"0\",\"BUILD_NAME\":\"1号楼\",\"IS_YLFN\":\"0\",\"IS_UNITED_FRONT\":\"0\",\"ID_CARD\":\"371325199310260529\",\"MOBILE\":\"15764229697\",\"IS_OLD_PEOPLE\":\"0\",\"DOOR_NAME\":\"101\"},{\"IS_SPECIAL\":\"1\",\"IS_XFRY\":\"0\",\"REMARKS\":\"beizhu\",\"IS_PARTY\":\"1\",\"icResiUserId\":\"yzmtest\",\"HOME_ID\":\"中海国际社区一里城1号楼1单元101\",\"HOUSE_TYPE\":\"平房\",\"UNIT_NAME\":\"1单元\",\"GRID_ID\":\"市北区-市北区第三网格3\",\"IS_DB\":\"0\",\"GENDER\":\"男\",\"BIRTHDAY\":\"2021-10-04\",\"IS_VETERANS\":\"0\",\"IS_MB\":\"0\",\"IS_UNEMPLOYED\":\"0\",\"DEMAND_NAME\":\"心理咨询\",\"IS_KC\":\"0\",\"IS_ENSURE_HOUSE\":\"0\",\"IS_SD\":\"0\",\"NAME\":\"尹作梅\",\"RDSJ\":\"2021-10-28 00:00:00\",\"IS_VOLUNTEER\":\"1\",\"GRID_ID_VALUE\":\"e74829ffc43d5470eba6b5e060c11e63\",\"IS_SZ\":\"0\",\"IS_CJ\":\"0\",\"HOME_ID_VALUE\":\"200\",\"DEMAND_CATEGORY_IDS\":\"10180002\",\"VILLAGE_NAME\":\"中海国际社区一里城\",\"IS_DBH\":\"0\",\"IS_SN\":\"0\",\"BUILD_NAME\":\"1号楼\",\"IS_YLFN\":\"0\",\"IS_UNITED_FRONT\":\"0\",\"ID_CARD\":\"371325199310260529\",\"MOBILE\":\"15764229697\",\"IS_OLD_PEOPLE\":\"0\",\"DOOR_NAME\":\"101\"}]"); log.info("resiMainList:{}", JSON.toJSONString(resiMainList)); String templatePath = "excel/ic_resi_info_cid.xls"; TemplateExportParams params = new TemplateExportParams(templatePath, true); Map> sheetMap = new HashMap<>(); Map mapData = new HashMap<>(); mapData.put("list", resiMainList.values()); System.out.println("===resiMainList==="+" "+JSON.toJSONString(resiMainList.values())); sheetMap.put(0, mapData); AtomicInteger n = new AtomicInteger(); for (FormItemResult item : resiFormItems.getItemList()) { if (item.getChildGroup() != null) { if (!item.getChildGroup().getTableName().equals(BASE_TABLE_NAME)) { Map itemMap1 = otherSheetItems.get(item.getChildGroup().getTableName()); Map> resiChildMap = icResiUserService.getDataForExport(itemMap1,resiMainList, pageFormDTO.getCustomerId(), pageFormDTO.getFormCode(), item.getChildGroup().getTableName(), pageFormDTO.getConditions(),staffInfoCacheResult.getAgencyId(),staffOrgPath); //resiChildMap.forEach((key, value) -> value.putAll(resiMainList.get(key))); Map mapData2 = new HashMap<>(); mapData2.put("list", resiChildMap.values()); System.out.println("===resiChildMap==="+item.getChildGroup().getTableName()+" "+JSON.toJSONString(resiChildMap.values())); sheetMap.put(n.incrementAndGet(), mapData2); } } } Workbook workbook = ExcelExportUtil.exportExcel(sheetMap, params); workbook.setActiveSheet(0); workbook.write(getOutputStream("居民基本信息.xls",response)); } @RequestMapping(value = "/exportExcel") public void exportExcelByEasyExcel(@RequestHeader String customerId,@LoginUser TokenDto tokenDto, @RequestBody IcResiUserPageFormDTO pageFormDTO, HttpServletResponse response) throws Exception { //tokenDto.setUserId("9e37adcce6472152e6508a19d3683e02"); CustomerStaffInfoCacheResult staffInfoCacheResult = CustomerStaffRedis.getStaffInfo(customerId, tokenDto.getUserId()); String staffOrgPath = null; if (StringUtils.isNotBlank(staffInfoCacheResult.getAgencyPIds()) && !NumConstant.ZERO_STR.equals(staffInfoCacheResult.getAgencyPIds())) { staffOrgPath = staffInfoCacheResult.getAgencyPIds().concat(":").concat(staffInfoCacheResult.getAgencyId()); }else{ staffOrgPath=staffInfoCacheResult.getAgencyId(); } pageFormDTO.setCustomerId(customerId); pageFormDTO.setPageFlag(false); CustomerFormResultDTO resiFormItems = getResiFormAddItems(pageFormDTO.getCustomerId()); Map> otherSheetItems = buildItemMap(resiFormItems); /*List resiFormAllItems = getResiFormAllItems(pageFormDTO.getCustomerId()); resiFormAllItems.stream().collect(Collectors.groupingBy(e ->e.get));*/ Map> resiMainList = icResiUserService.getDataForExport(otherSheetItems.get(BASE_TABLE_NAME),new HashMap<>(), pageFormDTO.getCustomerId(), pageFormDTO.getFormCode(), BASE_TABLE_NAME, pageFormDTO.getConditions(),staffInfoCacheResult.getAgencyId(),staffOrgPath); //========================================= String templatePath = "excel/ic_resi_info_cid_for_easy_excel.xlsx"; InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(templatePath); String fileName = "居民基本信息.xlsx"; ExcelWriter excelWriter = EasyExcel.write(getOutputStream(fileName,response)).withTemplate(inputStream).build(); FillConfig fillConfig = FillConfig.builder().direction(WriteDirectionEnum.VERTICAL).build(); WriteSheet fistSheet = EasyExcel.writerSheet(NumConstant.ZERO).build(); System.out.println("===resiMainList==="+" "+JSON.toJSONString(resiMainList.values())); excelWriter.fill(new FillWrapper("t1", resiMainList.values()),fillConfig, fistSheet); //======================================= AtomicInteger n = new AtomicInteger(); for (FormItemResult item : resiFormItems.getItemList()) { if (item.getChildGroup() != null) { if (!item.getChildGroup().getTableName().equals(BASE_TABLE_NAME)) { Map itemMap1 = otherSheetItems.get(item.getChildGroup().getTableName()); Map> resiChildMap = icResiUserService.getDataForExport(itemMap1,resiMainList, pageFormDTO.getCustomerId(), pageFormDTO.getFormCode(), item.getChildGroup().getTableName(), pageFormDTO.getConditions(),staffInfoCacheResult.getAgencyId(),staffOrgPath); //resiChildMap.forEach((key, value) -> value.putAll(resiMainList.get(key))); int sheetNo = n.incrementAndGet(); WriteSheet writeSheet = EasyExcel.writerSheet(sheetNo).build(); System.out.println("===resiChildMap==="+item.getChildGroup().getTableName()+" "+JSON.toJSONString(resiChildMap.values())); excelWriter.fill(new FillWrapper("t"+(sheetNo+1), resiChildMap.values()), writeSheet); } } } excelWriter.finish(); } @NotNull private Map> buildItemMap(CustomerFormResultDTO resiFormItems) { Map> otherSheetItems = new HashMap<>(); //主表的 for (FormItemResult formItemResult : resiFormItems.getItemList()) { if (StringUtils.isBlank(formItemResult.getColumnName())) { continue; } Map itemMap = otherSheetItems.getOrDefault(formItemResult.getTableName(), new HashMap<>()); otherSheetItems.putIfAbsent(formItemResult.getTableName(), itemMap); if (formItemResult.getItemType().equals("checkbox") || formItemResult.getItemType().equals("select") || formItemResult.getItemType().equals("radio")) { itemMap.put(formItemResult.getColumnName().concat(formItemResult.getColumnNum() == 0 ? "" : formItemResult.getColumnNum().toString()), formItemResult); } if (formItemResult.getChildGroup() != null) { itemMap = otherSheetItems.getOrDefault(formItemResult.getChildGroup().getTableName(), new HashMap<>()); otherSheetItems.putIfAbsent(formItemResult.getChildGroup().getTableName(), itemMap); for (FormItemResult2 item2 : formItemResult.getChildGroup().getItemList()) { if (StringUtils.isBlank(item2.getColumnName())) { continue; } if ("checkbox".equals(item2.getItemType()) || "select".equals(item2.getItemType()) || "radio".equals(item2.getItemType())) { itemMap.put(item2.getColumnName().concat(item2.getColumnNum() == 0 ? "" : item2.getColumnNum().toString()), ConvertUtils.sourceToTarget(item2, FormItemResult.class)); } } } } //其他sheet for (FormGroupDTO groupItem : resiFormItems.getGroupList()) { if (groupItem.getItemList() == null) { continue; } Map itemMap = otherSheetItems.getOrDefault(groupItem.getTableName(), new HashMap<>()); otherSheetItems.putIfAbsent(groupItem.getTableName(), itemMap); for (FormItemResult2 formItemResult2 : groupItem.getItemList()) { if (StringUtils.isBlank(formItemResult2.getColumnName())) { continue; } if ("checkbox".equals(formItemResult2.getItemType()) || "select".equals(formItemResult2.getItemType()) || "radio".equals(formItemResult2.getItemType())) { itemMap.put(formItemResult2.getColumnName().concat(formItemResult2.getColumnNum() == 0 ? "" : formItemResult2.getColumnNum().toString()), ConvertUtils.sourceToTarget(formItemResult2, FormItemResult.class)); } } } return otherSheetItems; } private static OutputStream getOutputStream(String fileName, HttpServletResponse response) throws Exception { fileName = URLEncoder.encode(fileName, "UTF-8"); response.setContentType("application/vnd.ms-excel"); response.setCharacterEncoding("utf8"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); response.addHeader("Access-Control-Expose-Headers", "Content-disposition"); return response.getOutputStream(); } /** * excel导入居民基本信息 * * @return */ @NoRepeatSubmit @PostMapping("importExcel") public void importExcelByEasyExcel(@RequestPart("file") MultipartFile file, HttpServletResponse response) { if (file.isEmpty()) { throw new RenException("请上传文件"); } // 校验文件类型 String extension = FilenameUtils.getExtension(file.getOriginalFilename()); if (!"xls".equals(extension) && !"xlsx".equals(extension)) { throw new RenException("文件类型不匹配"); } Path savePath = null; try { String fileName = UUID.randomUUID().toString().concat(".").concat(extension); savePath = IC_RESI_UPLOAD_DIR.resolve(fileName); IOUtils.copy(file.getInputStream(), new FileOutputStream(savePath.toString())); icResiUserImportService.importIcResiInfoFromExcel(savePath.toString(), response); } catch (IOException e) { String errorMsg = ExceptionUtils.getErrorStackTrace(e); log.error("【导入居民信息失败】导入失败:{}", errorMsg); throw new RenException(EpmetErrorCode.SERVER_ERROR.getCode()); } finally { try { Files.delete(savePath); } catch (IOException e) { log.error("【导入居民信息失败】清理上传的文件失败:{}", ExceptionUtils.getErrorStackTrace(e)); } } } @PostMapping("test") public Result>> test(@LoginUser TokenDto tokenDto,@RequestBody DynamicQueryFormDTO formDTO) { formDTO.setCustomerId("45687aa479955f9d06204d415238f7cc"); //formDTO.setCustomerId(tokenDto.getCustomerId()); return new Result>>().ok(icResiUserService.dynamicQuery(formDTO.getCustomerId(), formDTO.getFormCode(), formDTO.getResultTableName(), formDTO.getConditions(), tokenDto.getUserId(),null)); } /** * @param formDTO * @Description 查询个人数据 * @author zxc * @date 2021/11/3 9:21 上午 */ @PostMapping("persondata") public Result personData(@RequestBody PersonDataFormDTO formDTO) { return new Result().ok(icResiUserService.personData(formDTO)); } /** * @param formDTO * @param tokenDto * @Description 根据名字搜索 * @author zxc * @date 2021/11/3 1:42 下午 */ @PostMapping("searchbyname") public Result> searchByName(@RequestBody SearchByNameFormDTO formDTO, @LoginUser TokenDto tokenDto) { ValidatorUtils.validateEntity(formDTO, SearchByNameFormDTO.SearchByNameForm.class); return new Result>().ok(icResiUserService.searchByName(formDTO, tokenDto)); } @NotNull private CustomerFormResultDTO getResiFormAddItems(String customerId) { CustomerFormQueryDTO queryDTO = new CustomerFormQueryDTO(); queryDTO.setFormCode("resi_base_info"); queryDTO.setCustomerId(customerId); Result resultForm = operCustomizeOpenFeignClient.getCustomerForm(queryDTO); if (resultForm == null || !resultForm.success() || resultForm.getData() == null) { throw new RenException(EpmetErrorCode.SERVER_ERROR.getCode()); } System.out.println(JSON.toJSONString(resultForm.getData())); return resultForm.getData(); } @NotNull private List getResiFormAllItems(String customerId) { CustomerFormQueryDTO queryDTO = new CustomerFormQueryDTO(); queryDTO.setFormCode("resi_base_info"); queryDTO.setCustomerId(customerId); Result> resultForm = operCustomizeOpenFeignClient.listItems(queryDTO); if (resultForm == null || !resultForm.success() || resultForm.getData() == null) { throw new RenException(EpmetErrorCode.SERVER_ERROR.getCode()); } System.out.println(JSON.toJSONString(resultForm.getData())); return resultForm.getData(); } /** * @Description 个人信息-家庭关系 * @Param formDTO * @Return {@link Result< OwnerRelationResultDTO>} * @Author zhaoqifeng * @Date 2021/11/5 11:13 */ @PostMapping("ownerrelation") public Result getOwnerRelation(@RequestBody PersonDataFormDTO formDTO) { return new Result().ok(icResiUserService.getOwnerRelation(formDTO.getUserId())); } /** * @Description 获取一栋楼每个房间人员分类的数量 * @Param formDTO * @Return {@link Result< Map< String, Map< String, String>>>} * @Author zhaoqifeng * @Date 2021/11/5 15:10 */ @PostMapping("categorycount") public Result>> getHomeUserCategoryCount(@RequestBody IcResiUserDTO formDTO) { return new Result>>().ok(icResiUserService.getHomeUserCategoryCount(formDTO.getBuildId())); } }