AllocationServiceImpl.java 39 KB

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