AllocationServiceImpl.java 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. package com.imed.costaccount.service.impl;
  2. import cn.hutool.core.collection.CollUtil;
  3. import cn.hutool.core.date.DateTime;
  4. import cn.hutool.core.date.DateUtil;
  5. import cn.hutool.core.util.StrUtil;
  6. import cn.hutool.poi.excel.ExcelWriter;
  7. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  8. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  9. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  10. import com.imed.costaccount.common.constants.NumberConstant;
  11. import com.imed.costaccount.common.exception.CostException;
  12. import com.imed.costaccount.common.util.BeanUtil;
  13. import com.imed.costaccount.common.util.JacksonUtil;
  14. import com.imed.costaccount.common.util.PageUtils;
  15. import com.imed.costaccount.common.util.UserContext;
  16. import com.imed.costaccount.mapper.AllocationMapper;
  17. import com.imed.costaccount.model.*;
  18. import com.imed.costaccount.model.dto.StartDTO;
  19. import com.imed.costaccount.model.vo.*;
  20. import com.imed.costaccount.service.*;
  21. import lombok.extern.slf4j.Slf4j;
  22. import org.apache.poi.ss.usermodel.Sheet;
  23. import org.springframework.stereotype.Service;
  24. import org.springframework.transaction.annotation.Propagation;
  25. import org.springframework.transaction.annotation.Transactional;
  26. import java.math.BigDecimal;
  27. import java.util.*;
  28. import java.util.concurrent.atomic.AtomicReference;
  29. import java.util.stream.Collectors;
  30. @Slf4j
  31. @Service("allocationService")
  32. public class AllocationServiceImpl extends ServiceImpl<AllocationMapper, Allocation> implements AllocationService {
  33. private final CostCostingGroupService costCostingGroupService;
  34. private final CostShareLevelService shareLevelService;
  35. private final ResponsibilityService responsibilityService;
  36. private final CostAccountShareService accountShareService;
  37. private final ShareParamValueService shareParamValueService;
  38. private final CostShareParamService shareParamService;
  39. private final AllocationQueryService allocationQueryService;
  40. public AllocationServiceImpl(CostCostingGroupService costCostingGroupService,
  41. CostShareLevelService shareLevelService,
  42. ResponsibilityService responsibilityService,
  43. CostAccountShareService accountShareService,
  44. ShareParamValueService shareParamValueService, CostShareParamService shareParamService, AllocationQueryService allocationQueryService, AllocationQueryService allocationQueryService1) {
  45. this.costCostingGroupService = costCostingGroupService;
  46. this.shareLevelService = shareLevelService;
  47. this.responsibilityService = responsibilityService;
  48. this.accountShareService = accountShareService;
  49. this.shareParamValueService = shareParamValueService;
  50. this.shareParamService = shareParamService;
  51. this.allocationQueryService = allocationQueryService1;
  52. }
  53. /**
  54. * 分摊成本数据
  55. *
  56. * @param startDTO {@link StartDTO}
  57. * @param hospId 医院id
  58. */
  59. @Override
  60. @Transactional(rollbackFor = Throwable.class, propagation = Propagation.REQUIRED)
  61. public void startAllocation(StartDTO startDTO, Long hospId) {
  62. long timeMillis = System.currentTimeMillis();
  63. // 得到这个月的所有导入的成本数据
  64. List<CostCostingGroup> costingGroups = costCostingGroupService.getByYearAndDate(startDTO.getYear(), startDTO.getMonth(), hospId);
  65. // 没有重新导入
  66. if (costingGroups.isEmpty()) {
  67. throw new CostException("本月分摊参数值数据未导入");
  68. }
  69. Map<String, List<CostCostingGroup>> responsibilityCodeMap = costingGroups.stream().collect(Collectors.groupingBy(CostCostingGroup::getResponsibilityCode));
  70. // 得到这个月导入的成本分摊参数值列表
  71. List<ShareParamValue> shareParamValues = shareParamValueService.getListByYearAndMonth(startDTO.getYear(), startDTO.getMonth(), hospId);
  72. if (shareParamValues.isEmpty()) {
  73. throw new CostException("本月成本分摊参数值未导入");
  74. }
  75. Map<String, List<ShareParamValue>> paramValueRespCodeMap = shareParamValues.stream().collect(Collectors.groupingBy(ShareParamValue::getResponsibilityCode));
  76. // 删除该年月已经分摊过的数据
  77. removeData(startDTO, hospId);
  78. // 得到这个医院所有的分摊层级列表排序
  79. List<CostShareLevelVO> shareLevelVOs = shareLevelService.getAll(hospId);
  80. if (CollUtil.isEmpty(shareLevelVOs)) {
  81. throw new CostException("请先设置医院分摊层级");
  82. }
  83. List<Allocation> allocations = new LinkedList<>();
  84. // key 责任中心代码, value 分摊过来的钱
  85. // Map<String, BigDecimal> costMap = new ConcurrentReaderHashMap();
  86. List<Allocation> costList = new ArrayList();
  87. for (CostShareLevelVO shareLevelVO : shareLevelVOs) {
  88. // 分摊层级id
  89. Long levelId = shareLevelVO.getId();
  90. // 目标分摊层级,可能不存在
  91. String targetLevel = shareLevelVO.getTargetLevel();
  92. if (StrUtil.isBlank(targetLevel)) {
  93. throw new CostException("未设置目标层级");
  94. }
  95. // 计算方式 0是合并计算 1是分开计算
  96. Integer calcType = shareLevelVO.getCalcType();
  97. // 得到该分摊层级下责任中心列表,如果不存在,下一个
  98. List<Responsibility> responsibilities = responsibilityService.getByLevelId(levelId, hospId);
  99. if (responsibilities.isEmpty()) {
  100. continue;
  101. }
  102. // 遍历责任中心得到对应的分摊参数对应
  103. for (Responsibility responsibility : responsibilities) {
  104. String responsibilityCode = responsibility.getResponsibilityCode();
  105. // 得到分摊参数对应记录,不存在,下一个
  106. if (responsibilityCode.equals("123")) {
  107. System.out.println(1);
  108. }
  109. List<CostAccountShare> accountShares = accountShareService.getByResponsibility(responsibilityCode, hospId);
  110. if (accountShares.isEmpty()) {
  111. continue;
  112. }
  113. // 遍历分摊参数对应记录
  114. for (CostAccountShare accountShare : accountShares) {
  115. Long accountShareId = accountShare.getId();
  116. String paramList = accountShare.getParamList();
  117. List<AccountShareVO> accountShareVOs = JacksonUtil.str2ObjList(paramList, List.class, AccountShareVO.class);
  118. // 如果分摊比例未设置直接报错
  119. if (StrUtil.isBlank(paramList)) {
  120. throw new CostException("责任中心:" + accountShare.getResponsibilityName() + ";会计中心为:" + accountShare.getAccountingNames() + ";未设置分摊参数比例");
  121. }
  122. List<CostCostingGroup> groups = responsibilityCodeMap.get(responsibilityCode);
  123. if (CollUtil.isEmpty(groups)) {
  124. continue;
  125. }
  126. // 计算本次分摊的钱
  127. BigDecimal totalAmount = this.getCostAmount(accountShare, calcType, responsibilityCodeMap, costList);
  128. if (totalAmount.equals(BigDecimal.ZERO)) {
  129. continue;
  130. }
  131. // 相关的分摊参数比例
  132. for (AccountShareVO accountShareVO : accountShareVOs) {
  133. String paramCode = accountShareVO.getShareParamCode();
  134. String shareParamPopout = accountShareVO.getShareParamPopout();
  135. BigDecimal rate = new BigDecimal("1");
  136. if (!"100".equals(shareParamPopout)) {
  137. rate = new BigDecimal("0." + shareParamPopout);
  138. }
  139. // 本次的分摊比例计算
  140. BigDecimal thisAmount = rate.multiply(totalAmount);
  141. // 得到目标层级责任中心列表
  142. List<Responsibility> targetResponsibilities = this.getTargetResponsibility(targetLevel, hospId, shareLevelVO.getLeverSort());
  143. if (targetResponsibilities.isEmpty()) {
  144. throw new CostException("找不到目标责任中心");
  145. }
  146. // 目标责任中心得到对应
  147. List<ShareParamValue> targetShareParmValue = getTarget(targetResponsibilities, accountShareVO, paramValueRespCodeMap);
  148. if (CollUtil.isEmpty(targetResponsibilities)) {
  149. throw new CostException("找不到目标责任中心对应的分摊参数值");
  150. }
  151. // 分母
  152. BigDecimal reduce = targetShareParmValue.stream().map(ShareParamValue::getValueNum).reduce(BigDecimal.ZERO, BigDecimal::add);
  153. for (ShareParamValue paramValue : targetShareParmValue) {
  154. // 分子
  155. BigDecimal numerator = paramValue.getValueNum();
  156. BigDecimal targetAmount = thisAmount.multiply(numerator).divide(reduce, 4);
  157. Allocation targetAllocation = new Allocation();
  158. String valueResponsibilityCode = paramValue.getResponsibilityCode();
  159. String targetRespName = responsibilityService.getByCode(valueResponsibilityCode, hospId);
  160. String shareParamName = shareParamService.getByCode(paramValue.getShareParamCode(), hospId);
  161. targetAllocation.setDateMonth(startDTO.getMonth()).setDateYear(startDTO.getYear()).setLevelSort(shareLevelVO.getLeverSort())
  162. .setLevelName(shareLevelVO.getShareName()).setHospId(hospId).setResponsibilityCode(responsibility.getResponsibilityCode())
  163. .setResponsibilityName(responsibility.getResponsibilityName()).setAccountShareId(accountShareId).setAmount(targetAmount)
  164. .setCreateTime(timeMillis).setTargetResponsibilityCode(valueResponsibilityCode).setTargetResponsibilityName(targetRespName)
  165. .setShareParamCode(paramValue.getShareParamCode()).setShareParamName(shareParamName).setTotalAmount(totalAmount).setShareParamValueNum(paramValue.getValueNum())
  166. .setShareParamRate(numerator.divide(reduce, 4))
  167. ;
  168. // todo 目标分摊层级责任中心 就是当前列个表中的责任中心
  169. allocations.add(targetAllocation);
  170. costList.add(targetAllocation);
  171. }
  172. }
  173. }
  174. }
  175. }
  176. this.saveBatch(allocations);
  177. List<Allocation> list = this.list(
  178. new LambdaQueryWrapper<Allocation>()
  179. .eq(Allocation::getHospId, hospId).eq(Allocation::getDateYear, startDTO.getYear()).eq(Allocation::getDateMonth, startDTO.getMonth())
  180. );
  181. if (list.isEmpty()) {
  182. log.error("未分摊到数据......");
  183. return;
  184. }
  185. // 入cost_allocation_query 表 便于后续操作
  186. this.saveAllocationQuery(list, costingGroups, hospId);
  187. }
  188. private void removeData(StartDTO startDTO, Long hospId) {
  189. this.remove(
  190. new LambdaQueryWrapper<Allocation>()
  191. .eq(Allocation::getDateYear, startDTO.getYear())
  192. .eq(Allocation::getDateMonth, startDTO.getMonth())
  193. .eq(Allocation::getHospId, hospId)
  194. );
  195. allocationQueryService.remove(
  196. new LambdaQueryWrapper<AllocationQuery>()
  197. .eq(AllocationQuery::getDateYear, startDTO.getYear())
  198. .eq(AllocationQuery::getDateMonth, startDTO.getMonth())
  199. .eq(AllocationQuery::getHospId, hospId)
  200. );
  201. }
  202. @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
  203. public void saveAllocationQuery(List<Allocation> list, List<CostCostingGroup> costingGroups, Long hospId) {
  204. List<AllocationQuery> saveList = new ArrayList<>();
  205. list.forEach(i -> {
  206. Long accountShareId = i.getAccountShareId();
  207. CostAccountShare byId = accountShareService.getById(accountShareId);
  208. if (Objects.isNull(byId)) {
  209. return;
  210. }
  211. String accountingCodes = byId.getAccountingCodes();
  212. if (StrUtil.isBlank(accountingCodes)) {
  213. return;
  214. }
  215. String accountingNames = byId.getAccountingNames();
  216. String alias = byId.getAlias();
  217. if (StrUtil.isNotBlank(alias)) {
  218. accountingNames = alias;
  219. }
  220. AllocationQuery allocationQuery = new AllocationQuery();
  221. allocationQuery.setDateYear(i.getDateYear()).setDateMonth(i.getDateMonth())
  222. .setHospId(hospId).setResponsibilityCode(i.getResponsibilityCode()).setResponsibilityName(i.getResponsibilityName())
  223. .setOriginId(i.getId()).setOriginType(2L).setAmount(i.getAmount()).setAccountingCode(accountingCodes).setAccountingName(accountingNames)
  224. .setCreateTime(System.currentTimeMillis())
  225. ;
  226. saveList.add(allocationQuery);
  227. });
  228. costingGroups.forEach(i -> {
  229. AllocationQuery allocationQuery = new AllocationQuery();
  230. allocationQuery.setDateYear(i.getDateYear()).setDateMonth(i.getDateMonth())
  231. .setHospId(hospId).setResponsibilityCode(i.getResponsibilityCode()).setResponsibilityName(i.getResponsibilityName())
  232. .setOriginId(i.getId()).setOriginType(2L).setAmount(i.getAmount()).setAccountingCode(i.getAccountCode()).setAccountingName(i.getAccountName())
  233. .setCreateTime(System.currentTimeMillis())
  234. ;
  235. saveList.add(allocationQuery);
  236. });
  237. allocationQueryService.saveBatch(saveList);
  238. }
  239. /**
  240. * 得到目标月成本分摊参数值数据
  241. *
  242. * @param targetResponsibilities
  243. * @param map
  244. * @return
  245. */
  246. private List<ShareParamValue> getTarget(List<Responsibility> targetResponsibilities, AccountShareVO accountShareVO, Map<String, List<ShareParamValue>> map) {
  247. // 目标的责任中心
  248. List<ShareParamValue> shareParamValues = map.entrySet().stream().map(Map.Entry::getValue).flatMap(Collection::stream).collect(Collectors.toList());
  249. List<String> originRespCodes = targetResponsibilities.stream().map(Responsibility::getResponsibilityCode).collect(Collectors.toList());
  250. return shareParamValues.stream().filter(j -> originRespCodes.contains(j.getResponsibilityCode()))
  251. .filter(i -> i.getShareParamCode().equals(accountShareVO.getShareParamCode())).collect(Collectors.toList());
  252. }
  253. /**
  254. * 计算本次的成本金额
  255. *
  256. * @return
  257. */
  258. private BigDecimal getCostAmount(CostAccountShare accountShare, Integer calcType, Map<String, List<CostCostingGroup>> map, List<Allocation> costList) {
  259. // 是否包含分摊成本 0不包含 1 包含
  260. Integer isShareCost = accountShare.getIsShareCost();
  261. String accountingCodes = accountShare.getAccountingCodes();
  262. String responsibilityCode = accountShare.getResponsibilityCode();
  263. List<CostCostingGroup> costingGroups = map.get(responsibilityCode);
  264. if (CollUtil.isEmpty(costingGroups)) {
  265. return BigDecimal.ZERO;
  266. }
  267. // 计算方式 0是合并计算 1是分开计算
  268. BigDecimal costAmount = BigDecimal.ZERO;
  269. List<Allocation> all = new ArrayList<>();
  270. if (!costList.isEmpty()) {
  271. all = costList.stream().filter(i -> i.getTargetResponsibilityCode().equals(responsibilityCode)).collect(Collectors.toList());
  272. // Stream<Allocation> allocationStream = costList.stream().filter(i -> i.getTargetResponsibilityCode().equals(responsibilityCode));
  273. // if (Objects.nonNull(allocationStream)) {
  274. // all = allocationStream.collect(Collectors.toList());
  275. // }
  276. }
  277. if (calcType == 0) {
  278. costAmount = costingGroups.stream().map(CostCostingGroup::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
  279. if (!all.isEmpty()) {
  280. BigDecimal bigDecimal = all.stream()
  281. .map(Allocation::getAmount)
  282. .reduce(BigDecimal.ZERO, BigDecimal::add);
  283. if (Objects.nonNull(bigDecimal)) {
  284. costAmount = costAmount.add(bigDecimal);
  285. }
  286. }
  287. } else {
  288. if (StrUtil.isBlank(accountingCodes)) {
  289. return BigDecimal.ZERO;
  290. }
  291. ArrayList<String> accountCodes = CollUtil.newArrayList(accountingCodes.split(StrUtil.COMMA));
  292. List<CostCostingGroup> costGroups = costingGroups.stream().filter(i -> accountCodes.contains(i.getAccountCode())).collect(Collectors.toList());
  293. costAmount = costGroups.stream().map(CostCostingGroup::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
  294. if (isShareCost == 1) {
  295. if (!all.isEmpty()) {
  296. BigDecimal bigDecimal = all.stream()
  297. .map(Allocation::getAmount)
  298. .reduce(BigDecimal.ZERO, BigDecimal::add);
  299. if (Objects.nonNull(bigDecimal)) {
  300. costAmount = costAmount.add(bigDecimal);
  301. }
  302. }
  303. }
  304. }
  305. return costAmount;
  306. }
  307. /**
  308. * 通过目标层级获取目标责任中心
  309. *
  310. * @param targetLevel 目标层级 2,3,4
  311. * @param leverSort
  312. * @return List
  313. */
  314. private List<Responsibility> getTargetResponsibility(String targetLevel, Long hospId, Integer leverSort) {
  315. ArrayList<String> targetLevelList = CollUtil.newArrayList(StrUtil.split(targetLevel, StrUtil.COMMA));
  316. if (targetLevelList.size() == 1) {
  317. if (leverSort.equals(Integer.parseInt(targetLevelList.get(0)))) {
  318. return new ArrayList<>();
  319. }
  320. }
  321. List<CostShareLevel> shareLevels = shareLevelService.getListByLevelSort(targetLevelList, hospId);
  322. if (shareLevels.isEmpty()) {
  323. throw new CostException("请重新设置分摊层级");
  324. }
  325. List<Long> shareLevelIds = shareLevels.stream().map(CostShareLevel::getId).collect(Collectors.toList());
  326. return responsibilityService.getByLevelIds(shareLevelIds, hospId);
  327. }
  328. /**
  329. * 分摊后查询列表
  330. *
  331. * @param year 年月 (yyyy-MM-dd)
  332. * @param responsibilityCode 责任中心代码
  333. * @param current 当前页
  334. * @param pageSize 当前页展示的数据大小
  335. * @param hospId 医院id
  336. * @return PageUtils
  337. */
  338. @Override
  339. public PageUtils queryAfterAllocation(String year, String responsibilityCode, Integer current, Integer pageSize, Long hospId) {
  340. Integer dateYear = null;
  341. Integer dateMonth = null;
  342. if (StrUtil.isNotBlank(year)) {
  343. DateTime dateTime = DateUtil.parseDate(year);
  344. dateYear = DateUtil.year(dateTime);
  345. dateMonth = DateUtil.month(dateTime) + 1;
  346. }
  347. Integer startIndex = (current - 1) * pageSize;
  348. List<AfterAllocationVO> list = baseMapper.queryAfterAllocationList(dateYear, dateMonth, responsibilityCode, startIndex, pageSize, hospId);
  349. int totalCount = baseMapper.queryAfterAllocationListCount(dateYear, dateMonth, responsibilityCode, hospId);
  350. BigDecimal sum = baseMapper.queryAfterAllocationListSum(dateYear, dateMonth, responsibilityCode, hospId);
  351. return new PageUtils(list, totalCount, pageSize, current, sum);
  352. }
  353. /**
  354. * 分摊报表导出
  355. *
  356. * @param writer {@link ExcelWriter}
  357. * @param levelSort 分摊层级 就是第几次分摊
  358. * @param sheet 报表
  359. * @param year 年
  360. * @param month 月
  361. * @return
  362. */
  363. @Override
  364. public ExcelWriter getShareReportTemplate(ExcelWriter writer, Integer levelSort, Sheet sheet, Integer year, Integer month) {
  365. // 获取数据
  366. List<AllocationReportVO> allocationReportVOList = getAllocationReportVOS(levelSort, year, month);
  367. // 设置导出
  368. Map<String, List<AllocationReportVO>> responsibilityMap = allocationReportVOList.stream().collect(Collectors.groupingBy(AllocationReportVO::getResponsibilityCode));
  369. Map<String, List<AllocationReportVO>> targetResponsibilityMap = allocationReportVOList.stream().collect(Collectors.groupingBy(AllocationReportVO::getTargetResponsibilityCode));
  370. Map<String, AllocationReportVO> allAccMap = allocationReportVOList.stream().collect(Collectors.toMap(k -> k.getResponsibilityName() + k.getAccountName() + k.getTargetResponsibilityName() + k.getShareParamName(), synOne -> synOne));
  371. Map<String, AllocationReportVO> allAliMap = allocationReportVOList.stream().collect(Collectors.toMap(k -> k.getResponsibilityName() + k.getAlias() + k.getTargetResponsibilityName() + k.getShareParamName(), synOne -> synOne));
  372. // 当前责任中心下面有几个会计科目 后面进行合并使用
  373. int numResponsibility;
  374. // // 从第几列开始编写数据
  375. int column = levelSort + 3;
  376. Set<String> keySet = responsibilityMap.keySet();
  377. for (String key : keySet) {
  378. List<AllocationReportVO> allocationReportVOS = responsibilityMap.get(key);
  379. Map<String, AllocationReportVO> linkedHashMap = new LinkedHashMap<>();
  380. allocationReportVOS.forEach(i -> {
  381. String s = i.getResponsibilityCode() + i.getAccountCode();
  382. if (!linkedHashMap.containsKey(s)) {
  383. linkedHashMap.put(s, i);
  384. }
  385. });
  386. numResponsibility = linkedHashMap.size();
  387. if (numResponsibility >= NumberConstant.TWO) {
  388. Set<String> strings = linkedHashMap.keySet();
  389. for (String s : strings) {
  390. AllocationReportVO allocationReportVO = linkedHashMap.get(s);
  391. if (StrUtil.isBlank(allocationReportVO.getAlias())) {
  392. writer.writeCellValue(column, 0, allocationReportVO.getResponsibilityName());
  393. // 别名不存在
  394. writer.writeCellValue(column, 1, allocationReportVO.getAccountName());
  395. } else {
  396. // 不为空 设置别名
  397. writer.writeCellValue(column, 0, allocationReportVO.getResponsibilityName());
  398. writer.writeCellValue(column, 1, allocationReportVO.getAlias());
  399. }
  400. writer.writeCellValue(column, 2, allocationReportVO.getTotalAmounts());
  401. column++;
  402. }
  403. } else {
  404. // 不需要合并单元格
  405. writer.writeCellValue(column, 0, allocationReportVOS.get(0).getResponsibilityName());
  406. if (StrUtil.isNotBlank(allocationReportVOS.get(0).getAlias())) {
  407. writer.writeCellValue(column, 1, allocationReportVOS.get(0).getAlias());
  408. } else {
  409. writer.writeCellValue(column, 1, allocationReportVOS.get(0).getAccountName());
  410. }
  411. writer.writeCellValue(column, 2, allocationReportVOS.get(0).getTotalAmounts());
  412. column++;
  413. }
  414. }
  415. // 设置单元格合并
  416. for (int j = 1; j < levelSort; j++) {
  417. writer.merge(0, 1, j, j, "第" + j + "次分摊", false);
  418. }
  419. // 目标责任集合
  420. writer.passCurrentRow();
  421. // 从第三行开始
  422. int num = 3;
  423. Set<String> targetSet = targetResponsibilityMap.keySet();
  424. for (String target : targetSet) {
  425. List<AllocationReportVO> allocationReportVOS = targetResponsibilityMap.get(target);
  426. Map<String, AllocationReportVO> linkedHashMap = new LinkedHashMap<>();
  427. allocationReportVOS.forEach(i -> {
  428. String s = i.getTargetResponsibilityCode() + i.getShareParamName();
  429. if (!linkedHashMap.containsKey(s)) {
  430. linkedHashMap.put(s, i);
  431. }
  432. });
  433. int shareParamSize = linkedHashMap.size();
  434. if (shareParamSize >= NumberConstant.TWO) {
  435. // 责任中心
  436. AllocationReportVO costCostingVO = allocationReportVOS.get(0);
  437. // 设置第几次分摊的值
  438. for (int k = 0; k < levelSort - 1; k++) {
  439. writer.merge(num, num + shareParamSize - 1, k + 1, k + 1, costCostingVO.getTargetShareMoneys().get(k), false);
  440. }
  441. // 设置对应的分摊参数值
  442. Set<String> strings = linkedHashMap.keySet();
  443. for (String s : strings) {
  444. AllocationReportVO allocationReportVO = linkedHashMap.get(s);
  445. writer.writeCellValue(0, num, allocationReportVO.getTargetResponsibilityName());
  446. writer.writeCellValue(levelSort, num, allocationReportVO.getShareParamName());
  447. writer.writeCellValue(levelSort + 1, num, allocationReportVO.getShareParamValueNums());
  448. writer.writeCellValue(levelSort + 2, num, allocationReportVO.getShareParamRates());
  449. for (int m = levelSort + 3; m < column; m++) {
  450. // x是m y是num
  451. // 获取当前这一列对应的责任中心 以及会计科目
  452. // 第一行责任中心
  453. String responsibilityName = sheet.getRow(0).getCell(m).getStringCellValue();
  454. // 第二行的会计科目或者
  455. String accountNameOrAlias = sheet.getRow(1).getCell(m).getStringCellValue();
  456. // 这一行的目标责任中心
  457. String otherResponsibilityName = sheet.getRow(num).getCell(0).getStringCellValue();
  458. // 分摊参数
  459. String shareName = sheet.getRow(num).getCell(levelSort).getStringCellValue();
  460. String sss = responsibilityName + accountNameOrAlias + otherResponsibilityName + shareName;
  461. AllocationReportVO vo = allAliMap.get(sss);
  462. AllocationReportVO allocationReportVO2 = allAccMap.get(responsibilityName + accountNameOrAlias + otherResponsibilityName + shareName);
  463. AllocationReportVO allocationReportVO3 = allAliMap.get(responsibilityName + accountNameOrAlias + otherResponsibilityName + shareName);
  464. if (Objects.nonNull(allocationReportVO2)) {
  465. writer.writeCellValue(m, num, allocationReportVO2.getAmounts());
  466. } else if (Objects.nonNull(allocationReportVO3)) {
  467. writer.writeCellValue(m, num, allocationReportVO3.getAmounts());
  468. } else {
  469. writer.writeCellValue(m, num, 0);
  470. }
  471. }
  472. num++;
  473. }
  474. }
  475. if (shareParamSize < NumberConstant.TWO) {
  476. writer.writeCellValue(0, num, allocationReportVOS.get(0).getTargetResponsibilityName());
  477. for (int k = 0; k < levelSort - 1; k++) {
  478. writer.writeCellValue(k + 1, num, allocationReportVOS.get(0).getTargetShareMoneys().get(k));
  479. }
  480. writer.writeCellValue(levelSort, num, allocationReportVOS.get(0).getShareParamName());
  481. writer.writeCellValue(levelSort + 1, num, allocationReportVOS.get(0).getShareParamValueNums());
  482. writer.writeCellValue(levelSort + 2, num, allocationReportVOS.get(0).getShareParamRates());
  483. for (int m = levelSort + 4; m < column; m++) {
  484. // x是m y是num
  485. // 获取当前这一列对应的责任中心 以及会计科目
  486. // 第一行责任中心
  487. String responsibilityName = sheet.getRow(0).getCell(m).getStringCellValue();
  488. // 第二行的会计科目或者
  489. String accountNameOrAlias = sheet.getRow(1).getCell(m).getStringCellValue();
  490. // 这一行的目标责任中心
  491. String otherResponsibilityName = sheet.getRow(num).getCell(0).getStringCellValue();
  492. // 分摊参数
  493. String shareName = sheet.getRow(num).getCell(levelSort).getStringCellValue();
  494. AllocationReportVO allocationReportVO2 = allAccMap.get(responsibilityName + accountNameOrAlias + otherResponsibilityName + shareName);
  495. AllocationReportVO allocationReportVO3 = allAliMap.get(responsibilityName + accountNameOrAlias + otherResponsibilityName + shareName);
  496. if (Objects.nonNull(allocationReportVO2)) {
  497. writer.writeCellValue(m, num, allocationReportVO2.getAmounts());
  498. } else if (Objects.nonNull(allocationReportVO3)) {
  499. writer.writeCellValue(m, num, allocationReportVO3.getAmounts());
  500. } else {
  501. writer.writeCellValue(m, num, 0);
  502. }
  503. }
  504. num++;
  505. }
  506. }
  507. for (int i = 0; i < 30; i++) {
  508. // 调整每一列宽度
  509. sheet.autoSizeColumn((short) i);
  510. // 解决自动设置列宽中文失效的问题
  511. sheet.setColumnWidth(i, sheet.getColumnWidth(i) * 14 / 10);
  512. }
  513. return writer;
  514. }
  515. /**
  516. * 查询数据
  517. *
  518. * @param levelSort
  519. * @param year
  520. * @param month
  521. * @return
  522. */
  523. private List<AllocationReportVO> getAllocationReportVOS(Integer levelSort, Integer year, Integer month) {
  524. Long hospId = UserContext.getHospId();
  525. if (Objects.isNull(levelSort) || Objects.isNull(year) || Objects.isNull(month)) {
  526. throw new CostException(500, "参数异常");
  527. }
  528. List<Allocation> allocationList = baseMapper.selectList(new QueryWrapper<Allocation>().lambda()
  529. .eq(Allocation::getHospId, hospId).eq(Allocation::getLevelSort, levelSort).eq(Allocation::getDateYear, year)
  530. .eq(Allocation::getDateMonth, month));
  531. // 处理第几次分摊计算值
  532. List<Allocation> allocations = baseMapper.selectList(new QueryWrapper<Allocation>().lambda()
  533. .eq(Allocation::getHospId, hospId).eq(Allocation::getDateYear, year)
  534. .eq(Allocation::getDateMonth, month));
  535. Map<String, List<Allocation>> accrepMap = allocations.stream().collect(Collectors.groupingBy(k -> k.getLevelSort() + "cost" + k.getResponsibilityCode()));
  536. LinkedList<String> shareMoney = new LinkedList<>();
  537. List<CostAccountShare> costAccountShareList = accountShareService.list(new QueryWrapper<CostAccountShare>().lambda()
  538. .eq(CostAccountShare::getHospId, hospId));
  539. Map<Long, CostAccountShare> accountShareMap = costAccountShareList.stream().collect(Collectors.toMap(CostAccountShare::getId, synOne -> synOne));
  540. List<AllocationReportVO> allocationReportVOList = BeanUtil.convertList(allocationList, AllocationReportVO.class);
  541. allocationReportVOList.forEach(i -> {
  542. Long accountShareId = i.getAccountShareId();
  543. CostAccountShare costAccountShare = accountShareMap.get(accountShareId);
  544. if (Objects.isNull(costAccountShare)) {
  545. throw new CostException(500, "成本参数参数设置对应不存在");
  546. }
  547. i.setAccountCode(costAccountShare.getAccountingCodes());
  548. i.setAccountName(costAccountShare.getAccountingNames());
  549. i.setAlias(costAccountShare.getAlias());
  550. if (levelSort > 1) {
  551. for (int j = 1; j < levelSort; j++) {
  552. AtomicReference<BigDecimal> money = new AtomicReference<>(new BigDecimal("0.0000"));
  553. List<Allocation> allocations1 = accrepMap.get(j + "cost" + i.getResponsibilityCode());
  554. if (CollUtil.isNotEmpty(allocations1)) {
  555. allocations1.forEach(m -> {
  556. money.updateAndGet(v -> v.add(m.getAmount()));
  557. shareMoney.add(month.toString());
  558. });
  559. } else {
  560. // TODO 封装测试数据
  561. shareMoney.add("1000");
  562. }
  563. }
  564. }
  565. i.setTargetShareMoneys(shareMoney);
  566. // 设置字符串类型数据
  567. i.setTotalAmounts(i.getTotalAmount().toString());
  568. i.setShareParamValueNums(i.getShareParamValueNum().toString());
  569. i.setShareParamRates(i.getShareParamRate().toString());
  570. i.setAmounts(i.getAmount().toString());
  571. });
  572. return allocationReportVOList;
  573. }
  574. /**
  575. * 分摊后报表
  576. *
  577. * @param year 年月(yyyy-MM-dd)
  578. * @param responsibilityCode 责任中心代码
  579. * @param hospId 医院id
  580. * @return List
  581. */
  582. @Override
  583. public CollectDataFormVO queryAfterAllocationForm(String year, String responsibilityCode, Long hospId) {
  584. DateTime dateTime = DateUtil.parseDate(year);
  585. int dateYear = DateUtil.year(dateTime);
  586. int month = DateUtil.month(dateTime) + 1;
  587. List<CodeAndNameVO> responsibilityCodeAndNames = allocationQueryService.getRespCodeAndName(hospId, dateYear, month);
  588. List<CodeAndNameVO> accountCodeAndNames = allocationQueryService.getAccountCodeAndName(hospId, dateYear, month);
  589. // todo 校验两个List是否为空
  590. // 填充
  591. responsibilityCodeAndNames.add(0, new CodeAndNameVO("#", "#"));
  592. responsibilityCodeAndNames.add(responsibilityCodeAndNames.size(), new CodeAndNameVO("合计", "合计"));
  593. List<String> titleData = responsibilityCodeAndNames.stream().map(CodeAndNameVO::getName).collect(Collectors.toList());
  594. List<String> respCodes = responsibilityCodeAndNames.stream().map(CodeAndNameVO::getCode).collect(Collectors.toList());
  595. Map<Integer, String> titleMap = new HashMap<>();
  596. for (int i = 0; i < titleData.size(); i++) {
  597. titleMap.put(i + 1, titleData.get(i));
  598. }
  599. List<Map<Integer, Object>> realDatas = new ArrayList<>();
  600. List<String> accountCodes = accountCodeAndNames.stream().map(CodeAndNameVO::getCode).collect(Collectors.toList());
  601. for (CodeAndNameVO account : accountCodeAndNames) {
  602. Map<Integer, Object> map = new HashMap<>();
  603. for (int i = 0; i < responsibilityCodeAndNames.size(); i++) {
  604. if (i == 0) {
  605. map.put(i + 1, account.getName());
  606. continue;
  607. } else if (i == responsibilityCodeAndNames.size() - 1) {
  608. // todo 计算最右侧合计的钱
  609. BigDecimal amount = allocationQueryService.getTotalByAccountAndResps(hospId, dateYear, month, account.getCode(), respCodes);
  610. map.put(i + 1, amount);
  611. continue;
  612. }
  613. // TODO: 2021/8/26 计算 中间的钱
  614. BigDecimal amount = allocationQueryService.getTotalByAccountAndRespCode(hospId, dateYear, month, account.getCode(), respCodes.get(i));
  615. map.put(i + 1, amount);
  616. }
  617. realDatas.add(map);
  618. }
  619. // 尾栏计算
  620. Map<Integer, Object> map = new HashMap<>();
  621. for (int i = 0; i < titleData.size(); i++) {
  622. if (i == 0) {
  623. map.put(i + 1, "合计");
  624. continue;
  625. } else if (i == titleData.size() - 1) {
  626. // TODO: 2021/8/26 计算
  627. BigDecimal bigDecimal = allocationQueryService.getTotalMoney(dateYear, month, hospId);
  628. map.put(i + 1, bigDecimal);
  629. continue;
  630. }
  631. BigDecimal bigDecimal = allocationQueryService.getCountByRespAndAccounts(hospId, dateYear, month, responsibilityCodeAndNames.get(i).getCode(), accountCodes);
  632. map.put(i + 1, bigDecimal);
  633. }
  634. return new CollectDataFormVO(titleMap, realDatas, map);
  635. }
  636. /**
  637. * 分摊后报表输出
  638. *
  639. * @param date yyyy-MM-dd
  640. * @param hospId 医院id
  641. * @return List
  642. */
  643. @Override
  644. public List<AfterAllocationFormVO> afterAllocationFormList(String date, Long hospId) {
  645. DateTime parse = DateUtil.parse(date);
  646. int year = DateUtil.year(parse);
  647. int month = DateUtil.month(parse) + 1;
  648. // 得到这个月的分摊过的分摊层级
  649. List<Allocation> list = baseMapper.getAllSortLevel(hospId, year, month);
  650. // list.
  651. List<AfterAllocationFormVO> vos = list.stream().map(i -> {
  652. AfterAllocationFormVO vo = new AfterAllocationFormVO();
  653. vo.setId(i.getId());
  654. vo.setYear(i.getDateYear());
  655. vo.setMonth(i.getDateMonth());
  656. vo.setShareLevel(i.getLevelSort());
  657. vo.setShareReportName(i.getShareParamName() + "分摊");
  658. vo.setShareTime(DateUtil.date(i.getCreateTime()));
  659. return vo;
  660. }).collect(Collectors.toList());
  661. return vos;
  662. }
  663. }