AllocationServiceImpl.java 38 KB

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