AllocationServiceImpl.java 42 KB

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