AllocationServiceImpl.java 43 KB

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