package com.tofly.feesapi.sfgl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.tofly.feesapi.bmgl.entity.*;
import com.tofly.feesapi.bmgl.service.*;
import com.tofly.feesapi.cbgl.entity.dto.ZcbcssltjDto;
import com.tofly.feesapi.cbgl.entity.vo.YyCblrSelect;
import com.tofly.feesapi.common.NumberHelper;
import com.tofly.common.core.util.StringUtil;
import com.tofly.feesapi.bjgl.entity.YhCbkxx;
import com.tofly.feesapi.bjgl.service.YhCbkxxService;
import com.tofly.feesapi.cbgl.entity.YyCblr;
import com.tofly.feesapi.cbgl.service.YyCblrService;
import com.tofly.feesapi.common.constant.*;
import com.tofly.feesapi.common.dbhelper.DbHelper;
import com.tofly.feesapi.common.dzfp.InvoiceService;
import com.tofly.feesapi.common.core.dto.Order;
import com.tofly.feesapi.common.core.dto.PageDto;
import com.tofly.feesapi.common.core.vo.PageResult;
import com.tofly.feesapi.common.enums.BcFylxEnum;
import com.tofly.feesapi.common.enums.BglxEnum;
import com.tofly.feesapi.common.enums.ChargeTypeEnum;
import com.tofly.feesapi.common.enums.PjlxEnum;
import com.tofly.feesapi.common.exception.FeesErrorCode;
import com.tofly.feesapi.common.exception.FeesException;
import com.tofly.feesapi.common.util.CommSearchParams;
import com.tofly.feesapi.common.util.GuidGenerator;
import com.tofly.feesapi.common.util.ToolsUtils;
import com.tofly.feesapi.common.znj.ZNJResult;
import com.tofly.feesapi.common.znj.ZnjCal;
import com.tofly.feesapi.mxcx.entity.YyBgLog;
import com.tofly.feesapi.mxcx.entity.dto.JkbsltjFilter;
import com.tofly.feesapi.mxcx.entity.dto.LjftjFilter;
import com.tofly.feesapi.mxcx.entity.dto.QftjSeachFilter;
import com.tofly.feesapi.mxcx.entity.dto.YkfpmxtjFilter;
import com.tofly.feesapi.mxcx.entity.vo.*;
import com.tofly.feesapi.mxcx.service.YyBgLogService;

import com.tofly.feesapi.security.auth.ToflyUser;
import com.tofly.feesapi.security.exception.ToflyDeniedException;
import com.tofly.feesapi.security.util.SecurityUtils;
import com.tofly.feesapi.sfgl.entity.YyQfmx;
import com.tofly.feesapi.sfgl.entity.YyQfmxGd;
import com.tofly.feesapi.sfgl.entity.YySspjxx;
import com.tofly.feesapi.sfgl.entity.dto.*;
import com.tofly.feesapi.sfgl.entity.vo.*;
import com.tofly.feesapi.sfgl.mapper.YyQfmxMapper;
import com.tofly.feesapi.sfgl.service.*;
import com.tofly.feesapi.xtgl.entity.Syscommlog;
import com.tofly.feesapi.xtgl.service.ISysGdcsbService;
import com.tofly.feesapi.xtgl.service.ISyscommlogService;
import com.tofly.feesapi.yhgl.entity.YhGroupAccounts;
import com.tofly.feesapi.yhgl.entity.YhKhjbxx;
import com.tofly.feesapi.yhgl.entity.YyZjzh;
import com.tofly.feesapi.yhgl.entity.dto.YhkhjbxxFilter;
import com.tofly.feesapi.yhgl.entity.vo.YhkhjbxxSelect2;
import com.tofly.feesapi.yhgl.service.IYyZjzhService;
import com.tofly.feesapi.yhgl.service.YhGroupAccountsService;
import com.tofly.feesapi.yhgl.service.YhKhjbxxService;
import com.tofly.feesapi.yhgl.service.YhsjqxService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Clob;
import java.sql.SQLException;
import java.text.Collator;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import static com.tofly.feesapi.common.exception.FeesErrorCode.BUSINESS_ERROR;

@Slf4j
@Service("yyQfmxService")
public class YyQfmxServiceImpl extends ServiceImpl<YyQfmxMapper, YyQfmx> implements YyQfmxService {

    @Autowired
    private YyCblrService cblrService;
    @Autowired
    private BmCbbService cbbService;
    @Autowired
    private YhCbkxxService cbkxxService;
    @Autowired
    private YhKhjbxxService khjbxxService;
    @Autowired
    private BmSjService sjService;
    @Autowired
    private IBmFylxService fylxService;
    @Autowired
    private ISysGdcsbService gdcsbService;

    @Autowired
    private ZnjCal znjCal;
    @Autowired
    private InvoiceService invoiceService;
    @Autowired
    private BmYslxService bmYslxService;
    @Autowired
    private YyBgLogService yyBgLogService;
    @Autowired
    private IBmFylxService bmFylxService;
    @Autowired
    private YhGroupAccountsService yhGroupAccountsService;
    @Autowired
    private ISyscommlogService syscommlogService;
    @Autowired
    private YyQfmxGdService yyQfmxGdService;
    @Autowired
    private IYyZjzhService zjzhService;
    @Autowired
    private YhsjqxService yhsjqxService;
    @Autowired
    private YySspjxxService yySspjxxService;
    @Autowired
    private YyWyjtzService yyWyjtzService;

    @Autowired
    private BmYmjzConfigService ymjzConfigService;
    @Autowired
    private BmDbhysyhService bmDbhysyhService;
    @Autowired
    private PlatformTransactionManager transactionManager;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private TransactionTemplate transactionTemplate;


    @Override
    public void sf() {
        List<BmCbb> cbbs = cbbService.lambdaQuery()
                .select(BmCbb::getSsgs, BmCbb::getSscbpq, BmCbb::getCbbbm)
                .orderByAsc(BmCbb::getSsgs, BmCbb::getSscbpq, BmCbb::getCbbbm)
                .list();

        List<String> cbbbms = cbbs.stream().map(e -> e.getCbbbm()).collect(Collectors.toList());
        CbbSf cbbSf = new CbbSf();
        cbbSf.setCbbs(cbbbms);

        String result = cbbSf(cbbSf);

        Syscommlog syscommlog = new Syscommlog();
        syscommlog.setTablename("yy_qfmx");
        syscommlog.setMstext("自动算费Tasksf");
        syscommlog.setAddate(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss")));
        syscommlog.setRemark(String.format("系统自动算费：%s", result));
        syscommlog.setUserid("3");
        syscommlogService.save(syscommlog);
    }

    @Override
    public PageResult<YyQfmxSelect> getPage(PageDto pageDto, YyQfmxFilter filter, String sfbz, String chbz) {
        List<Order> orders = pageDto.getOrders();
        if (orders.isEmpty()) {
            orders.add(new Order("jsrq", false));
        }
        if (orders.size() > 0) {
            orders = orders.stream().map(item -> {
                if (item.getColumn().equals("yhbh")) {
                    Order order = new Order();
                    order.setColumn("a.yhbh");
                    order.setAsc(item.isAsc());
                    return order;
                }
                return item;
            }).collect(Collectors.toList());
        }
        pageDto.setOrders(orders);
//        if (StringUtil.isNotEmpty(filter.getYhbh())) {
//            List<YyQfmx> list = this.lambdaQuery().eq(YyQfmx::getSfbz, "0").eq(YyQfmx::getChbz, "0").eq(YyQfmx::getSfbc, "0").eq(YyQfmx::getYhbh, filter.getYhbh()).list();
//            if (list.size() > 0) {
//                znjCal.YyQfmxZnj(filter.getYhbh(), list);
//            }
//        }

        PageDto<YyQfmxSelect> page = this.baseMapper.getPageList(pageDto, filter, sfbz, chbz);
        page.getRecords().forEach(e -> {
            if (!"1".equals(e.getFylx()) && !"2".equals(e.getFylx())) {
                e.setYssl(BigDecimal.ZERO);
            }
        });
        return page.toVo();
    }

    @Override
    public Map qfmxbgtj(YyQfmxFilter filter) {
        return this.baseMapper.qfmxbgtj(filter);
    }

    @Override
    public String cbbSf(CbbSf cbbSf) {
        List<String> cbbs = cbbSf.getCbbs();

        if (cbbs == null || cbbs.isEmpty()) {
            throw new FeesException("抄表本编码为空", FeesErrorCode.BUSINESS_ERROR);
        }

        //总分表水量计算
        ZfborZmb("cbb", cbbSf.getCbbs());

        TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
        transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        return transactionTemplate.execute(status -> {
            List<YyCblr> list = cblrService.lambdaQuery()
                    .in(YyCblr::getSscbb, cbbs)
                    .eq(YyCblr::getCbbz, CbbzEnum.已抄表)
                    .eq(YyCblr::getShbz, ShbzEnum.审核通过)
                    .eq(YyCblr::getJsbz, JsbzEnum.未算费)
                    //排除水表用途为4的水表
                    //.notExists("select 1 from yh_cbkxx a where sbyt='4' and cbkid=a.cbkid")
                    //排除子表水表与分表水表
                    .notExists("select 1 from yh_bjfl_fb fb left join yh_bjfl_zb zb on fb.zb_id=zb.id " + "where fb.zb_id<>fb.id and zb.isdisabled='1' and (fb.yhbh||fb.cbkh)=cbkid").ge(YyCblr::getSl, BigDecimal.ZERO).list();
            if (list.isEmpty()) {
                throw new FeesException("可算费用户不存在", FeesErrorCode.BUSINESS_ERROR);
            }

            int cg = sf(list);

            int total = list.size();
            int sb = total - cg;
            return String.format("共%s户可算费用户，算费成功%s户，算费失败%s户", total, cg, sb);
        });
    }

    @Override
    public String yhSf(YhSf yhSf) {
        List<String> cbkids = yhSf.getCbkids();
        if (CollectionUtil.isEmpty(cbkids)) {
            throw new FeesException("抄表卡ID为空", FeesErrorCode.BUSINESS_ERROR);
        }
        //总分表水量计算
        ZfborZmb("cbkid", cbkids);
        TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
        transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        return transactionTemplate.execute(status -> {
            List<YyCblr> list = new ArrayList<>();
            List<List<String>> lists = Lists.partition(cbkids, 1000);
            for (List<String> e : lists) {
                list.addAll(cblrService.lambdaQuery().in(YyCblr::getCbkid, e).list());
            }
            if (list.isEmpty()) {
                throw new FeesException("可算费用户不存在", FeesErrorCode.BUSINESS_ERROR);
            }
            for (YyCblr e : list) {
                if (e.getCbbz() == null || e.getCbbz() == CbbzEnum.未抄表 || e.getSl() == null)
                    throw new FeesException(String.format("未抄表:%s", e.getCbkid()), FeesErrorCode.BUSINESS_ERROR);
                if (e.getShbz() == ShbzEnum.未审核)
                    throw new FeesException(String.format("未审核:%s", e.getCbkid()), FeesErrorCode.BUSINESS_ERROR);
                if (e.getJsbz() == JsbzEnum.已算费)
                    throw new FeesException(String.format("已算费:%s", e.getCbkid()), FeesErrorCode.BUSINESS_ERROR);
            }
            int cg = sf(list);
            return String.format("共%s户可算费用户，算费成功%s户，算费失败%s户", list.size(), cg, list.size() - cg);
        });
    }

    @Override
    @Transactional
    public boolean sfBc(SfBc sfBc) {
        String id = sfBc.getId();
        String fylx = sfBc.getFylx();
        String bz = sfBc.getBz();
        if (StringUtils.isBlank(id)) throw new FeesException("欠费明细ID为空", FeesErrorCode.BUSINESS_ERROR);
        if (StringUtils.isBlank(bz)) throw new FeesException("补差备注ID为空", FeesErrorCode.BUSINESS_ERROR);
        BmFylx bmFylx = fylxService.getById(fylx);
        if (bmFylx == null) throw new FeesException("费用类型不存在", FeesErrorCode.BUSINESS_ERROR);
        if (StringUtils.isBlank(fylx)) throw new FeesException("费用类型为空", FeesErrorCode.BUSINESS_ERROR);
        YyQfmx yyQfmx = this.getById(id);
        if (yyQfmx == null) throw new FeesException("欠费明细不存在", FeesErrorCode.BUSINESS_ERROR);
        String qflsbh = yyQfmx.getQflsbh();
        String sfbc = yyQfmx.getSfbc();
        YyQfmx bcQfmx = new YyQfmx();
        bcQfmx.setQflsbh(qflsbh);
        bcQfmx.setYhbh(yyQfmx.getYhbh());
        bcQfmx.setYhxm(yyQfmx.getYhxm());
        bcQfmx.setCbkh(yyQfmx.getCbkh());
        bcQfmx.setCbkid(yyQfmx.getCbkid());
        bcQfmx.setSsgs(yyQfmx.getSsgs());
        bcQfmx.setSscbpq(yyQfmx.getSscbpq());
        bcQfmx.setSscbb(yyQfmx.getSscbb());
        bcQfmx.setCwrq(yyQfmx.getCwrq());
        bcQfmx.setYsyf(yyQfmx.getYsyf());
        bcQfmx.setFylx(fylx);
        bcQfmx.setFylxmc(bmFylx.getName());

        Date now = new Date();
        bcQfmx.setJsrq(now);
        bcQfmx.setLrrq(now);
        bcQfmx.setCbrq(now);
        bcQfmx.setCbrybm(String.valueOf(SecurityUtils.getUserId()));
        bcQfmx.setCbryxm(SecurityUtils.getUser().getRealName());

        BeanUtils.copyProperties(sfbc, bcQfmx, "id");
        BeanUtils.copyProperties(sfBc.getSfJsJg(), bcQfmx);
        bcQfmx.setSfbc("1");
//        this.lambdaUpdate()
//                .set(YyQfmx::getSfbc, "1")
//                .eq(YyQfmx::getId, id).update();
        return this.save(bcQfmx);
    }

    @Override
    public SfJsJg sfJs(SfJs sfJs) throws Exception {
        String cbkid = sfJs.getCbkid();
        BigDecimal sjsl = sfJs.getSjsl();
        if (cbkid == null) throw new FeesException("抄表卡ID为空", FeesErrorCode.BUSINESS_ERROR);
        List<YhCbkxx> list = cbkxxService.lambdaQuery().eq(YhCbkxx::getCbkid, cbkid).list();
        if (list.isEmpty()) throw new FeesException("抄表卡不存在", FeesErrorCode.BUSINESS_ERROR);
        YhKhjbxx khjbxx = khjbxxService.getById(list.get(0).getYhbh());
        if (StringUtil.isNull(khjbxx)) {
            throw new FeesException("用户信息不存在", FeesErrorCode.BUSINESS_ERROR);
        }
        sjCache();//缓存表价信息（计算前必须）
        zbFbsCache();

        return sfJs0(list.get(0), khjbxx, sjsl, sjsl);
    }

    @Override
    public SfJsJg sfCs(Sfcs sfcs) {
        SfJsJg jsJg = new SfJsJg();
        if (sfcs.getFylx().equals(BcFylxEnum.Ljf.getValue().toString()) || sfcs.getFylx().equals(BcFylxEnum.Wsclf.getValue().toString())) {
            jsJg.setYsje(BigDecimal.valueOf(0.00));
            jsJg.setYssl(BigDecimal.valueOf(0));
            jsJg.setYssf(BigDecimal.valueOf(0.00));
            jsJg.setYswsf(BigDecimal.valueOf(0.00));
            jsJg.setYsljf(BigDecimal.valueOf(0.00));
            jsJg.setBcje(jsJg.getYsje().subtract(sfcs.getYje()));
            jsJg.setBcsl(jsJg.getYssl().subtract(sfcs.getYsl()));
            jsJg.setBcsf(jsJg.getYssf().subtract(sfcs.getYsf()));
            jsJg.setBcwsf(jsJg.getYswsf().subtract(sfcs.getYwsf()));
            jsJg.setBcljf(jsJg.getYsljf().subtract(sfcs.getYljf()));
            jsJg.setBcszyf(jsJg.getYsszyf().subtract(sfcs.getYszyf()));
        } else {
            TreeMap<String, String> slMap = new TreeMap<>();
            if (sfcs.getYbdjbz().equals("1")) {
                slMap.put("L1", String.format("%s_%s", sfcs.getSjbm(), sfcs.getSl()));
                if (StringUtils.isNotEmpty(sfcs.getSjbm1())) {
                    slMap.put("L2", String.format("%s_%s", sfcs.getSjbm1(), sfcs.getSl1()));
                }
                if (StringUtils.isNotEmpty(sfcs.getSjbm2())) {
                    slMap.put("L3", String.format("%s_%s", sfcs.getSjbm2(), sfcs.getSl2()));
                }
            } else {
                slMap.put("L0", String.format("%s_%s", sfcs.getSjbm(), sfcs.getSl()));
            }
            Date now = new Date();
            jsJg.setJsrq(now);
            YhCbkxx cbkxx = cbkxxService.getById(sfcs.getCbkid());
            YhKhjbxx khjbxx = khjbxxService.getById(cbkxx.getYhbh());
            sjCache();//缓存表价信息（计算前必须）
            zbFbsCache();
            Map<String, Object> values = new LinkedHashMap<>();
            slMap.forEach((key, value) -> {
                if (key.equals("L0") || key.equals("L1")) {
                    String sjTag = "";
                    String sjTag2 = "";
                    Map<String, Object> values1 = getValues(value, sfcs.getJtzqljl(), sjTag, sjTag2, cbkxx, khjbxx);
                    values.putAll(values1);

                } else if (key.equals("L2")) {
                    String sjTag = "sj1";
                    String sjTag2 = "1";
                    Map<String, Object> values1 = getValues(value, sfcs.getJtzqljl(), sjTag, sjTag2, cbkxx, khjbxx);
                    values.putAll(values1);

                } else if (key.equals("L3")) {
                    String sjTag = "sj2";
                    String sjTag2 = "2";
                    Map<String, Object> values1 = getValues(value, sfcs.getJtzqljl(), sjTag, sjTag2, cbkxx, khjbxx);
                    values.putAll(values1);
                }
            });

            List<BigDecimal> sls = getMxValues(values, "sl");
            List<BigDecimal> sfs = getMxValues(values, "sf");
            List<BigDecimal> wsfs = getMxValues(values, "wsf");
            List<BigDecimal> ljfs = getMxValues(values, "ljf");
            List<BigDecimal> szyfs = getMxValues(values, "szyf");

            BigDecimal yssl = sls.stream().reduce(BigDecimal.ZERO, (x, y) -> x.add(y));
            BigDecimal yssf = sfs.stream().reduce(BigDecimal.ZERO, (x, y) -> x.add(y));
            BigDecimal yswsf = wsfs.stream().reduce(BigDecimal.ZERO, (x, y) -> x.add(y));
            BigDecimal ysljf = ljfs.stream().reduce(BigDecimal.ZERO, (x, y) -> x.add(y));
            BigDecimal ysszyf = szyfs.stream().reduce(BigDecimal.ZERO, (x, y) -> x.add(y));

            try {
                BigDecimal ljsl = sfcs.getJtzqljl();
                org.apache.commons.beanutils.BeanUtils.populate(jsJg, values);
                CbjsfsEnum cbjsfs = getCbjsfs(slMap, values);//抄表计算方式（0正常单价，1一表多价，2阶梯,3 一表多价含阶梯；用于判断计价类型，处理显示水价）
                jsJg.setCbjsbz(cbjsfs.getValue());
                jsJg.setCbjsfs(cbjsfs.name());
                jsJg.setJtzqljlJsq(ljsl);
                jsJg.setJtzqljl(ljsl == null ? null : ljsl.add(yssl));
                jsJg.setYssl(yssl);
                jsJg.setYssf(yssf);
                jsJg.setYsljf(ysljf);
                jsJg.setYswsf(yswsf);
                jsJg.setYsszyf(ysszyf);
                jsJg.setYsje(yssf.add(ysljf).add(yswsf).add(ysszyf));
                jsJg.setBcsl(jsJg.getYssl().subtract(sfcs.getYsl()));
                jsJg.setBcsf(jsJg.getYssf().subtract(sfcs.getYsf()));
                jsJg.setBcljf(jsJg.getYsljf().subtract(sfcs.getYljf()));
                jsJg.setBcwsf(jsJg.getYswsf().subtract(sfcs.getYwsf()));
                jsJg.setBcszyf(jsJg.getYsszyf().subtract(sfcs.getYszyf()));
                jsJg.setBcje(jsJg.getYsje().subtract(sfcs.getYje()));
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            }
        }
        return jsJg;
    }


    /**
     * 应收统计报表（汇总版）
     */
    @Override
    public List<YyQfmxMonthlyStat> monthlyStatSummary(YyQfmxStatFilter filter) {
        List<YySjStat> list0 = this.baseMapper.sjStat(filter, "", "");
        List<YySjStat> list1 = this.baseMapper.sjStat(filter, "1", "");
        List<YySjStat> list2 = this.baseMapper.sjStat(filter, "2", "");
        //List<YySjStat> list3 = this.baseMapper.sjStat(filter, "3", "");
        BigDecimal bc = this.baseMapper.bcStat(filter) == null ? BigDecimal.ZERO : this.baseMapper.bcStat(filter);
        //BigDecimal znj = this.baseMapper.qtStat(filter, "znj") == null ? BigDecimal.ZERO : this.baseMapper.qtStat(filter, "znj");//违约金
        List<YySjStat> list = new ArrayList<>();
        if ((long) list0.size() != 0) {
            //费用不等于或者水量也不等于零
            list.addAll(list0.stream().filter(i ->
                    !i.getSf().add(i.getLjf()).add(i.getWsf()).add(i.getSzyf())
                            .add(i.getEcjyf()).add(i.getFjf()).add(i.getQtf()).equals(BigDecimal.ZERO) ||
                            !i.getSl().equals(BigDecimal.ZERO)
            ).collect(Collectors.toList()));
        }
        if ((long) list1.size() != 0) {
            list.addAll(list1);
        }
        if ((long) list2.size() != 0) {
            list.addAll(list2);
        }
//        if ((long) list3.size() != 0) {
//            list.addAll(list3);
//        }

        List<BmSj> sjList = getSjMap();

        List<YyQfmxMonthlyStat> result = new ArrayList<>();

        Map<String, List<YySjStat>> sjmxMap = list.stream().filter(
                e -> StringUtils.isNotBlank(e.getSjbm())
                        && !e.getSfbz().equals("4")
        ).collect(Collectors.groupingBy(x -> x.getSjbm()));
        /*不收费费用明细--不显示*/
//        Map<String, List<YySjStat>> sjmxbsfMap = list.stream().filter(
//                e -> StringUtils.isNotBlank(e.getSjbm())
//                        && e.getSfbz().equals("4")
//
//        ).collect(Collectors.groupingBy(x -> x.getSjbm()));
//        if (!sjmxbsfMap.isEmpty()) {
//            for (List<YySjStat> yySjStats : sjmxbsfMap.values()) {
//                BmSj bmsj = sjList.stream().filter(e -> e.getCode().equals(yySjStats.get(0).getSjbm())).findFirst().get();
//                BigDecimal sl = yySjStats.stream().map(YySjStat::getSl).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                BigDecimal sf = yySjStats.stream().map(YySjStat::getSf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                BigDecimal wsf = yySjStats.stream().map(YySjStat::getWsf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                BigDecimal ljf = yySjStats.stream().map(YySjStat::getLjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                BigDecimal szyf = yySjStats.stream().map(YySjStat::getSzyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                BigDecimal bs = yySjStats.stream().map(YySjStat::getBs).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                BigDecimal znj = yySjStats.stream().map(YySjStat::getZnj).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//
//
//                BigDecimal fjf = yySjStats.stream().map(YySjStat::getFjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                BigDecimal ecjyf = yySjStats.stream().map(YySjStat::getEcjyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                BigDecimal qtf = yySjStats.stream().map(YySjStat::getQtf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//
//                result.add(0, new YyQfmxMonthlyStat(null, bmsj.getName(), BigDecimal.ZERO, BigDecimal.ZERO, sl, sf, wsf, ljf, szyf, znj, fjf, ecjyf, qtf, sf.add(wsf).add(ljf).add(szyf).add(fjf).add(ecjyf).add(qtf), bs));
//            }
//        }

        for (BmSj bmsj : sjList) {
            List<YySjStat> sjmxs = sjmxMap.getOrDefault(bmsj.getCode(), new ArrayList<>());
            BigDecimal sl = sjmxs.stream().map(YySjStat::getSl).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal sf = sjmxs.stream().map(YySjStat::getSf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal wsf = sjmxs.stream().map(YySjStat::getWsf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal ljf = sjmxs.stream().map(YySjStat::getLjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal szyf = sjmxs.stream().map(YySjStat::getSzyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal bs = sjmxs.stream().map(YySjStat::getBs).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal znj = sjmxs.stream().map(YySjStat::getZnj).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);


            BigDecimal fjf = sjmxs.stream().map(YySjStat::getFjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal ecjyf = sjmxs.stream().map(YySjStat::getEcjyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal qtf = sjmxs.stream().map(YySjStat::getQtf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);

            if (bmsj.getJtbz().equals("0")) {
                BigDecimal hjyeje = sf.add(wsf).add(ljf).add(szyf).add(fjf).add(ecjyf).add(qtf);
                if (hjyeje.compareTo(BigDecimal.ZERO) != 0 || !sl.equals(BigDecimal.ZERO)) {
                    BigDecimal hjsj = bmsj.getSj().add(bmsj.getWsfdj()).add(bmsj.getSzyfdj());
                    result.add(new YyQfmxMonthlyStat(null, bmsj.getName(), bmsj.getSj(), hjsj, sl, sf, wsf, ljf, szyf, znj, hjyeje, bs, ecjyf, fjf, qtf));
                }
            } else {
                //阶梯费用
                List<YySjStat> list4 = this.baseMapper.sjjtStat(filter, "1", "", bmsj.getCode());
                List<YySjStat> list5 = this.baseMapper.sjjtStat(filter, "2", "", bmsj.getCode());
                List<YySjStat> list6 = this.baseMapper.sjjtStat(filter, "3", "", bmsj.getCode());
                List<YySjStat> jtlist = new ArrayList<>();
                if ((long) list4.size() != 0) {
                    jtlist.addAll(list4);
                }
                if ((long) list5.size() != 0) {
                    jtlist.addAll(list5);
                }
                if ((long) list6.size() != 0) {
                    jtlist.addAll(list6);
                }
                //获取需要收费的阶梯费用明细
                Map<BigDecimal, List<YySjStat>> jtsjmxMap = jtlist.stream()
                        .filter(e -> StringUtils.isNotBlank(e.getSjbm())
                                && !e.getSfbz().equals("4"))
                        .collect(Collectors.groupingBy(x -> x.getSj()));
                //获取需要不收费的阶梯费用明细--不显示
//                List<YySjStat> jtbsfyySjStats = jtlist.stream().filter(
//                        e -> StringUtils.isNotBlank(e.getSjbm())
//                                && e.getSfbz().equals("4")
//                                && e.getSl().compareTo(BigDecimal.ZERO) > 0
//                ).collect(Collectors.toList());
//                if (!jtbsfyySjStats.isEmpty()) {
//                    BigDecimal bsfsl = jtbsfyySjStats.stream().map(YySjStat::getSl).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                    BigDecimal bsfsf = jtbsfyySjStats.stream().map(YySjStat::getSf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                    BigDecimal bsfwsf = jtbsfyySjStats.stream().map(YySjStat::getWsf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                    BigDecimal bsfljf = jtbsfyySjStats.stream().map(YySjStat::getLjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                    BigDecimal bsfszyf = jtbsfyySjStats.stream().map(YySjStat::getSzyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                    BigDecimal bsfbs = jtbsfyySjStats.stream().map(YySjStat::getBs).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                    BigDecimal bsfznj = jtbsfyySjStats.stream().map(YySjStat::getZnj).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//
//                    BigDecimal bsfjf = jtbsfyySjStats.stream().map(YySjStat::getFjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                    BigDecimal bsecjyf = jtbsfyySjStats.stream().map(YySjStat::getEcjyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                    BigDecimal bsqtf = jtbsfyySjStats.stream().map(YySjStat::getQtf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//
//                    result.add(0, new YyQfmxMonthlyStat(null, bmsj.getName(), BigDecimal.ZERO, BigDecimal.ZERO, bsfsl, bsfsf, bsfwsf, bsfljf, bsfszyf, bsfznj, bsfjf, bsecjyf, bsqtf, bsfsf.add(bsfwsf).add(bsfljf).add(bsfszyf).add(bsfjf).add(bsecjyf).add(bsqtf), bsfbs));
//                }

//                List<YySjStat> zeroSjs = jtlist.stream().filter(
//                        e -> StringUtils.isNotBlank(e.getSjbm())
//                                && e.getSj().compareTo(BigDecimal.ZERO) == 0
//                                && e.getSf().add(e.getWsf()).add(e.getLjf()).add(e.getSzyf()).compareTo(BigDecimal.ZERO) != 0
//                                && !e.getSfbz().equals("4")
//
//                ).collect(Collectors.toList());
//                int i = 0;
                for (List<YySjStat> yySjStats : jtsjmxMap.values()) {
                    BigDecimal jtsl = yySjStats.stream().map(YySjStat::getSl).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal jtsf = yySjStats.stream().map(YySjStat::getSf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal jtwsf = yySjStats.stream().map(YySjStat::getWsf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal jtljf = yySjStats.stream().map(YySjStat::getLjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal jtszyf = yySjStats.stream().map(YySjStat::getSzyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal jtbs = yySjStats.stream().map(YySjStat::getBs).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal jtznj = yySjStats.stream().map(YySjStat::getZnj).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);


                    BigDecimal jtfjf = yySjStats.stream().map(YySjStat::getFjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal jtecjyf = yySjStats.stream().map(YySjStat::getEcjyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal jtqtf = yySjStats.stream().map(YySjStat::getQtf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);

                    BigDecimal jthjysje = jtsf.add(jtwsf).add(jtljf).add(jtszyf).add(jtfjf).add(jtecjyf).add(jtqtf);
                    if (jthjysje.compareTo(BigDecimal.ZERO) != 0) {
                        BigDecimal jthjsj = yySjStats.get(0).getSj().add(bmsj.getWsfdj()).add(bmsj.getSzyfdj());
                        if (yySjStats.get(0).getSj().compareTo(BigDecimal.ZERO) <= 0) {
                            jthjsj = BigDecimal.ZERO;
                        }

                        result.add(new YyQfmxMonthlyStat(null, bmsj.getName(), yySjStats.get(0).getSj(), jthjsj, jtsl, jtsf, jtwsf, jtljf, jtszyf, jtznj, jthjysje, jtbs, jtecjyf, jtfjf, jtqtf));
                    }
                    //i++;
                }
            }
        }
        //小计
        if (!result.isEmpty()) {
            BigDecimal sl = result.stream().map(YyQfmxMonthlyStat::getSl).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal sf = result.stream().map(YyQfmxMonthlyStat::getSf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal wsf = result.stream().map(YyQfmxMonthlyStat::getWsf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal ljf = result.stream().map(YyQfmxMonthlyStat::getLjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal szyf = result.stream().map(YyQfmxMonthlyStat::getSzyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal hj = result.stream().map(YyQfmxMonthlyStat::getHj).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal bs = result.stream().map(YyQfmxMonthlyStat::getBs).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal znj = result.stream().map(YyQfmxMonthlyStat::getZnj).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);

            BigDecimal fjf = result.stream().map(YyQfmxMonthlyStat::getFjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal ecjyf = result.stream().map(YyQfmxMonthlyStat::getEcjyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal qtf = result.stream().map(YyQfmxMonthlyStat::getQtf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);

            result.add(new YyQfmxMonthlyStat(null, "小计", BigDecimal.ZERO, BigDecimal.ZERO, sl, sf, wsf, ljf, szyf, znj, hj, bs, ecjyf, fjf, qtf));
        }

        if (bc.compareTo(BigDecimal.ZERO) != 0) {
            result.add(new YyQfmxMonthlyStat(null, "水费补差", BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, bc, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO));
        }
        BigDecimal hjsl = result.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getSl).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal hjsf = result.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getSf).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal hjwsf = result.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getWsf).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal hjljf = result.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getLjf).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal hjszyf = result.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getSzyf).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal zhj = result.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getHj).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal zbs = result.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getBs).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal znj = result.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getZnj).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal hjecjyf = result.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getEcjyf).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal hjfjf = result.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getFjf).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal hjqtf = result.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getQtf).reduce(BigDecimal.ZERO, BigDecimal::add);

        if (zhj.compareTo(BigDecimal.ZERO) != 0) {
            result.add(new YyQfmxMonthlyStat(null, "合计", null, null, hjsl, hjsf, hjwsf, hjljf, hjszyf, znj, zhj, zbs, hjecjyf, hjfjf, hjqtf));
        }
        return result;
    }

    @Override
    public List<YyQfmxSelect> getList(YyQfmxFilter filter, String sfbz, String chbz) {
        /*
         * 高级查询拼接公用方法
         * */
        try {

            filter.setSqlStrWhere(ToolsUtils.getCommSearchList(filter.getCommSearchParams()));
        } catch (Exception e) {
            filter.setSqlStrWhere("");
        }

        if (StringUtil.isNotEmpty(filter.getYhbh())) {
            // 计算违约金
            List<YyQfmx> list = this.lambdaQuery()
                    .eq(YyQfmx::getSfbz, "0")
                    .eq(YyQfmx::getChbz, "0")
                    .eq(YyQfmx::getYhbh, filter.getYhbh())
                    .isNull(YyQfmx::getKhbm)
                    .list();
            if (CollUtil.isNotEmpty(list)) {
                //先计算违约金
                //znjCal.YyQfmxZnj(filter.getYhbh(), list);
                //用户资金账号
                YyZjzh zjzh = zjzhService.getById(filter.getYhbh());
                if (StringUtil.isNotNull(zjzh)) {
                    //再进行自动扣减
                    YyQfmx yyQfmx = list.stream().min(Comparator.comparing(YyQfmx::getCbrq)).orElse(null);
                    if (zjzh.getNbsyje().compareTo(yyQfmx.getYsje().add(yyQfmx.getZnj())) >= 0) {
                        yySspjxxService.yffkj(filter.getYhbh(), zjzh.getNbsyje(), list);
                    }
                }
            }
        }

        // 付费关系组
//        if (StringUtil.isNotEmpty(filter.getFfgxzh())) {
//            List<YyQfmx> list = this.lambdaQuery().eq(YyQfmx::getSfbz, "0").eq(YyQfmx::getChbz, "0")
//                    .eq(YyQfmx::getSfbc, "0")
//                    .apply(String.format("yhbh=" + filter.getYhbh()))
//                    .apply(StringUtil.isNotEmpty(filter.getCwrqStart())
//                                    && StringUtil.isNotEmpty(filter.getCwrqEnd()),
//                            String.format("cwrq BETWEEN '%s' AND '%s'", filter.getCwrqStart(), filter.getCwrqEnd()))
//                    .list();
//            znjCal.YyQfmxZnj(filter.getFfgxzh(), list);
//        }


//        if (StrUtil.isNotEmpty(yhbh)) {
//            if (yhbh.startsWith("D") || yhbh.startsWith("d")) {
//                filter.setKhbm(yhbh);
//            }
//        }
        if (StringUtil.isEmpty(filter.getUserId())) {
            filter.setUserId(SecurityUtils.getUserId().toString());
        }
        List<YyQfmxSelect> dataList = baseMapper.getPageList(filter, sfbz, chbz);
        // 二次加压、附加、消防栓费
        if (CollectionUtil.isNotEmpty(dataList)) {
            dataList.forEach(o -> {
                if (ObjectUtil.isNull(o.getYsecjyf())) {
                    o.setYsecjyf(BigDecimal.ZERO);
                }
                if (ObjectUtil.isNull(o.getYsfjf())) {
                    o.setYsfjf(BigDecimal.ZERO);
                }
                if (ObjectUtil.isNull(o.getYsxfsf())) {
                    o.setYsxfsf(BigDecimal.ZERO);
                }
                if (!"1".equals(o.getFylx()) && !"2".equals(o.getFylx())) {
                    o.setYssl(BigDecimal.ZERO);
                }
            });
        }
        return dataList;
    }

    @Override
    public List<YyQfmxSelect1> getQfList(YyQfmxFilter filter, String sfbz, String chbz) {
        if (StringUtil.isNotEmpty(filter.getFfgxzh())) {
//            List<YyQfmx> list = this.lambdaQuery()
//            .eq(YyQfmx::getSfbz, "0")
//            .eq(YyQfmx::getChbz, "0")
//            .eq(YyQfmx::getSfbc, "0")
//            .apply(String.format("yhbh in (select yhbh from yh_group_accounts " + "where group_id in (select id from yh_group where yhbh='%s' )" + "union " + "select yhbh from yh_group where yhbh='%s')", filter.getFfgxzh(), filter.getFfgxzh())).apply(StringUtil.isNotEmpty(filter.getCwrqStart()) && StringUtil.isNotEmpty(filter.getCwrqEnd()), String.format("cwrq BETWEEN '%s' AND '%s'", filter.getCwrqStart(), filter.getCwrqEnd()))
////                    .apply(String.format("=cwrq(select min(cwrq) from yy_qfmx " +
////                            "where yhbh in (select yhbh from yh_group_accounts " +
////                            "where group_id in (select id from yh_group where yhbh='%s')))", filter.getFfgxzh()))
//                    .list();
//            List<String> yhbhs = list.stream().map(YyQfmx::getYhbh).distinct().collect(Collectors.toList());
//            for (String yhbh : yhbhs) {
//                List<YyQfmx> yhqflist = list.stream().filter(e -> e.getYhbh().equals(yhbh)).collect(Collectors.toList());
//                znjCal.YyQfmxZnj(yhbh, yhqflist);
//            }

        } else {
            throw new FeesException("付费关系组号不能为空", FeesErrorCode.BUSINESS_ERROR);
        }
        return this.baseMapper.getQfList(filter, sfbz, chbz);
    }

    @Override
    public YyQfmxSelectCount getPageList(PageDto pageDto, YyQfmxFilter filter, String sfbz, String chbz) {
        if (StringUtil.isEmpty(filter.getUserId())) {
            filter.setUserId(SecurityUtils.getUserId().toString());
        }

        List<Order> orders = pageDto.getOrders();
        if (orders.size() > 0) {
            orders = orders.stream().map(item -> {
                if (item.getColumn().equals("yhbh")) {
                    Order order = new Order();
                    order.setColumn("a.yhbh");
                    order.setAsc(item.isAsc());
                    return order;
                }
                return item;
            }).collect(Collectors.toList());
        }


        PageDto<YyQfmxSelect> page = null;
        if (filter.getDhkh() != null && filter.getDhkh().equals("0")) {
            pageDto.setOrders(orders);

            page = baseMapper.getPageList(pageDto, filter, sfbz, chbz);
            page.getRecords().forEach(e -> {
                if (!"1".equals(e.getFylx()) && !"2".equals(e.getFylx())) {
                    e.setYssl(BigDecimal.ZERO);
                }
            });
        } else if (filter.getDhkh() != null && filter.getDhkh().equals("1")) {
            pageDto.setOrders(null);
            page = baseMapper.getPageListByKhbm(pageDto, filter, sfbz, chbz);
        }


        YyQfmxSelectCount yyQfmxSelectCount = new YyQfmxSelectCount();
        yyQfmxSelectCount.setList(page.toVo());
        //所有页合计
        YyQfmxSelectCount tempModel = baseMapper.getPageCount(filter, sfbz, chbz);
        if (ObjectUtil.isNotNull(tempModel)) {
            BeanUtils.copyProperties(tempModel, yyQfmxSelectCount);
            yyQfmxSelectCount.setList(page.toVo());
            List<YyQfmxSelect> records = page.getRecords();
            //当前页合计
            yyQfmxSelectCount.setYssf(records.stream().filter(o -> ObjUtil.isNotNull(o.getYssf()))
                    .map(YyQfmxSelect::getYssf).reduce(BigDecimal.ZERO, BigDecimal::add));
            yyQfmxSelectCount.setYssl(records.stream().filter(o -> ObjUtil.isNotNull(o.getYssl()) &&
                            ObjUtil.isNotNull(o.getYssf()) &&
                            o.getYssf().compareTo(BigDecimal.ZERO) > 0)
                    .map(YyQfmxSelect::getYssl).reduce(BigDecimal.ZERO, BigDecimal::add));
            yyQfmxSelectCount.setYswsf(records.stream().filter(o -> ObjUtil.isNotNull(o.getYswsf()))
                    .map(YyQfmxSelect::getYswsf).reduce(BigDecimal.ZERO, BigDecimal::add));
            yyQfmxSelectCount.setYsljf(records.stream().filter(o -> ObjUtil.isNotNull(o.getYsljf()))
                    .map(YyQfmxSelect::getYsljf).reduce(BigDecimal.ZERO, BigDecimal::add));
            yyQfmxSelectCount.setYsszyf(records.stream()
                    .filter(o -> ObjUtil.isNotNull(o.getYsszyf())).map(YyQfmxSelect::getYsszyf).reduce(BigDecimal.ZERO, BigDecimal::add));
            yyQfmxSelectCount.setYsecjyf(records.stream().filter(o -> ObjUtil.isNotNull(o.getYsecjyf()))
                    .map(YyQfmxSelect::getYsecjyf).reduce(BigDecimal.ZERO, BigDecimal::add));
            yyQfmxSelectCount.setYsfjf(records.stream()
                    .filter(o -> ObjUtil.isNotNull(o.getYsfjf())).map(YyQfmxSelect::getYsfjf).reduce(BigDecimal.ZERO, BigDecimal::add));
            yyQfmxSelectCount.setYsqtf(records.stream().filter(o -> ObjUtil.isNotNull(o.getYsqt()))
                    .map(YyQfmxSelect::getYsqt).reduce(BigDecimal.ZERO, BigDecimal::add));
            yyQfmxSelectCount.setZnj(records.stream().filter(o -> ObjUtil.isNotNull(o.getZnj()))
                    .map(YyQfmxSelect::getZnj).reduce(BigDecimal.ZERO, BigDecimal::add));
            yyQfmxSelectCount.setYsje(records.stream().filter(o -> ObjUtil.isNotNull(o.getYsje()))
                    .map(YyQfmxSelect::getYsje).reduce(BigDecimal.ZERO, BigDecimal::add));
            yyQfmxSelectCount.setYszje(records.stream().filter(o -> ObjUtil.isNotNull(o.getYszje()))
                    .map(YyQfmxSelect::getYszje).reduce(BigDecimal.ZERO, BigDecimal::add));
        }
        return yyQfmxSelectCount;
    }


    @Override
    public List<YyQfmxMonthlyStat> monthlyStat(YyQfmxStatFilter filter) {
        String cwrqorysyf = "cwrq,";
        if (StringUtil.isNotEmpty(filter.getJyType()) ||
                (StringUtil.isNotEmpty(filter.getCxlx()) && filter.getCxlx().equals("1"))) {
            cwrqorysyf = "ysyf,";
        }
        List<YySjStat> list0 = this.baseMapper.sjStat(filter, "", cwrqorysyf);
        List<YySjStat> list1 = this.baseMapper.sjStat(filter, "1", cwrqorysyf);
        List<YySjStat> list2 = this.baseMapper.sjStat(filter, "2", cwrqorysyf);
        //List<YySjStat> list3 = this.baseMapper.sjStat(filter, "3", cwrqorysyf);

        List<YySjStat> list = new ArrayList<>();
        if (list0.size() != 0) {
            //费用不等于并且水量也不等于零
            list.addAll(list0.stream().filter(i ->
                    !i.getSf().add(i.getLjf()).add(i.getWsf()).add(i.getSzyf())
                            .add(i.getEcjyf()).add(i.getFjf()).add(i.getQtf()).equals(BigDecimal.ZERO) ||
                            !i.getSl().equals(BigDecimal.ZERO)).collect(Collectors.toList()));
        }
        if (list1.size() != 0) {
            list.addAll(list1);
        }
        if (list2.size() != 0) {
            list.addAll(list2);
        }
//        if (list3.size() != 0) {
//            list.addAll(list3);
//        }

        //阶梯费用
        List<YySjStat> list4 = this.baseMapper.sjjtStat(filter, "1", cwrqorysyf, "");
        List<YySjStat> list5 = this.baseMapper.sjjtStat(filter, "2", cwrqorysyf, "");
        List<YySjStat> list6 = this.baseMapper.sjjtStat(filter, "3", cwrqorysyf, "");
        List<YySjStat> jtlist = new ArrayList<>();
        if (list4.size() != 0) {
            jtlist.addAll(list4);
        }
        if (list5.size() != 0) {
            jtlist.addAll(list5);
        }
        if (list6.size() != 0) {
            jtlist.addAll(list6);
        }

        //List<YyQfmxMonthlyStatCwrq> resultlist = new ArrayList<>();
        Map<String, List<YySjStat>> cwrqMap = new HashMap<>();
        Map<String, List<YySjStat>> cwrqjtMap = new HashMap<>();

        List<String> cwrqList = new ArrayList<>();

        if (StringUtil.isNotEmpty(filter.getJyType())) {
            //根据用水月份分类

            //非阶梯水价费用
            cwrqMap = list.stream().filter(e -> StringUtils.isNotBlank(e.getYsyf()))
                    .collect(Collectors.groupingBy(YySjStat::getYsyf, LinkedHashMap::new,  // 指定有序 Map
                            Collectors.toList()));
            //阶梯水价费用
            cwrqjtMap = jtlist.stream().filter(e -> StringUtils.isNotBlank(e.getYsyf()))
                    .collect(Collectors.groupingBy(YySjStat::getYsyf, LinkedHashMap::new,  // 指定有序 Map
                            Collectors.toList()));

            cwrqList.addAll(list.stream().map(YySjStat::getYsyf).distinct().collect(Collectors.toList()));
            cwrqList.addAll(jtlist.stream().map(YySjStat::getYsyf).distinct().collect(Collectors.toList()));
        } else {
            //按财务日期分类

            //非阶梯水价费用
            cwrqMap = list.stream().filter(e -> StringUtils.isNotBlank(e.getCwrq()))
                    .collect(Collectors.groupingBy(YySjStat::getCwrq, LinkedHashMap::new,  // 指定有序 Map
                            Collectors.toList()));
            //阶梯水价费用
            cwrqjtMap = jtlist.stream().filter(e -> StringUtils.isNotBlank(e.getCwrq()))
                    .collect(Collectors.groupingBy(YySjStat::getCwrq, LinkedHashMap::new,  // 指定有序 Map
                            Collectors.toList()));

            cwrqList.addAll(list.stream().map(YySjStat::getCwrq).distinct().collect(Collectors.toList()));
            cwrqList.addAll(jtlist.stream().map(YySjStat::getCwrq).distinct().collect(Collectors.toList()));
        }
        cwrqList = cwrqList.stream().distinct()
                .sorted(Comparator.comparingInt((String e) -> Integer.parseInt(e)).reversed())
                .collect(Collectors.toList());
        List<YyQfmxMonthlyStat> results = new ArrayList<>();
        List<BmSj> sjList = getSjMap();
        if (StringUtil.isNotEmpty(filter.getYslx())) {
            sjList = sjList.stream().filter(e -> e.getYslx().equals(filter.getYslx())).collect(Collectors.toList());
        }
        //月份循环
        List<BmSj> finalSjList = sjList;
        Map<String, List<YySjStat>> finalCwrqjtMap = cwrqjtMap;
        Map<String, List<YySjStat>> finalCwrqMap = cwrqMap;
        cwrqList.forEach(key -> {
            List<YyQfmxMonthlyStat> result = new ArrayList<>();

            List<YySjStat> value = finalCwrqMap.getOrDefault(key, new ArrayList<>());
            //阶梯水价明细
            Map<String, List<YySjStat>> jtSjmxMap = Optional.ofNullable(finalCwrqjtMap)
                    .map(m -> m.getOrDefault(key, new ArrayList<>()))
                    .orElse(new ArrayList<>()).stream()
                    .filter(e -> StringUtils.isNotBlank(e.getSjbm()))
                    .collect(Collectors.groupingBy(x -> x.getSjbm()));

            //需要收费记录
            Map<String, List<YySjStat>> sjmxMap = value.stream().filter(
                    e -> StringUtils.isNotBlank(e.getSjbm())
                            && !e.getSfbz().equals("4")
            ).collect(Collectors.groupingBy(x -> x.getSjbm()));
            /*不收费费用记录不显示*/
            //不收费费用记录
//            Map<String, List<YySjStat>> sjmxbsfMap = value.stream().filter(
//                    e -> StringUtils.isNotBlank(e.getSjbm())
//                            && e.getSfbz().equals("4")
//            ).collect(Collectors.groupingBy(x -> x.getSjbm()));
//            if (!sjmxbsfMap.isEmpty()) {
//                for (List<YySjStat> yySjStats : sjmxbsfMap.values()) {
//                    BmSj bmsj = finalSjList.stream().filter(e -> e.getCode().equals(yySjStats.get(0).getSjbm())).findFirst().get();
//                    BigDecimal sl = yySjStats.stream().map(YySjStat::getSl).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                    BigDecimal sf = yySjStats.stream().map(YySjStat::getSf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                    BigDecimal wsf = yySjStats.stream().map(YySjStat::getWsf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                    BigDecimal ljf = yySjStats.stream().map(YySjStat::getLjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                    BigDecimal szyf = yySjStats.stream().map(YySjStat::getSzyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                    BigDecimal bs = yySjStats.stream().map(YySjStat::getBs).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                    BigDecimal znj = yySjStats.stream().map(YySjStat::getZnj).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                    BigDecimal ecjyf = yySjStats.stream().map(YySjStat::getEcjyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                    BigDecimal fjf = yySjStats.stream().map(YySjStat::getFjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                    BigDecimal qtf = yySjStats.stream().map(YySjStat::getQtf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//
//                    result.add(0, new YyQfmxMonthlyStat(key, bmsj.getName(), BigDecimal.ZERO, BigDecimal.ZERO, sl, sf, wsf, ljf, szyf, znj, sf.add(wsf).add(ljf).add(szyf), bs, ecjyf, fjf, qtf));
//                }
//            }
            for (BmSj bmsj : finalSjList) {
                List<YySjStat> sjmxs = sjmxMap.getOrDefault(bmsj.getCode(), new ArrayList<>());
                BigDecimal sl = sjmxs.stream().map(YySjStat::getSl).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal sf = sjmxs.stream().map(YySjStat::getSf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal wsf = sjmxs.stream().map(YySjStat::getWsf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal ljf = sjmxs.stream().map(YySjStat::getLjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal szyf = sjmxs.stream().map(YySjStat::getSzyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal bs = sjmxs.stream().map(YySjStat::getBs).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal znj = sjmxs.stream().map(YySjStat::getZnj).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal ecjyf = sjmxs.stream().map(YySjStat::getEcjyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal fjf = sjmxs.stream().map(YySjStat::getFjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal qtf = sjmxs.stream().map(YySjStat::getQtf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                if (bmsj.getJtbz().equals("0")) {
                    BigDecimal hsysje = sf.add(wsf).add(ljf).add(szyf).add(ecjyf).add(fjf).add(qtf);
                    if (hsysje.compareTo(BigDecimal.ZERO) != 0 || !sl.equals(BigDecimal.ZERO)) {
                        BigDecimal hjsj = bmsj.getSj().add(bmsj.getWsfdj()).add(bmsj.getSzyfdj());
                        result.add(new YyQfmxMonthlyStat(key, bmsj.getName(), bmsj.getSj(), hjsj, sl, sf, wsf, ljf, szyf, znj, hsysje, bs, ecjyf, fjf, qtf));
                    }
                } else {

                    List<YySjStat> jtsjmxs = jtSjmxMap.getOrDefault(bmsj.getCode(), new ArrayList<>());
                    //获取需要收费的阶梯费用明细
                    Map<BigDecimal, List<YySjStat>> jtsjmxsMap = jtsjmxs.stream().filter(
                            e -> StringUtils.isNotBlank(e.getSjbm())
                                    && !e.getSfbz().equals("4")
                            //&& e.getSj().compareTo(BigDecimal.ZERO) != 0
                    ).collect(Collectors.groupingBy(x -> x.getSj()));
                    /*不收费费用记录不显示*/
                    //获取需要不收费的阶梯费用明细
//                    List<YySjStat> jtbsfyySjStats = jtsjmxs.stream().filter(
//                            e -> StringUtils.isNotBlank(e.getSjbm())
//                                    && e.getSfbz().equals("4")
//                                    && e.getSl().compareTo(BigDecimal.ZERO) > 0
//                    ).collect(Collectors.toList());
//                    if (!jtbsfyySjStats.isEmpty()) {
//                        BigDecimal bsfsl = jtbsfyySjStats.stream().map(YySjStat::getSl).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                        BigDecimal bsfsf = jtbsfyySjStats.stream().map(YySjStat::getSf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                        BigDecimal bsfwsf = jtbsfyySjStats.stream().map(YySjStat::getWsf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                        BigDecimal bsfljf = jtbsfyySjStats.stream().map(YySjStat::getLjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                        BigDecimal bsfszyf = jtbsfyySjStats.stream().map(YySjStat::getSzyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                        BigDecimal bsfbs = jtbsfyySjStats.stream().map(YySjStat::getBs).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                        BigDecimal bsfznj = jtbsfyySjStats.stream().map(YySjStat::getZnj).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                        BigDecimal bsfecjyf = jtbsfyySjStats.stream().map(YySjStat::getEcjyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                        BigDecimal bsffjf = jtbsfyySjStats.stream().map(YySjStat::getFjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                        BigDecimal bsfqtf = jtbsfyySjStats.stream().map(YySjStat::getQtf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//
//                        result.add(0, new YyQfmxMonthlyStat(key, bmsj.getName(), BigDecimal.ZERO, BigDecimal.ZERO, bsfsl, bsfsf, bsfwsf, bsfljf, bsfszyf, bsfznj, bsfsf.add(bsfwsf).add(bsfljf).add(bsfszyf), bsfbs, bsfecjyf, bsffjf, bsfqtf));
//                    }
                    for (List<YySjStat> yySjStats : jtsjmxsMap.values()) {
                        BigDecimal jtsl = yySjStats.stream().map(YySjStat::getSl).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                        BigDecimal jtsf = yySjStats.stream().map(YySjStat::getSf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                        BigDecimal jtwsf = yySjStats.stream().map(YySjStat::getWsf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                        BigDecimal jtljf = yySjStats.stream().map(YySjStat::getLjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                        BigDecimal jtszyf = yySjStats.stream().map(YySjStat::getSzyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                        BigDecimal jtbs = yySjStats.stream().map(YySjStat::getBs).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                        BigDecimal jtznj = yySjStats.stream().map(YySjStat::getZnj).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                        BigDecimal jtecjyf = yySjStats.stream().map(YySjStat::getEcjyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                        BigDecimal jtfjf = yySjStats.stream().map(YySjStat::getFjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                        BigDecimal jtqtf = yySjStats.stream().map(YySjStat::getQtf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                        BigDecimal jthjysje = jtsf.add(jtwsf).add(jtljf).add(jtszyf).add(jtecjyf).add(jtfjf).add(jtqtf);
                        if (jthjysje.compareTo(BigDecimal.ZERO) != 0 || !jtsl.equals(BigDecimal.ZERO)) {
                            BigDecimal jthjsj = yySjStats.get(0).getSj().add(bmsj.getWsfdj()).add(bmsj.getSzyfdj());
                            if (yySjStats.get(0).getSj().compareTo(BigDecimal.ZERO) <= 0) {
                                jthjsj = BigDecimal.ZERO;
                            }
                            result.add(new YyQfmxMonthlyStat(key, bmsj.getName(), yySjStats.get(0).getSj(), jthjsj, jtsl, jtsf, jtwsf, jtljf, jtszyf, jtznj, jthjysje, jtbs, jtecjyf, jtfjf, jtqtf));
                        }
                        //i++;
                    }
                }
            }
            //小计
            if (!result.isEmpty()) {
                BigDecimal sl = result.stream().map(YyQfmxMonthlyStat::getSl).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal sf = result.stream().map(YyQfmxMonthlyStat::getSf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal wsf = result.stream().map(YyQfmxMonthlyStat::getWsf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal ljf = result.stream().map(YyQfmxMonthlyStat::getLjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal szyf = result.stream().map(YyQfmxMonthlyStat::getSzyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal hj = result.stream().map(YyQfmxMonthlyStat::getHj).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal bs = result.stream().map(YyQfmxMonthlyStat::getBs).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal znj = result.stream().map(YyQfmxMonthlyStat::getZnj).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal ecjyf = result.stream().map(YyQfmxMonthlyStat::getEcjyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal fjf = result.stream().map(YyQfmxMonthlyStat::getFjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal qtf = result.stream().map(YyQfmxMonthlyStat::getQtf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                result.add(new YyQfmxMonthlyStat(key, "小计", BigDecimal.ZERO, BigDecimal.ZERO, sl, sf, wsf, ljf, szyf, znj, hj, bs, ecjyf, fjf, qtf));
            }
            results.addAll(result);

        });
        BigDecimal hjsl = results.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getSl).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal hjsf = results.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getSf).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal hjwsf = results.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getWsf).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal hjljf = results.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getLjf).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal hjszyf = results.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getSzyf).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal zhj = results.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getHj).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal zbs = results.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getBs).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal znj = results.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getZnj).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal zecjyf = results.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getEcjyf).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal zfjf = results.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getFjf).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal zqtf = results.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getQtf).reduce(BigDecimal.ZERO, BigDecimal::add);
        if (zhj.compareTo(BigDecimal.ZERO) != 0) {
            results.add(new YyQfmxMonthlyStat(null, "合计", null, null, hjsl, hjsf, hjwsf, hjljf, hjszyf, znj, zhj, zbs, zecjyf, zfjf, zqtf));
        }

        return results;
    }


    @Override
    public List<JzhztjDto> jzhztj(JzhztjSeachFilter filter) {

        String sfbz = filter.getSfbz();
        String chbz = filter.getChbz();
        List<YyQfmxJzhzSelect> lists = new ArrayList<>();
        List<YyQfmxJzhzSelect> jzhztjList1 = baseMapper.getJzhztjList(filter, sfbz, chbz, "");
        List<YyQfmxJzhzSelect> jzhztjList2 = baseMapper.getJzhztjList(filter, sfbz, chbz, "1");
        List<YyQfmxJzhzSelect> jzhztjList3 = baseMapper.getJzhztjList(filter, sfbz, chbz, "2");
        if (!jzhztjList1.isEmpty())
            lists.addAll(jzhztjList1);
        if (!jzhztjList2.isEmpty())
            lists.addAll(jzhztjList2);
        if (!jzhztjList3.isEmpty())
            lists.addAll(jzhztjList3);
        List<JzhztjDto> dataList = new ArrayList<>();
        if (!lists.isEmpty()) {
            dataList = this.jsjzhzmx(lists);
        }
        return dataList;
    }

    public List<JzhztjDto> jzhzqscx(JzhztjSeachFilter filter) {
        if (StringUtil.isEmpty(filter.getCwrq()) && StringUtil.isEmpty(filter.getNf())) {
            throw new FeesException("参数错误，年份与财务日期不能同时为空", BUSINESS_ERROR);
        }
        filter.setJzEnd(filter.getEndDate());
        filter.setStartDate(null);
        filter.setEndDate(null);
//        if (StringUtil.isNotEmpty(filter.getCwrq())) {
//            String cwrq = filter.getCwrq();
//            String tempEndSfrq = cwrq.substring(0, 4) + "-" + cwrq.substring(4, 6) + "-01 23:59:59";
//            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN);
//            LocalDateTime dt_tempEndSfrq = LocalDateTime.parse(tempEndSfrq, formatter).plusMonths(1).plusDays(-1);
//            filter.setJzEnd(dt_tempEndSfrq);
//        }
//        if (StringUtil.isNotEmpty(filter.getNf())) {
//            String nf = filter.getNf();
//            String tempEndSfrq = nf + "-12-31 23:59:59";
//            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN);
//            LocalDateTime dt_tempEndSfrq = LocalDateTime.parse(tempEndSfrq, formatter);
//            filter.setJzEnd(dt_tempEndSfrq);
//        }
        String sfbz = filter.getSfbz();
        String chbz = filter.getChbz();
        List<YyQfmxJzhzSelect> lists = new ArrayList<>();
        List<YyQfmxJzhzSelect> jzhztjList1 = baseMapper.getJzhztjList(filter, sfbz, chbz, "");
        List<YyQfmxJzhzSelect> jzhztjList2 = baseMapper.getJzhztjList(filter, sfbz, chbz, "1");
        List<YyQfmxJzhzSelect> jzhztjList3 = baseMapper.getJzhztjList(filter, sfbz, chbz, "2");
        if (!jzhztjList1.isEmpty())
            lists.addAll(jzhztjList1);
        if (!jzhztjList2.isEmpty())
            lists.addAll(jzhztjList2);
        if (!jzhztjList3.isEmpty())
            lists.addAll(jzhztjList3);
        if (lists.isEmpty()) {
            return new ArrayList<>();
        }
        List<JzhztjDto> dataList = this.jsjzhzmx(lists);
        return dataList;
    }


    private List<JzhztjDto> jsjzhzmx(List<YyQfmxJzhzSelect> qfmxList) {
        List<JzhztjDto> details = new ArrayList<>();
        Map<String, List<YyQfmxJzhzSelect>> ysxzMaps = qfmxList.stream()
                .collect(Collectors.groupingBy(YyQfmxJzhzSelect::getSjmc));
        List<Jzhztjmx> sflist = new ArrayList<>();
        List<Jzhztjmx> wsflist = new ArrayList<>();
        List<Jzhztjmx> szyflist = new ArrayList<>();

        ysxzMaps.forEach((key, value) -> {
            BigDecimal sf = value.stream().filter(o -> ObjUtil.isNotNull(o.getSf()))
                    .map(YyQfmxJzhzSelect::getSf)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal sfsl = value.stream().filter(o -> ObjUtil.isNotNull(o.getSfsl()))
                    .map(YyQfmxJzhzSelect::getSfsl)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            Integer sfhs = value.stream().filter(o -> ObjUtil.isNotNull(o.getSfhs()))
                    .map(YyQfmxJzhzSelect::getSfhs)
                    .reduce(0, Integer::sum);
            List<BigDecimal> sjList = value.stream().filter(o -> ObjUtil.isNotNull(o.getSj()) && o.getSj().compareTo(BigDecimal.ZERO) != 0)
                    .map(YyQfmxJzhzSelect::getSj)
                    .distinct().sorted(Comparator.comparing(BigDecimal::doubleValue))
                    .collect(Collectors.toList());
            BigDecimal sj = sjList.size() > 0 ? sjList.get(0) : BigDecimal.ZERO;
            if (sf.compareTo(BigDecimal.ZERO) != 0) {
                Jzhztjmx sfmx = this.getJzhztjmx(key, sfhs, "吨", sfsl, sj, sf);
                sflist.add(sfmx);
            }

            BigDecimal wsf = value.stream().filter(o -> ObjUtil.isNotNull(o.getWsf()))
                    .map(YyQfmxJzhzSelect::getWsf)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal wsfsl = value.stream().filter(o -> ObjUtil.isNotNull(o.getWsfsl()))
                    .map(YyQfmxJzhzSelect::getWsfsl)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            Integer wsfhs = value.stream().filter(o -> ObjUtil.isNotNull(o.getWsfhs()))
                    .map(YyQfmxJzhzSelect::getWsfhs)
                    .reduce(0, Integer::sum);
            List<BigDecimal> wsfdjList = value.stream().filter(o -> ObjUtil.isNotNull(o.getWsf()) && o.getWsf().compareTo(BigDecimal.ZERO) != 0)
                    .map(YyQfmxJzhzSelect::getWsf)
                    .distinct().sorted(Comparator.comparing(BigDecimal::doubleValue))
                    .collect(Collectors.toList());
            BigDecimal wsfdj = wsfdjList.size() > 0 ? wsfdjList.get(0) : BigDecimal.ZERO;
            if (wsf.compareTo(BigDecimal.ZERO) != 0) {
                Jzhztjmx wsfmx = this.getJzhztjmx(key, wsfhs, "吨", wsfsl, wsfdj, wsf);
                wsflist.add(wsfmx);
            }

            BigDecimal syzf = value.stream().filter(o -> ObjUtil.isNotNull(o.getSzyf()))
                    .map(YyQfmxJzhzSelect::getSzyf)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal syzfsl = value.stream().filter(o -> ObjUtil.isNotNull(o.getSzyfsl()))
                    .map(YyQfmxJzhzSelect::getSzyfsl)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            Integer syzfhs = value.stream().filter(o -> ObjUtil.isNotNull(o.getSzyfhs()))
                    .map(YyQfmxJzhzSelect::getSzyfhs)
                    .reduce(0, Integer::sum);
            List<BigDecimal> szyfdjList = value.stream().filter(o -> ObjUtil.isNotNull(o.getSzyf()) && o.getSzyf().compareTo(BigDecimal.ZERO) != 0)
                    .map(YyQfmxJzhzSelect::getSzyf)
                    .distinct().sorted(Comparator.comparing(BigDecimal::doubleValue))
                    .collect(Collectors.toList());
            BigDecimal szyfdj = szyfdjList.size() > 0 ? szyfdjList.get(0) : BigDecimal.ZERO;
            if (syzf.compareTo(BigDecimal.ZERO) != 0) {
                Jzhztjmx szyfmx = this.getJzhztjmx(key, syzfhs, "吨", syzfsl, szyfdj, syzf);
                szyflist.add(szyfmx);
            }
        });
        BigDecimal ecjyf = qfmxList.stream().filter(o -> ObjUtil.isNotNull(o.getEcjyf()))
                .map(YyQfmxJzhzSelect::getEcjyf)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal fjf = qfmxList.stream().filter(o -> ObjUtil.isNotNull(o.getFjf()))
                .map(YyQfmxJzhzSelect::getFjf)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal xfsf = qfmxList.stream().filter(o -> ObjUtil.isNotNull(o.getXfsf()))
                .map(YyQfmxJzhzSelect::getXfsf)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        Integer ecjyfhs = qfmxList.stream().filter(o -> ObjUtil.isNotNull(o.getEcjyfhs()))
                .map(YyQfmxJzhzSelect::getEcjyfhs)
                .reduce(0, Integer::sum);
        Integer fjfhs = qfmxList.stream().filter(o -> ObjUtil.isNotNull(o.getFjfhs()))
                .map(YyQfmxJzhzSelect::getFjfhs)
                .reduce(0, Integer::sum);
        Integer xfsfhs = qfmxList.stream().filter(o -> ObjUtil.isNotNull(o.getXfsfhs()))
                .map(YyQfmxJzhzSelect::getXfsfhs)
                .reduce(0, Integer::sum);
        if (ecjyf.compareTo(BigDecimal.ZERO) != 0) {
            Jzhztjmx ecjyfmx = this.getJzhztjmx("二次加压费", ecjyfhs, "吨", BigDecimal.ZERO, BigDecimal.ZERO, ecjyf);
            sflist.add(ecjyfmx);
        }
        if (fjf.compareTo(BigDecimal.ZERO) != 0) {
            Jzhztjmx fjfmx = this.getJzhztjmx("附加费", fjfhs, "吨", BigDecimal.ZERO, BigDecimal.ZERO, fjf);
            sflist.add(fjfmx);
        }
        if (xfsf.compareTo(BigDecimal.ZERO) != 0) {
            Jzhztjmx xfsfmx = this.getJzhztjmx("消防栓费", xfsfhs, "吨", BigDecimal.ZERO, BigDecimal.ZERO, xfsf);
            sflist.add(xfsfmx);
        }

        if (!sflist.isEmpty()) {
            details.add(this.getJzhztjDto(1, sflist));
        }
        if (!wsflist.isEmpty()) {
            details.add(this.getJzhztjDto(2, wsflist));
        }
        if (!szyflist.isEmpty()) {
            details.add(this.getJzhztjDto(3, szyflist));
        }
        return details;
    }

    private Jzhztjmx getJzhztjmx(String xm, Integer hs, String dw, BigDecimal sl, BigDecimal dj, BigDecimal je) {
        Jzhztjmx mx = new Jzhztjmx();
        mx.setXm(xm);
        mx.setHs(hs);
        mx.setDw(dw);
        mx.setSl(sl);
        mx.setDj(dj);
        mx.setJe(je);
        return mx;
    }

    private JzhztjDto getJzhztjDto(Integer type, List<Jzhztjmx> qfmxList) {
        JzhztjDto jzhztjDto = new JzhztjDto();
        jzhztjDto.setType(type);
        jzhztjDto.setDetails(qfmxList);
        jzhztjDto.setHjhs(qfmxList.stream().mapToInt(Jzhztjmx::getHs).sum());
        jzhztjDto.setHjsl(qfmxList.stream().map(Jzhztjmx::getSl).reduce(BigDecimal.ZERO, BigDecimal::add));
        jzhztjDto.setHjje(qfmxList.stream().map(Jzhztjmx::getJe).reduce(BigDecimal.ZERO, BigDecimal::add));
        return jzhztjDto;
    }


    @Override
    @Transactional
    public boolean cxSf(String id) {

        YyQfmx yyQfmx = this.getById(id);
        if (yyQfmx == null) throw new FeesException("欠费明细不存在", FeesErrorCode.BUSINESS_ERROR);
        String chbz = yyQfmx.getChbz();
        if (PjztEnum.已冲红.getValue().equals(chbz))
            throw new FeesException("只能撤销票据状态正常的欠费明细", FeesErrorCode.BUSINESS_ERROR);
        if (PjztEnum.冲红记录.getValue().equals(chbz))
            throw new FeesException("只能撤销票据状态正常的欠费明细", FeesErrorCode.BUSINESS_ERROR);
        String cwrq = gdcsbService.selectCwrq();
        if (!cwrq.equals(yyQfmx.getCwrq()))
            throw new FeesException("只能撤销当前财务月份的欠费明细", FeesErrorCode.BUSINESS_ERROR);
        String sfbz = yyQfmx.getSfbz();
        if ("1".equals(sfbz)) throw new FeesException("只能撤销未收费欠费明细", FeesErrorCode.BUSINESS_ERROR);
        String cbkid = yyQfmx.getCbkid();
        if (cbkid == null) throw new FeesException("只能撤销水费欠费明细", FeesErrorCode.BUSINESS_ERROR);
        boolean success = cblrService.lambdaUpdate().set(YyCblr::getJsbz, JsbzEnum.未算费).eq(YyCblr::getCbkid, cbkid).update();
        Date chsj = new Date();
        if (success) {
            yyQfmx.setChbz(PjztEnum.已冲红.getValue());
            yyQfmx.setChsj(chsj);
            yyQfmx.setChrybm(String.valueOf(SecurityUtils.getUserId()));
            yyQfmx.setChryxm(SecurityUtils.getUser().getRealName());
            YyQfmx hp = createHp(yyQfmx, chsj);//红票
            this.save(hp);
            this.updateById(yyQfmx);
        }
        return success;
    }

    @Override
    public YyStat stat(YyQfmxStatFilter filter) {
        return this.baseMapper.stat(filter);
    }

    @Override
    public String pjyl(pjYl pjyl) {
        try {
            YyQfmx yyQfmx = this.getById(pjyl.getQfid());
            if (yyQfmx == null) throw new FeesException("欠费明细不存在", FeesErrorCode.BUSINESS_ERROR);
            YhKhjbxx yhKhjbxx = khjbxxService.getById(yyQfmx.getYhbh());
            if (yhKhjbxx == null) throw new FeesException("客户信息不存在", FeesErrorCode.BUSINESS_ERROR);

            String qfmxsql = String.format("with sssf as" + "     (" + "     select  1 xh, '阶梯1' as mc, sjbm, b.name sjmc, jt1sj sj, jt1sl sl, jt1sf sf from yy_qfmx a left join bm_sj b on a.sjbm=b.code where  id='%s' and b.jtbz=1" + "     union" + "     select  2 xh, '阶梯2', sjbm, b.name sjmc, jt2sj, jt2sl, jt2sf from yy_qfmx a left join bm_sj b on a.sjbm=b.code where id='%s' and b.jtbz=1" + "     union" + "     select  3 xh, '阶梯3', sjbm, b.name sjmc, jt3sj, jt3sl, jt3sf from yy_qfmx a left join bm_sj b on a.sjbm=b.code where id='%s' and b.jtbz=1" + "     union" + "     select  4 xh, '' , a.sjbm, b.name sjmc, a.sj, a.sl, a.sf from yy_qfmx a left join bm_sj b on a.sjbm=b.code where id='%s' and nvl(b.jtbz,0)=0" + "     )" + "     select a.* from sssf a left  join bm_sj b on a.sjbm=b.code where nvl(a.sf,0)>0 ", pjyl.getQfid(), pjyl.getQfid(), pjyl.getQfid(), pjyl.getQfid());

            String qtfysql = String.format("select 5,'污水费' mc,wsfdj dj, yswsf sf,yssl sl from yy_qfmx" + "     where id='%s' and  nvl(yswsf,0)>0  " + "     union " + "     select 6,'垃圾费',ljfdj dj,ysljf,yssl sl from yy_qfmx" + "     where id='%s' and nvl(ysljf,0)>0  " + "     union " + "     select 7,'违约金',0 ,znj,0 sl from yy_qfmx" + "     where id='%s' and nvl(ysljf,0)>0 ", pjyl.getQfid(), pjyl.getQfid(), pjyl.getQfid());
            List<HashMap<String, Object>> qflist = DbHelper.getDbHelper().getList(qfmxsql);
            StringBuilder str = new StringBuilder();
            qflist.forEach(e -> {
                str.append("<tr>");
                str.append(String.format("<td>%s</td>", e.get("mc")));
                str.append(String.format("<td>%s</td>", e.get("sf")));
                str.append(String.format("<td>%s</td>", e.get("sj")));
                str.append(String.format("<td>%s</td>", e.get("sl")));
                str.append(String.format("<td>%s</td>", "\\"));
                str.append(String.format("<td>%s</td>", ""));
                str.append("</tr>");
            });
            List<HashMap<String, Object>> qtlist = DbHelper.getDbHelper().getList(qtfysql);
            qtlist.forEach(e -> {
                str.append("<tr>");
                str.append(String.format("<td>%s</td>", e.get("mc")));
                str.append(String.format("<td>%s</td>", e.get("sf")));
                str.append(String.format("<td>%s</td>", e.get("dj")));
                str.append(String.format("<td>%s</td>", e.get("sl")));
                str.append(String.format("<td>%s</td>", "\\"));
                str.append(String.format("<td>%s</td>", ""));
                str.append("</tr>");
            });
            String htmlstr = DbHelper.getDbHelper().getValue(String.format("select printtemplate from print_template where id=%s", PjlxEnum.实收票据信息.getValue()));
            htmlstr = htmlstr.replace("{{title}}", "水务");
            htmlstr = htmlstr.replace("{{yhbh}}", yyQfmx.getYhbh());
            htmlstr = htmlstr.replace("{{yhxm}}", yyQfmx.getYhxm());
            htmlstr = htmlstr.replace("{{cwyf}}", yyQfmx.getCwrq());
            htmlstr = htmlstr.replace("{{sfrq}}", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            htmlstr = htmlstr.replace("{{lxdh}}", yhKhjbxx.getLxdh());
            htmlstr = htmlstr.replace("{{addr}}", yhKhjbxx.getYhdz());
            htmlstr = htmlstr.replace("{{scds}}", yyQfmx.getScds().toString());
            htmlstr = htmlstr.replace("{{bcds}}", yyQfmx.getBcds().toString());
            htmlstr = htmlstr.replace("{{sl}}", yyQfmx.getSl().toString());

            htmlstr = htmlstr.replace("{{content}}", str.toString());
            htmlstr = htmlstr.replace("{{ysje}}", yyQfmx.getYsje().add(yyQfmx.getZnj()).toString());
            htmlstr = htmlstr.replace("{{ysjedx}}", NumberHelper.toChineseMoney(yyQfmx.getYsje().add(yyQfmx.getZnj())));
            htmlstr = htmlstr.replace("{{scjy}}", pjyl.getScjz().toString());
            htmlstr = htmlstr.replace("{{bcjy}}", pjyl.getBcjz().toString());
            htmlstr = htmlstr.replace("{{sszje}}", pjyl.getSsje().toString());
            htmlstr = htmlstr.replace("{{sfry}}", SecurityUtils.getUser().getRealName());
            htmlstr = htmlstr.replace("{{cbry}}", yyQfmx.getCbryxm());
            String cbrydh = DbHelper.getDbHelper().getValue(String.format("select olxdh from  sys_operators where ocode = (select cby from bm_cbb where cbbbm='%s')", yyQfmx.getSscbb()));
            if (StringUtils.isEmpty(cbrydh)) {
                cbrydh = "无";
            }
            htmlstr = htmlstr.replace("{{cbrydh}}", cbrydh);
            return htmlstr;
        } catch (Exception e) {
            throw new FeesException("查询数据错误！", FeesErrorCode.BUSINESS_ERROR);
        }
    }

    @Override
    public SfJsJg znbsfJs(YhCbkxx cbkxx, YhKhjbxx khjbxx, BigDecimal sjsl) throws Exception {
        sjCache();//缓存表价信息（计算前必须）
        zbFbsCache();
        return sfJs(cbkxx, khjbxx, sjsl);
    }

    /**
     * 水费计算
     * 一表多价： 一个水表（含多个用水类型）按用水类型和比例计算水费
     * 阶梯计算： 居民用水根据年度/季度等范围计算阶梯用量,不同阶梯不同单价
     */
    private SfJsJg sfJs(YhCbkxx cbkxx, YhKhjbxx yhxx, BigDecimal sjsl) throws Exception {
        BigDecimal ljsl = yhxx.getJtzqljl() == null ? BigDecimal.ZERO : yhxx.getJtzqljl();

        SfJsJg jsqJg = sfJs0(cbkxx, yhxx, ljsl, sjsl);

        if (jsqJg.getJtzqljl().compareTo(BigDecimal.ZERO) > 0) {
            cbkxxService.updateLjsl(cbkxx.getCbkid(), jsqJg.getJtzqljl());
            khjbxxService.lambdaUpdate().set(YhKhjbxx::getJtzqljl, jsqJg.getJtzqljl()).eq(YhKhjbxx::getYhbh, yhxx.getYhbh()).update();
        }
        if (jsqJg.getYhsl().compareTo(BigDecimal.ZERO) > 0) {
            BigDecimal dbhndljl = jsqJg.getYhsl().add(yhxx.getDbhndljl());
            khjbxxService.lambdaUpdate().set(YhKhjbxx::getDbhndljl, dbhndljl).eq(YhKhjbxx::getYhbh, yhxx.getYhbh()).update();
        }

        return jsqJg;
    }

    @Override
    public SfJsJg jtSfjs(Jtsfjs jtsfjs) {
        SfJsJg jsqJg = new SfJsJg();
        TreeMap<String, String> slMap = new TreeMap<>();
        slMap.put("L1", String.format("%s_%s", jtsfjs.getSjbm(), jtsfjs.getSl()));
        Date now = new Date();
        jsqJg.setJsrq(now);

        YhKhjbxx yhKhjbxx = khjbxxService.getById(jtsfjs.getYhbh());
        if (ObjUtil.isNull(yhKhjbxx)) {
            throw new FeesException("用户档案不存在", FeesErrorCode.BUSINESS_ERROR);
        }

        YhCbkxx yhCbkxx = cbkxxService.getOne(new QueryWrapper<YhCbkxx>().lambda().eq(YhCbkxx::getCbkh, jtsfjs.getCbkh()).eq(YhCbkxx::getYhbh, jtsfjs.getYhbh()));
        if (ObjUtil.isNull(yhCbkxx)) {
            throw new FeesException("水表档案不存在", FeesErrorCode.BUSINESS_ERROR);
        }

        sjCache();//缓存表价信息（计算前必须）
        zbFbsCache();

        Map<String, Object> values = new LinkedHashMap<>();
        slMap.forEach((key, value) -> {
            if (key.equals("L1")) {
                String sjTag = "";
                String sjTag2 = "";
                Map<String, Object> values1 = getValues(value, jtsfjs.getJtljl(), sjTag, sjTag2, yhCbkxx, yhKhjbxx);
                values.putAll(values1);
            }
        });

        List<BigDecimal> sls = getMxValues(values, "sl");
        List<BigDecimal> sfs = getMxValues(values, "sf");
        List<BigDecimal> wsfs = getMxValues(values, "wsf");
        List<BigDecimal> ljfs = getMxValues(values, "ljf");
        List<BigDecimal> szyfs = getMxValues(values, "szyf");

        List<BigDecimal> ecjyf = getMxValues(values, "ecjyf");
        List<BigDecimal> fjf = getMxValues(values, "fjf");
        List<BigDecimal> xfsf = getMxValues(values, "xfsf");

        BigDecimal yssl = sls.stream().reduce(BigDecimal.ZERO, (x, y) -> x.add(y));
        BigDecimal yssf = sfs.stream().reduce(BigDecimal.ZERO, (x, y) -> x.add(y));
        BigDecimal yswsf = wsfs.stream().reduce(BigDecimal.ZERO, (x, y) -> x.add(y));
        BigDecimal ysljf = ljfs.stream().reduce(BigDecimal.ZERO, (x, y) -> x.add(y));
        BigDecimal ysszyf = szyfs.stream().reduce(BigDecimal.ZERO, (x, y) -> x.add(y));
        // 新增二次加压费、附加费、消防栓费计算
        BigDecimal ysecjyf = ecjyf.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal ysfjf = fjf.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal ysxfsf = xfsf.stream().reduce(BigDecimal.ZERO, BigDecimal::add);

        try {
            BigDecimal ljsl = yhKhjbxx.getJtzqljl() == null ? BigDecimal.ONE.negate() : yhKhjbxx.getJtzqljl();
            org.apache.commons.beanutils.BeanUtils.populate(jsqJg, values);
            CbjsfsEnum cbjsfs = getCbjsfs(slMap, values);//抄表计算方式（0正常单价，1一表多价，2阶梯,3 一表多价含阶梯；用于判断计价类型，处理显示水价）
            jsqJg.setCbjsbz(cbjsfs.getValue());
            jsqJg.setCbjsfs(cbjsfs.name());
            jsqJg.setJtzqljlJsq(ljsl);
            jsqJg.setJtzqljl(ljsl == null ? null : ljsl.add(yssl));
            jsqJg.setYssl(yssl);
            jsqJg.setYssf(yssf);
            jsqJg.setYsljf(ysljf);
            jsqJg.setYswsf(yswsf);
            jsqJg.setYsszyf(ysszyf);
            jsqJg.setYsecjyf(ysecjyf);
            jsqJg.setYsfjf(ysfjf);
            jsqJg.setYsqt(ysxfsf);

            jsqJg.setYsje(yssf.add(ysljf).add(yswsf).add(ysszyf).add(ysecjyf).add(ysfjf).add(ysxfsf));

            // 违约金计算
            List<BmYslx> bmYslxs = bmYslxService.lambdaQuery().inSql(BmYslx::getCode, String.format("select yslx from bm_sj where code='%s'", jtsfjs.getSjbm())).list();
            if (bmYslxs.size() > 0) {
                BmYslx bmYslx = bmYslxs.get(0);
                ZNJResult znjResult = znjCal.getZNJ(LocalDateTime.parse(jtsfjs.getCbrq(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).toLocalDate(), bmYslx.getZnjbm(), bmYslx.getZnjday(), bmYslx.getZnj(), jsqJg.getYssf(), "", jtsfjs.getYhbh());
                jsqJg.setZnj(znjResult.getZnJJe());
            }

        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        return jsqJg;
    }

    @Override
    public void suanfeiTask() {
        List<YyCblr> cblrs = cblrService.lambdaQuery()
                .eq(YyCblr::getJsbz, JsbzEnum.未算费)
                .eq(YyCblr::getShbz, ShbzEnum.审核通过)
                .eq(YyCblr::getCbbz, CbbzEnum.已抄表)
                .gt(YyCblr::getSl, BigDecimal.ZERO)
                .notExists("select 1 from yh_bjfl_fb fb left join yh_bjfl_zb zb on fb.zb_id=zb.id "
                        + "where fb.zb_id<>fb.id and zb.isdisabled='1' and (fb.yhbh||fb.cbkh)=cbkid")
                .list();
        Syscommlog syscommlog = new Syscommlog();
        syscommlog.setTablename("yy_qfmx");
        syscommlog.setMstext("自动算费suanfeiTask");
        syscommlog.setAddate(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss")));

        if (CollectionUtil.isNotEmpty(cblrs)) {
            int count = this.Tasksf(cblrs);
            syscommlog.setRemark(String.format("调用算费，成功%s条，失败%s条", count, cblrs.size() - count));

        } else {
            syscommlog.setRemark("调用算费：无未算费数据");
        }
        syscommlog.setUserid("3");
        syscommlogService.save(syscommlog);
    }

    @Override
    public int Tasksf(List<YyCblr> cblrs) {

        cblrs = cblrs.stream()
                .filter(e -> e.getCbbz() == CbbzEnum.已抄表)
                .filter(e -> e.getJsbz() == JsbzEnum.未算费)
                .filter(e -> e.getSl() != null && e.getSl().compareTo(BigDecimal.ZERO) >= 0)
                .collect(Collectors.toList());

        if (cblrs.isEmpty()) {
            return 0;
        }

        Set<String> yhbhs = cblrs.stream().map(e -> e.getYhbh()).collect(Collectors.toSet());
        Map<String, YyCblr> cblrMap = cblrs.stream()
                .collect(Collectors.toMap(e -> e.getCbkid(), e -> e, (u1, u2) -> u1, LinkedHashMap::new));
        if (cblrMap.isEmpty()) {
            return 0;
        }

        // 缓存水价
        sjCache();

        AtomicInteger count = new AtomicInteger();
        cblrMap.forEach((cbkid, cblr) -> {
            int i = transactionTemplate.execute(status -> {
                try {
                    YhCbkxx cbkxx = cbkxxService.getById(cbkid);
                    if (ObjUtil.isNull(cbkxx)) {
                        return 0;
                    }

                    String yhbh = cbkxx.getYhbh();
                    YhKhjbxx yhxx = khjbxxService.getById(yhbh);
                    if (ObjUtil.isNull(yhxx)) {
                        return 0;
                    }

                    BigDecimal sjsl = cblr.getSl();
                    if (sjsl.compareTo(BigDecimal.ZERO) <= 0) {
                        cblrService.updateJsbz(cbkid);
                        return 0;
                    }

                    // 消防通表号的水表不做计费
                    String xftbh = cbkxx.getXftbh();
                    if (StrUtil.isNotEmpty(xftbh)) {
                        cblrService.updateJsbz(cbkid);
                        return 1;
                    }

                    YyQfmx yyQfmx = new YyQfmx();
                    yyQfmx.setQflsbh(GuidGenerator.getQflsbh());
                    BigDecimal cbkxxXfsf = cbkxx.getXfsf();

                    if (sjsl.compareTo(BigDecimal.ZERO) == 0 && cbkxxXfsf.compareTo(BigDecimal.ZERO) == 0) {
                        BeanUtils.copyProperties(yhxx, yyQfmx, NumberHelper.getNullPropertyNames(yhxx));
                        BeanUtils.copyProperties(cblr, yyQfmx, NumberHelper.getNullPropertyNames(cblr));
                        yyQfmx.setSfbz("4");
                        yyQfmx.setJsrq(new Date());
                        if (StringUtil.isNotEmpty(cbkxx.getSjbm())) {
                            yyQfmx.setSjbm(cbkxx.getSjbm());
                        }
                        if (StringUtil.isNotEmpty(cbkxx.getSjbm1())) {
                            yyQfmx.setSjbm1(cbkxx.getSjbm1());
                        }
                        if (StringUtil.isNotEmpty(cbkxx.getSjbm1())) {
                            yyQfmx.setSjbm2(cbkxx.getSjbm2());
                        }
                        yyQfmx.setJtzqljlJsq(yhxx.getJtzqljl());
                    } else {
                        SfJsJg sfJsJg = sfJs(cbkxx, yhxx, sjsl);
                        BeanUtils.copyProperties(yhxx, yyQfmx, NumberHelper.getNullPropertyNames(yhxx));
                        BeanUtils.copyProperties(cblr, yyQfmx, "sl");
                        BeanUtils.copyProperties(sfJsJg, yyQfmx, NumberHelper.getNullPropertyNames(sfJsJg));
                    }
                    //附加费与消防栓费每个月只用算费一次
                    if (cblr.getCbcs().compareTo(BigDecimal.ONE) == 0) {
                        // 附加费
                        if (cbkxx.getFjf() != null && cbkxx.getFjf().compareTo(BigDecimal.ZERO) > 0) {
                            BigDecimal fjf = cbkxx.getFjf();
                            yyQfmx.setYsfjf(fjf);
                            yyQfmx.setFjf(fjf);
                            yyQfmx.setFjfdj(fjf);
                        }
                        // 消防栓费
                        if (cbkxxXfsf != null && cbkxxXfsf.compareTo(BigDecimal.ZERO) > 0) {
                            BigDecimal xfsf = cbkxx.getXfsf();
                            yyQfmx.setYsqt(xfsf);
                        }
                        yyQfmx.setYsje(yyQfmx.getYsje().add(yyQfmx.getYsfjf()).add(yyQfmx.getYsqt()));
                    }
                    yyQfmx.setSfbc("0");
                    yyQfmx.setFylx(BcFylxEnum.Zhfy.getValue().toString());
                    yyQfmx.setFylxmc(BcFylxEnum.Zhfy.getName());
                    //yyQfmx.setYsyf(cblr.getCwrq());
                    yyQfmx.setYsyf(ymjzConfigService.getCwrq(cblr.getCbrq()));
                    yyQfmx.setChbz(PjztEnum.正常.getValue());
                    yyQfmx.setKhbm(yhxx.getKhbm());
                    this.save(yyQfmx);

                    cblrService.updateJsbz(cbkid);
                    return 1;
                } catch (Exception e) {
                    log.error("水费计算失败: =====================> ", e);
                    status.setRollbackOnly();
                    return 0;
                }
            });
            count.addAndGet(i);
        });

        return count.get();
    }

    @Override
    @Transactional
    public boolean ykfp(FpykInsert insert) {
        if (StringUtil.isEmpty(insert.getYhbh())) {
            throw new FeesException("用户编号不能为空", FeesErrorCode.BUSINESS_ERROR);
        }
        if (insert.getQfids().isEmpty()) {
            throw new FeesException("欠费ID集合不能为空", FeesErrorCode.BUSINESS_ERROR);
        }
        long count = yhGroupAccountsService.lambdaQuery().eq(YhGroupAccounts::getYhbh, insert.getYhbh()).count();
        if (count > 0) {
            throw new FeesException("该记录是群主户不能预开发票！", FeesErrorCode.BUSINESS_ERROR);
        }
        khjbxxService.lambdaUpdate()
                .set(YhKhjbxx::getFplx, insert.getFplx())
                .set(StrUtil.isNotEmpty(insert.getFpName()), YhKhjbxx::getFpName, insert.getFpName())
                .set(StringUtil.isNotEmpty(insert.getFpDz()), YhKhjbxx::getFpDz, insert.getFpDz())
                .set(StringUtil.isNotEmpty(insert.getFpLxdh()), YhKhjbxx::getFpLxdh, insert.getFpLxdh())
                .set(StringUtil.isNotEmpty(insert.getFpNsrsbh()), YhKhjbxx::getFpNsrsbh, insert.getFpNsrsbh())
                .set(StringUtil.isNotEmpty(insert.getFpBankcode()), YhKhjbxx::getFpBankcode, insert.getFpBankcode())
                .set(StringUtil.isNotEmpty(insert.getFpBankname()), YhKhjbxx::getFpBankname, insert.getFpBankname())
                .set(StringUtil.isNotEmpty(insert.getFpBz()), YhKhjbxx::getFpBz, insert.getFpBz())
                .eq(YhKhjbxx::getYhbh, insert.getYhbh()).update();

        List<YyQfmx> yyQfmxList = this.lambdaQuery()
                .in(YyQfmx::getId, insert.getQfids())
                .eq(YyQfmx::getSfbz, "0")
                .eq(YyQfmx::getChbz, "0")
                .eq(YyQfmx::getEiYkfpBz, "0").list();
        if (insert.getQfids().size() != yyQfmxList.size()) {
            throw new FeesException("存在不符合条件的欠费ID", FeesErrorCode.BUSINESS_ERROR);
        }
        YhKhjbxx yhKhjbxx = khjbxxService.getById(insert.getYhbh());
        yyQfmxList.stream().forEach(e -> {
            e.setEiYkfpBz("1");
        });
        if (insert.getIshbkp().equals("1")) {
            invoiceService.addInvoiceData(yyQfmxList, null, yhKhjbxx, "1", "1");
        } else {
            for (YyQfmx yyQfmx : yyQfmxList) {
                invoiceService.addInvoiceData(Collections.singletonList(yyQfmx), null, yhKhjbxx, "0", "1");
            }
        }
        this.lambdaUpdate().set(YyQfmx::getEiYkfpBz, "1").in(YyQfmx::getId, insert.getQfids()).update();
        return true;
    }

    @Override
    public String fytzsave(fylrDto e, String gdzt) {
        fytzCheckParam(e);

        ToflyUser user = SecurityUtils.getUser();
        if (gdzt.equals("4")) {
            YhKhjbxx yhKhjbxx = khjbxxService.getById(e.getYhbh());
            if (StringUtil.isNull(yhKhjbxx)) {
                throw new FeesException("用户信息不存在！", FeesErrorCode.BUSINESS_ERROR);
            }

            YhCbkxx yhCbkxx = cbkxxService.getById(e.getYhbh() + "1");
            if (StringUtil.isNull(yhCbkxx)) {
                throw new FeesException("用户抄表信息不存在！", FeesErrorCode.BUSINESS_ERROR);
            }

            YyQfmx yyQfmx = new YyQfmx();
            BeanUtils.copyProperties(yhKhjbxx, yyQfmx);
            BeanUtils.copyProperties(yhCbkxx, yyQfmx);
            yyQfmx.setChbz(PjztEnum.正常.getValue());
            yyQfmx.setEiYkfpBz("0");
            yyQfmx.setCbjsbz("0");
            yyQfmx.setCbjsfs("正常单价计费");
            yyQfmx.setJyType(e.getJyType());
            yyQfmx.setSfbc("1");
            yyQfmx.setQflsbh(GuidGenerator.getQflsbh());
            yyQfmx.setYhbh(e.getYhbh());
            yyQfmx.setYhxm(e.getYhxm());
            yyQfmx.setSsgs(yhKhjbxx.getSsgs());
            yyQfmx.setSscbpq(yhKhjbxx.getSscbpq());
            yyQfmx.setCwrq(e.getCwrq());
            //yyQfmx.setYsyf(e.getCwrq());
            yyQfmx.setCbrq(e.getCbrq());
            yyQfmx.setYsyf(ymjzConfigService.getCwrq(e.getCbrq()));
            yyQfmx.setFylx(e.getFylx());
            yyQfmx.setJsrq(new Date());

            BmFylx bmFylx = bmFylxService.getById(e.getFylx());
            String fylxName = bmFylx.getName();
            yyQfmx.setFylxmc(fylxName);
            BigDecimal fydj = e.getFydj();
            BigDecimal fysl = e.getFysl();
            BigDecimal fyje = e.getFyje();
            if (fylxName.contains("违约金")) {
                yyQfmx.setZnj(fyje);
            } else if (fylxName.contains("水费")) {
                yyQfmx.setSf(fyje);
                yyQfmx.setSj(fydj);
                yyQfmx.setSl(fysl);
                yyQfmx.setYssl(fysl);
                yyQfmx.setYssf(fyje);
            } else if (fylxName.contains("污水处理费")) {
                yyQfmx.setWsf(fyje);
                yyQfmx.setWsfdj(fydj);
                yyQfmx.setSl(fysl);
                yyQfmx.setYswsf(fyje);
            } else if (fylxName.contains("水资源税")) {
                yyQfmx.setSzyf(fyje);
                yyQfmx.setSzyfDj(fydj);
                yyQfmx.setSl(fysl);
                yyQfmx.setYsszyf(fyje);
            } else if (fylxName.contains("垃圾费")) {
                yyQfmx.setLjf(fyje);
                yyQfmx.setLjfdj(fydj);
                yyQfmx.setSl(fysl);
                yyQfmx.setYsljf(fyje);
            } else if (fylxName.contains(BcFylxEnum.XFSF.getName())) {
                yyQfmx.setYsqt(fyje);
                yyQfmx.setSl(BigDecimal.ZERO);
            } else if (fylxName.contains(BcFylxEnum.ECJYF.getName())) {
                yyQfmx.setSl(fysl);
                yyQfmx.setEcjyfdj(fydj);
                yyQfmx.setEcjyf(fyje);
                yyQfmx.setYsecjyf(fyje);
            } else if (fylxName.contains(BcFylxEnum.FJF.getName())) {
                yyQfmx.setSl(fysl);
                yyQfmx.setFjfdj(fydj);
                yyQfmx.setFjf(fyje);
                yyQfmx.setYsfjf(fyje);
            }
            yyQfmx.setYsje(fyje);

            yyQfmx.setLrrybm(String.valueOf(SecurityUtils.getUserId()));
            yyQfmx.setLrryxm(user.getRealName());
            yyQfmx.setCbrybm(String.valueOf(SecurityUtils.getUserId()));
            yyQfmx.setCbryxm(user.getRealName());
            yyQfmx.setLrrq(new Date());
            yyQfmx.setGdzt("4");
            this.save(yyQfmx);

            YyBgLog yyBgLog = new YyBgLog();
            yyBgLog.setBglx(BglxEnum.FYLRLOG.getValue());
            yyBgLog.setBgqjson(JSONObject.toJSONString(e));//费用录入json
            String format = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            String bgnr = String.format("费用调整，用户编号%s-财务日期%s，调整日期：%s 调整人：%s", e.getYhbh(), e.getCwrq(), format, user.getRealName());
            yyBgLog.setBgnr(bgnr);
            yyBgLog.setGdzt("4");
            yyBgLogService.bglogsave(yyBgLog);

            //  yyBgLogService.lambdaUpdate().eq(YyBgLog::getId, e.getLogid()).set(YyBgLog::getBglxid, yyQfmx.getId()).set(YyBgLog::getBgqjson, JSONObject.toJSONString(e)).set(YyBgLog::getBghjson, JSONObject.toJSONString(yyQfmx)).set(YyBgLog::getGdzt, "4").update();
            return yyQfmx.getId();
        } else {
            YyBgLog yyBgLog = new YyBgLog();
            yyBgLog.setBglx(BglxEnum.FYLRLOG.getValue());
            yyBgLog.setBgqjson(JSONObject.toJSONString(e));//费用录入json
            String format = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            String bgnr = String.format("费用调整，用户编号%s-财务日期%s，调整日期：%s 调整人：%s", e.getYhbh(), e.getCwrq(), format, user.getRealName());
            yyBgLog.setBgnr(bgnr);
            yyBgLog.setGdzt("1");
            yyBgLogService.bglogsave(yyBgLog);
            return yyBgLog.getId();
        }
    }

    private void fytzCheckParam(fylrDto e) {
        if (StringUtil.isEmpty(e.getYhbh())) {
            throw new FeesException("用户编号不能为空！", FeesErrorCode.BUSINESS_ERROR);
        }
        if (StringUtil.isEmpty(e.getYhxm())) {
            throw new FeesException("用户姓名不能为空！", FeesErrorCode.BUSINESS_ERROR);
        }
        if (StringUtil.isEmpty(e.getCwrq())) {
            throw new FeesException("财务日期不能为空！", FeesErrorCode.BUSINESS_ERROR);
        }
        if (StringUtil.isEmpty(e.getFylx())) {
            throw new FeesException("费用类型不能为空！", FeesErrorCode.BUSINESS_ERROR);
        }
        if (StringUtil.isEmpty(e.getJyType())) {
            throw new FeesException("减免类型不能为空！", FeesErrorCode.BUSINESS_ERROR);
        }
        if (e.getFyje().compareTo(BigDecimal.ZERO) == 0) {
            throw new FeesException("费用金额不能等于零！", FeesErrorCode.BUSINESS_ERROR);
        }
    }

    @Override
    public PageResult<YyQfmxFytzSelect> fytzpage(PageDto pageDto, FytzFilter filter) {
        //return this.baseMapper.fytzpage(pageDto, filter).toVo();
        PageResult<Map> mapPageResult = this.baseMapper.fytzpage2(pageDto, filter).toVo();

        List<BmFylx> bmFylxList = bmFylxService.list();

        long total = mapPageResult.getTotal();
        List<Map> records = mapPageResult.getRecords();
        if (CollectionUtil.isEmpty(records)) {
            return new PageResult<>(0, new ArrayList<>());
        }

        List<YyQfmxFytzSelect> collect = records.stream().map(e -> {
            Clob clob = (Clob) e.get("bgqjson");
            String bgqjson;
            try {
                bgqjson = clob.getSubString(1, (int) clob.length());
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }

            YyQfmxFytzSelect yyQfmxFytzSelect = JSONObject.parseObject(bgqjson, YyQfmxFytzSelect.class);
            if (StringUtil.isNotNull(e.get("lrry"))) {
                yyQfmxFytzSelect.setLrry(e.get("lrry").toString());
            }

            if (StringUtil.isNotNull(e.get("lrrq"))) {
                yyQfmxFytzSelect.setLrrq((Date) e.get("lrrq"));
            }

            if (StringUtil.isNotNull(e.get("gdzt"))) {
                yyQfmxFytzSelect.setGdzt(e.get("gdzt").toString());
            }

            yyQfmxFytzSelect.setLogid(e.get("logid").toString());
            if (StringUtil.isNotNull(yyQfmxFytzSelect)) {
                BmFylx bmFylx = bmFylxList.stream().filter(item -> item.getCode().equals(yyQfmxFytzSelect.getFylx())).findFirst().orElse(null);
                if (StringUtil.isNotNull(bmFylx)) {
                    yyQfmxFytzSelect.setFymc(bmFylx.getName());
                }
            }
            return yyQfmxFytzSelect;
        }).collect(Collectors.toList());


        return new PageResult<>(total, collect);
    }

    @Override
    public List<Map> getqfsjmx(String qfid) {
        if (StringUtil.isEmpty(qfid)) {
            throw new FeesException("欠费ID不能为空！", FeesErrorCode.BUSINESS_ERROR);
        }
        if (this.count(new QueryWrapper<YyQfmx>().lambda().eq(YyQfmx::getId, qfid)) == 0) {
            throw new FeesException("未查询到响应欠费明细！", FeesErrorCode.BUSINESS_ERROR);
        }
        return this.baseMapper.getqfsjmx(qfid);
    }

    @Override
    public YyQfmx createHp(YyQfmx yyQfmx, Date chsj) {
        YyQfmx hp = new YyQfmx();
        Set<String> negateKeys = new LinkedHashSet<>();

        for (int i = 0; i < 4; i++) {
            negateKeys.add(i == 0 ? "sl" : "sl" + i);
            negateKeys.add(i == 0 ? "ljf" : "ljf" + i);
            negateKeys.add(i == 0 ? "wsf" : "wsf" + i);
            negateKeys.add(i == 0 ? "szyf" : "szyf" + i);
            negateKeys.add(i == 0 ? "sf" : "sf" + i);
        }
        for (int i = 0; i < 3; i++) {
            for (int j = 1; j < 5; j++) {
                negateKeys.add(i == 0 ? String.format("jt%ssl", j) : String.format("sj%sJt%ssl", i, j));
                negateKeys.add(i == 0 ? String.format("jt%ssf", j) : String.format("sj%sJt%ssf", i, j));
            }
            negateKeys.add(i == 0 ? "ecjyf" : "ecjyf" + i);
            negateKeys.add(i == 0 ? "fjf" : "fjf" + i);
        }

        negateKeys.add("znj");
        negateKeys.add("yssl");
        negateKeys.add("yssf");
        negateKeys.add("yswsf");
        negateKeys.add("ysljf");
        negateKeys.add("ysszyf");
        negateKeys.add("ysqt");
        negateKeys.add("ysecjyf");
        negateKeys.add("ysfjf");
        negateKeys.add("ysje");

        List<String> ignoreProperties = new ArrayList<>();
        ignoreProperties.addAll(Arrays.asList("id", "chbz", "sfbc", "kpbz", "kprq", "shry", "lockbz", "eiSgkpId", "taxrate", "bz"));
        ignoreProperties.addAll(negateKeys);

        BeanUtils.copyProperties(yyQfmx, hp, ignoreProperties.toArray(new String[ignoreProperties.size()]));

        hp.setChid(yyQfmx.getId());
        hp.setChsj(chsj);
        hp.setJsrq(chsj);
        hp.setLrrq(chsj);
        hp.setChlx("0");
        hp.setChbz(PjztEnum.冲红记录.getValue());

        negateKeys.forEach(name -> populateNegateValue(yyQfmx, name, hp));

        hp.setChrybm(String.valueOf(SecurityUtils.getUserId()));
        hp.setChryxm(SecurityUtils.getUser().getRealName());
        hp.setCwrq(gdcsbService.selectCwrq());

        return hp;
    }

    public String getFirstCwrq(String qflsbh) {
        return this.baseMapper.getFirstCwrq(qflsbh);
    }

    private void populateNegateValue(YyQfmx from, String name, YyQfmx to) {
        Object value = null;
        try {
            value = PropertyUtils.getProperty(from, name);
            if (value != null) {
                if (value instanceof BigDecimal) {
                    PropertyUtils.setProperty(to, name, ((BigDecimal) value).negate());
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    private List<BmSj> getSjMap() {
        return sjService.list().stream().collect(Collectors.toList());
    }

    /**
     * 水费及附加费计算
     *
     * @param cbkxx 抄表卡信息
     * @param ljsl  累积水量（非阶梯时与本次水量相同）
     * @param bcsl  本次水量
     */
    private SfJsJg sfJs0(YhCbkxx cbkxx, YhKhjbxx yhxx, BigDecimal ljsl, BigDecimal bcsl) throws Exception {
        SfJsJg sfJsJg = new SfJsJg();
        sfJsJg.setRks(yhxx.getRks().toString());
        //判断用户是否是低保户并且月累计量是否大于配置
        if (StringUtil.isNotEmpty(yhxx.getKhlb()) && yhxx.getKhlb().equals("2")) {
            String cwrq = gdcsbService.selectCwrq();
            String year = cwrq.substring(0, cwrq.length() - 2);
            String month = cwrq.substring(cwrq.length() - 2);
            BmDbhysyh bmDbhysyh = bmDbhysyhService.lambdaQuery()
                    .eq(BmDbhysyh::getIsdisabled, "1")
                    .eq(BmDbhysyh::getYear, year)
                    .eq(BmDbhysyh::getSdys, Integer.parseInt(month))
                    .one();
            BigDecimal dbhsdsl = bmDbhysyh.getSdsl();
            if (yhxx.getDbhndljl().compareTo(dbhsdsl) < 0) {
                BigDecimal yhsl;
                BigDecimal syyhsl = dbhsdsl.subtract(yhxx.getDbhndljl());
                if (bcsl.compareTo(syyhsl) > 0) {
                    yhsl = syyhsl;
                    bcsl = bcsl.subtract(syyhsl);
                } else {
                    yhsl = bcsl;
                    bcsl = BigDecimal.ZERO;
                    sfJsJg.setSfbz("4");
                }
                sfJsJg.setJyType("2");
                sfJsJg.setIsYh("1");
                sfJsJg.setYhsl(yhsl);
            }
        }

        String cbkid = cbkxx.getCbkid();
        Date now = new Date();
        sfJsJg.setJsrq(now);
        Map<String, BigDecimal> ljslMap = new HashMap<>();

        TreeMap<String, String> slMap = getSlMap(cbkxx, bcsl);

        Map<String, Object> values = new LinkedHashMap<>();
        slMap.forEach((key, value) -> {
            if (key.equals("L0") || key.equals("L1")) {
                String sjTag = "";
                String sjTag2 = "";
                Map<String, Object> values1 = getValues(value, ljsl, sjTag, sjTag2, cbkxx, yhxx);
                if (values1.containsKey("ljsl")) {
                    ljslMap.put("ljsljsh", (BigDecimal) values1.get("ljsl"));
                }
                values.putAll(values1);
            } else if (key.equals("L2")) {
                String sjTag = "sj1";
                String sjTag2 = "1";
                Map<String, Object> values1 = getValues(value, ljsl, sjTag, sjTag2, cbkxx, yhxx);
                if (values1.containsKey("ljsl")) {
                    ljslMap.put("ljsljsh", (BigDecimal) values1.get("ljsl"));
                }
                values.putAll(values1);

            } else if (key.equals("L3")) {
                String sjTag = "sj2";
                String sjTag2 = "2";
                Map<String, Object> values1 = getValues(value, ljsl, sjTag, sjTag2, cbkxx, yhxx);
                if (values1.containsKey("ljsl")) {
                    ljslMap.put("ljsljsh", (BigDecimal) values1.get("ljsl"));
                }
                values.putAll(values1);
            }
        });

        List<BigDecimal> sls = getMxValues(values, "sl");
        List<BigDecimal> sfs = getMxValues(values, "sf");
        List<BigDecimal> wsfs = getMxValues(values, "wsf");
        List<BigDecimal> ljfs = getMxValues(values, "ljf");
        List<BigDecimal> szyfs = getMxValues(values, "szyf");//水资源费
        List<BigDecimal> ecjyfs = getMxValues(values, "ecjyf");
        List<BigDecimal> fjfs = getMxValues(values, "fjf");
        List<BigDecimal> xfsfs = getMxValues(values, "xfsf");

        BigDecimal yssl = sls.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal yssf = sfs.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal yswsf = wsfs.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal ysljf = ljfs.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal ysszyf = szyfs.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal ysecjyf = ecjyfs.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal ysfjf = fjfs.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal ysxfsf = xfsfs.stream().reduce(BigDecimal.ZERO, BigDecimal::add);

        try {
            org.apache.commons.beanutils.BeanUtils.populate(sfJsJg, values);
            CbjsfsEnum cbjsfs = getCbjsfs(slMap, values);//抄表计算方式（0正常单价，1一表多价，2阶梯,3 一表多价含阶梯；用于判断计价类型，处理显示水价）
            sfJsJg.setCbjsbz(cbjsfs.getValue());
            sfJsJg.setCbjsfs(cbjsfs.name());
            sfJsJg.setJtzqljlJsq(ljsl);
            sfJsJg.setJtzqljl(ljslMap.getOrDefault("ljsljsh", BigDecimal.ZERO));
            sfJsJg.setYssl(yssl);
            sfJsJg.setYssf(yssf);
            sfJsJg.setYsljf(ysljf);//垃圾费按月收取或按量收取
            sfJsJg.setYsszyf(ysszyf);//应收水资源费
            sfJsJg.setYswsf(yswsf);
            sfJsJg.setYsqt(ysxfsf);
            sfJsJg.setYsfjf(ysfjf);
            sfJsJg.setYsecjyf(ysecjyf);
            sfJsJg.setYsje(yssf.add(ysljf).add(yswsf).add(ysszyf).add(ysecjyf).add(ysfjf).add(ysxfsf));
        } catch (Exception e) {
            log.error("月末结转水费、附加费计算失败 ===============> ");
            throw e;
        }
        log.info("{}:{}", cbkid, values);
        return sfJsJg;
    }

    /**
     * 抄表正常计算
     *
     * @param slMap
     * @param values
     * @return
     */
    private CbjsfsEnum getCbjsfs(TreeMap<String, String> slMap, Map<String, Object> values) {
        CbjsfsEnum cbjsfs = CbjsfsEnum.正常单价计费;
        if (slMap.containsKey("L0")) {
            String sjjtbz = (String) values.get("sjjtbz");
            if (sjjtbz.equals("0")) {
                cbjsfs = CbjsfsEnum.正常单价计费;
            } else {
                cbjsfs = CbjsfsEnum.阶梯计费;
            }
//            Set<String> keys = values.keySet();
//            List<String> jt = keys.stream().filter(e -> e.contains("jt")).collect(Collectors.toList());
//            if (jt.isEmpty()) {
//                cbjsfs = CbjsfsEnum.正常单价计费;
//            } else {
//                cbjsfs = CbjsfsEnum.阶梯计费;
//            }
        } else if (slMap.containsKey("L1")) {
            cbjsfs = CbjsfsEnum.一表多价计费;
            for (long i = 0; i <= 2; i++) {
                String Tag = "sjjtbz";
                if (i != 0) {
                    Tag = String.format("sjjtbz%s", i);
                }
                if (values.containsKey(Tag)) {
                    String sjjtbz = (String) values.get(Tag);
                    if (sjjtbz.equals("0")) {
                        cbjsfs = CbjsfsEnum.一表多价计费;
                    } else {
                        cbjsfs = CbjsfsEnum.一表多价含阶梯;
                    }
                }
            }
//            Set<String> keys = values.keySet();
//            List<String> jt = keys.stream().filter(e -> e.contains("Jt")).collect(Collectors.toList());
//            if (jt.isEmpty()) {
//                cbjsfs = CbjsfsEnum.一表多价计费;
//            } else {
//                cbjsfs = CbjsfsEnum.一表多价含阶梯;
//            }
        }
        return cbjsfs;
    }

    /**
     * 明细值
     *
     * @param values
     * @param prefix
     * @return
     */
    private List<BigDecimal> getMxValues(Map<String, Object> values, String prefix) {
        List<BigDecimal> mxValues = new ArrayList<>();

        for (int i = 0; i < 4; i++) {
            String key;
            if (i == 0) {
                key = String.format("%s", prefix);
            } else {
                key = String.format("%s%s", prefix, i);
            }

            if (values.containsKey(key)) {
                mxValues.add((BigDecimal) values.getOrDefault(key, BigDecimal.ZERO));
            }
        }
        return mxValues;
    }

    /**
     * @param sjsl   水量
     * @param ljsl   累计水量
     * @param sjTag1 水价标签1
     * @param sjTag2 水价标签2
     * @param cbkxx  抄表卡号信息
     * @return
     */
    private Map<String, Object> getValues(String sjsl, BigDecimal ljsl, String sjTag1, String sjTag2, YhCbkxx cbkxx, YhKhjbxx yhxx) {
        String wsfbz = cbkxx.getWsfbz();
        String ljfbz = cbkxx.getLjfbz();
        String szyfbz = cbkxx.getSzyfbz();

        String[] values = sjsl.split("_");
        String sjbm = values[0];
        BigDecimal sl = new BigDecimal(values[1]);
        Sjmx sjmx = sfjs(sl, sjbm, ljsl, yhxx);
        Map<String, Object> map = new LinkedHashMap<>();
        String prefix = "";
        String suffix = sjTag2;
        map.put(String.format("%s%s%s", prefix, "sjbm", suffix), sjbm);
        Sjmx.Jtmx jtmx = sjmx.getJtmx();

        // 水费计算(阶梯/非阶梯)
        if (jtmx != null) {//非阶梯水价
            prefix = sjTag1;
            suffix = sjTag2;
            map.put(String.format("%s%s%s", prefix, "sl", suffix), jtmx.getSl());
            map.put(String.format("%s%s%s", prefix, "sj", suffix), jtmx.getSj());
            map.put(String.format("%s%s%s", prefix, "sf", suffix), jtmx.getSf());

            prefix = "";
            suffix = sjTag2;
            map.put(String.format("%s%s%s", prefix, "sl", suffix), jtmx.getSl());
            map.put(String.format("%s%s%s", prefix, "sj", suffix), jtmx.getSj());
            map.put(String.format("%s%s%s", prefix, "sf", suffix), jtmx.getSf());
            map.put(String.format("%s%s", "sjjtbz", suffix), "0");
        } else {
            map.put(String.format("%s%s", "sjjtbz", suffix), "1");
            Sjmx.Jtmx jtmx1 = sjmx.getJtmx1();
            BigDecimal zsl = BigDecimal.ZERO;
            BigDecimal zsf = BigDecimal.ZERO;
            if (jtmx1 != null) {
                prefix = "jt1";
                if (StringUtils.isNotBlank(sjTag1)) prefix = sjTag1 + "Jt1";
                suffix = "";
                BigDecimal sl1 = jtmx1.getSl();
                zsl = zsl.add(sl1);
                map.put(String.format("%s%s%s", prefix, "sl", suffix), sl1);
                map.put(String.format("%s%s%s", prefix, "sj", suffix), jtmx1.getSj());
                BigDecimal sf = jtmx1.getSf();
                zsf = zsf.add(sf);
                map.put(String.format("%s%s%s", prefix, "sf", suffix), sf);
            }
            Sjmx.Jtmx jtmx2 = sjmx.getJtmx2();
            if (jtmx2 != null) {
                prefix = "jt2";
                if (StringUtils.isNotBlank(sjTag1)) prefix = sjTag1 + "Jt2";
                suffix = "";
                BigDecimal sl1 = jtmx2.getSl();
                zsl = zsl.add(sl1);
                map.put(String.format("%s%s%s", prefix, "sl", suffix), sl1);
                map.put(String.format("%s%s%s", prefix, "sj", suffix), jtmx2.getSj());
                BigDecimal sf = jtmx2.getSf();
                zsf = zsf.add(sf);
                map.put(String.format("%s%s%s", prefix, "sf", suffix), sf);
            }
            Sjmx.Jtmx jtmx3 = sjmx.getJtmx3();
            if (jtmx3 != null) {
                prefix = "jt3";
                if (StringUtils.isNotBlank(sjTag1)) prefix = sjTag1 + "Jt3";
                suffix = "";
                BigDecimal sl1 = jtmx3.getSl();
                zsl = zsl.add(sl1);
                map.put(String.format("%s%s%s", prefix, "sl", suffix), sl1);
                map.put(String.format("%s%s%s", prefix, "sj", suffix), jtmx3.getSj());
                BigDecimal sf = jtmx3.getSf();
                zsf = zsf.add(sf);
                map.put(String.format("%s%s%s", prefix, "sf", suffix), sf);
            }
            Sjmx.Jtmx jtmx4 = sjmx.getJtmx4();
            if (jtmx4 != null) {
                prefix = "jt4";
                if (StringUtils.isNotBlank(sjTag1)) prefix = sjTag1 + "Jt4";
                suffix = "";
                BigDecimal sl1 = jtmx4.getSl();
                zsl = zsl.add(sl1);
                map.put(String.format("%s%s%s", prefix, "sl", suffix), sl1);
                map.put(String.format("%s%s%s", prefix, "sj", suffix), jtmx4.getSj());
                BigDecimal sf = jtmx4.getSf();
                zsf = zsf.add(sf);
                map.put(String.format("%s%s%s", prefix, "sf", suffix), sf);
            }
            prefix = "";
            suffix = sjTag2;
            map.put(String.format("%s%s%s", prefix, "sl", suffix), zsl);
            map.put(String.format("%s%s%s", prefix, "sf", suffix), zsf);
        }

        //其它费用计算
        BmSj bmSj = sjCache.get(sjbm);
        if (bmSj != null) {
            if (ObjUtil.isNotNull(bmSj.getJtjslx()) && (bmSj.getJtjslx().equals(JtjslxEnum.年阶梯)
                    || bmSj.getJtjslx().equals(JtjslxEnum.月阶梯))) {
                map.put("ljsl", ljsl.add(sl));
            }

            prefix = "";
            suffix = sjTag2;
            BigDecimal wsfdj = bmSj.getWsfdj();
            BigDecimal ljfdj = bmSj.getLjfdj();
            BigDecimal szyfdj = bmSj.getSzyfdj();
            BigDecimal ecjyfdj = new BigDecimal("0.1");

            map.put(String.format("%s%s%s", prefix, "wsfdj", suffix), wsfdj);
            map.put(String.format("%s%s%s", prefix, "szyfDj", suffix), szyfdj);
            map.put(String.format("%s%s%s", prefix, "ecjyfdj", suffix), ecjyfdj);

            // 二次加压费
            if (cbkxx.getEcjybz() != null && cbkxx.getEcjybz().equals("1")) {
                BigDecimal ecjyf = fyjs(sl, ecjyfdj);
                map.put(String.format("%s%s%s", prefix, "ecjyf", suffix), ecjyf);
            }

//            // 附加费
//            if (cbkxx.getFjf() != null && cbkxx.getFjf().compareTo(BigDecimal.ZERO) > 0) {
//                if (StringUtil.isEmpty(sjTag1) && StringUtil.isEmpty(sjTag2)) {
//                    BigDecimal fjf = cbkxx.getFjf();
//                    map.put(String.format("%s%s%s", prefix, "fjf", suffix), fjf);
//                    map.put(String.format("%s%s%s", prefix, "fjfdj", suffix), fjf);
//                }
//            }
//
//            // 消防栓费
//            if (cbkxx.getXfsf() != null && cbkxx.getXfsf().compareTo(BigDecimal.ZERO) > 0) {
//                if (StringUtil.isEmpty(sjTag1) && StringUtil.isEmpty(sjTag2)) {
//                    BigDecimal xfsf = cbkxx.getXfsf();
//                    map.put(String.format("%s%s%s", prefix, "xfsf", suffix), xfsf);
//                }
//            }

            // 污水费
            if ("1".equals(wsfbz)) {
                BigDecimal wsf = fyjs(sl, wsfdj);
                map.put(String.format("%s%s%s", prefix, "wsf", suffix), wsf);
            }

            // 垃圾费
            if ("1".equals(ljfbz) && sl.compareTo(BigDecimal.ZERO) > 0) {
                //按量收取垃圾费
                if (cbkxx.getLjffs().equals("1")) {
                    map.put(String.format("%s%s%s", prefix, "ljfdj", suffix), ljfdj);
                    BigDecimal ljf = fyjs(sl, ljfdj);
                    map.put(String.format("%s%s%s", prefix, "ljf", suffix), ljf);
                } else {
                    BigDecimal num = BigDecimal.ONE;
                    //判断总分表或子母表是否存在
                    if (zbFbsCache.size() > 0 && zbFbsCache.containsKey(cbkxx.getCbkid())) {
                        num = zbFbsCache.get(cbkxx.getCbkid());
                        //判断子表数或者分表数是否为0，为零按单户处理
                        if (BigDecimal.ZERO.compareTo(num) == 0) {
                            num = BigDecimal.ONE;
                        }
                    }
                    //按户收取垃圾费是只需要算一次
                    if (StringUtil.isEmpty(sjTag1) && StringUtil.isEmpty(sjTag2)) {
                        map.put(String.format("%s%s%s", prefix, "ljfdj", suffix), cbkxx.getLjfje());
                        BigDecimal ljf = cbkxx.getLjfje().multiply(num);
                        map.put(String.format("%s%s%s", prefix, "ljf", suffix), ljf);
                    }
                }
            }

            // 水资源费
            if (szyfdj != null && szyfdj.compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal szyf = fyjs(sl, szyfdj);
                map.put(String.format("%s%s%s", prefix, "szyf", suffix), szyf);
            }
        }

        return map;
    }

    private final static Map<String, BmSj> sjCache = new HashMap<>();//水价缓存

    private final static Map<String, BigDecimal> zbFbsCache = new HashMap<>();//缓存总表的分表数与母表的子表数

    private void sjCache() {
        sjCache.clear();
        List<BmSj> sjs = sjService.lambdaQuery().list();
        sjs.forEach(sj -> sjCache.put(sj.getCode(), sj));
    }

    private void zbFbsCache() {
        zbFbsCache.clear();
        Map<String, BigDecimal> zbFbs = cblrService.getZbFbs();
        zbFbs.forEach((k, v) -> zbFbsCache.put(k, v));
    }


    /**
     * [莱阳费用]
     * 算费：费用 = 基础水费+水资源费+垃圾费+污水费处理+附加费+二次加压费+消防栓费
     */
    private int sf(List<YyCblr> cblrs) {
        cblrs = cblrs.stream()
                .filter(e -> e.getCbbz() == CbbzEnum.已抄表)
                .filter(e -> e.getShbz() == ShbzEnum.审核通过)
                .filter(e -> e.getJsbz() == JsbzEnum.未算费)
                .filter(e -> e.getSl() != null && e.getSl().compareTo(BigDecimal.ZERO) >= 0)
                .collect(Collectors.toList());

        if (cblrs.isEmpty()) {
            return 0;
        }

        Map<String, YyCblr> cblrMap = cblrs.stream()
                .collect(Collectors.toMap(e -> e.getCbkid(), e -> e, (u1, u2) -> u1, LinkedHashMap::new));

        if (cblrMap.isEmpty()) {
            return 0;
        }

        ThreadPoolExecutor processexecutor = new ThreadPoolExecutor(
                Runtime.getRuntime().availableProcessors() * 2,
                Runtime.getRuntime().availableProcessors() * 4,
                60L, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(2000),
                new ThreadPoolExecutor.CallerRunsPolicy());
        try {
            // 初始化缓存
            sjCache();
            zbFbsCache();

            List<BmCbb> bmCbbs = cbbService.list();
            if (CollUtil.isEmpty(bmCbbs)) {
                throw new FeesException("未配置抄表本信息", FeesErrorCode.BUSINESS_ERROR);
            }

            Map<String, BmCbb> cbbMap = bmCbbs.stream().collect(Collectors.toMap(BmCbb::getCbbbm, o -> o));

            TransactionTemplate nestedTemplate = new TransactionTemplate(transactionManager);
            nestedTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED);
            // 并行处理算费逻辑
            List<CompletableFuture<Integer>> processfutures = cblrMap.entrySet().parallelStream()
                    .map(entry -> CompletableFuture.supplyAsync(() -> {
                        String cbkid = entry.getKey();
                        YyCblr cblr = entry.getValue();
                        String lockKey = "FEE_LOCK_CBKID:" + cbkid;
                        RLock lock = redissonClient.getLock(lockKey);
                        return nestedTemplate.execute(status -> {
                            try {
                                // 尝试获取锁：最多等1秒，持有60秒
                                boolean lockSuccess = lock.tryLock(1, 60, TimeUnit.SECONDS);
                                if (!lockSuccess) {
                                    // 未获取到锁 = 已被其他线程处理 → 跳过
                                    return 1;
                                }
                                //双重排除已算费数据
                                YyCblr lockRow = cblrService.lambdaQuery()
                                        .select(YyCblr::getCbkid)
                                        .eq(YyCblr::getCbkid, cbkid)
                                        .eq(YyCblr::getJsbz, JsbzEnum.未算费)
                                        .one();
                                if (lockRow == null) {
                                    return 1;
                                }
                                // 主键查询
                                YhCbkxx cbkxx = cbkxxService.getById(cbkid);
                                if (cbkxx == null) {
                                    return 0;
                                }
                                String yhbh = cbkxx.getYhbh();
                                YhKhjbxx yhxx = khjbxxService.getById(yhbh);
                                if (yhxx == null) {
                                    return 0;
                                }
                                // 消防通表不做计费
                                String xftbh = cbkxx.getXftbh();
                                if (StrUtil.isNotEmpty(xftbh)) {
                                    cblrService.updateJsbz(cbkid);
                                    return 1;
                                }
                                BigDecimal sjsl = cblr.getSl();

                                YyQfmx yyQfmx = new YyQfmx();
                                yyQfmx.setQflsbh(GuidGenerator.getQflsbh());
                                yyQfmx.setKhbm(yhxx.getKhbm());
                                BigDecimal cbkxxXfsf = cbkxx.getXfsf();

                                if (sjsl.compareTo(BigDecimal.ZERO) == 0 && cbkxxXfsf.compareTo(BigDecimal.ZERO) == 0) {
                                    BeanUtils.copyProperties(yhxx, yyQfmx, NumberHelper.getNullPropertyNames(yhxx));
                                    BeanUtils.copyProperties(cblr, yyQfmx, NumberHelper.getNullPropertyNames(cblr));
                                    yyQfmx.setSfbz("4");
                                    yyQfmx.setJsrq(new Date());
                                    if (StringUtil.isNotEmpty(cbkxx.getSjbm())) {
                                        yyQfmx.setSjbm(cbkxx.getSjbm());
                                    }
                                    if (StringUtil.isNotEmpty(cbkxx.getSjbm1())) {
                                        yyQfmx.setSjbm1(cbkxx.getSjbm1());
                                    }
                                    if (StringUtil.isNotEmpty(cbkxx.getSjbm1())) {
                                        yyQfmx.setSjbm2(cbkxx.getSjbm2());
                                    }
                                    yyQfmx.setJtzqljlJsq(yhxx.getJtzqljl());
                                } else {
                                    // 水费计算
                                    SfJsJg sfJsJg = sfJs(cbkxx, yhxx, sjsl);
                                    BeanUtils.copyProperties(yhxx, yyQfmx, NumberHelper.getNullPropertyNames(yhxx));
                                    BeanUtils.copyProperties(cblr, yyQfmx, "sl");
                                    BeanUtils.copyProperties(sfJsJg, yyQfmx, NumberHelper.getNullPropertyNames(sfJsJg));
                                }

                                if (cblr.getCbcs().compareTo(BigDecimal.ONE) == 0) {
                                    // 附加费
                                    if (cbkxx.getFjf() != null && cbkxx.getFjf().compareTo(BigDecimal.ZERO) > 0) {
                                        BigDecimal fjf = cbkxx.getFjf();
                                        yyQfmx.setYsfjf(fjf);
                                        yyQfmx.setFjf(fjf);
                                        yyQfmx.setFjfdj(fjf);
                                    }
                                    // 消防栓费
                                    if (cbkxxXfsf != null && cbkxxXfsf.compareTo(BigDecimal.ZERO) > 0) {
                                        BigDecimal xfsf = cbkxx.getXfsf();
                                        yyQfmx.setYsqt(xfsf);
                                    }
                                    yyQfmx.setYsje(yyQfmx.getYsje().add(yyQfmx.getYsfjf()).add(yyQfmx.getYsqt()));
                                }
                                yyQfmx.setSfbc("0");
                                yyQfmx.setFylx(BcFylxEnum.Zhfy.getValue().toString());
                                yyQfmx.setFylxmc(BcFylxEnum.Zhfy.getName());
                                //yyQfmx.setYsyf(new SimpleDateFormat("yyyyMM").format(cblr.getCbrq()));
                                yyQfmx.setYsyf(ymjzConfigService.getCwrq(cblr.getCbrq()));
                                yyQfmx.setChbz(PjztEnum.正常.getValue());

                                BmCbb bmCbb = cbbMap.get(cblr.getSscbb());
                                if (StringUtil.isNotNull(bmCbb)) {
                                    yyQfmx.setQyfzrbm(bmCbb.getQyfzr());
                                    yyQfmx.setQyfzrxm(bmCbb.getQyfzrxm());
                                }

                                this.save(yyQfmx);

                                cblrService.updateJsbz(cbkid);
                                return 1;
                            } catch (Exception e) {
                                log.error("抄表卡id[" + cbkid + "]抄表计划算费失败 ====================>", e);
                                status.setRollbackOnly();
                                return 0;
                            }
                        });
                    }, processexecutor))
                    .collect(Collectors.toList());

            CompletableFuture.allOf(processfutures.toArray(new CompletableFuture[0])).join();
            return processfutures.stream().mapToInt(CompletableFuture::join).sum();
        } finally {
            processexecutor.shutdown();
        }
    }

    private Map<String, YhKhjbxx> getYhMap(Set<String> yhbhs) {
        if (CollectionUtil.isEmpty(yhbhs)) {
            return new HashMap<>();
        }

        List<List<String>> lists = Lists.partition(new ArrayList<>(yhbhs), 1000);
        List<YhKhjbxx> yhs = new ArrayList<>();
        for (List<String> yhbhs1 : lists) {
            LambdaQueryWrapper<YhKhjbxx> yhKhjbxxQueryWrapper = new LambdaQueryWrapper<>();
            yhKhjbxxQueryWrapper.select(YhKhjbxx::getYhxm, YhKhjbxx::getYhbh, YhKhjbxx::getKhlb, YhKhjbxx::getDbhndljl, YhKhjbxx::getJtzqljl, YhKhjbxx::getRks, YhKhjbxx::getKhbm);
            yhKhjbxxQueryWrapper.in(YhKhjbxx::getYhbh, yhbhs1);
            yhs.addAll(khjbxxService.list(yhKhjbxxQueryWrapper));
        }
        if (CollectionUtil.isEmpty(yhs)) {
            return new HashMap<>();
        }

        return yhs.stream().collect(Collectors.toMap(YhKhjbxx::getYhbh, e -> e));
    }

    /**
     * 水费计算(含阶梯运算)
     */
    private Sjmx sfjs(BigDecimal sl, String sjbm, BigDecimal ljsl, YhKhjbxx yhKhjbxx) {
        BmSj bmSj = sjCache.get(sjbm);
        if (bmSj == null) {
            throw new FeesException("水价编码不存在", FeesErrorCode.BUSINESS_ERROR);
        }

        String jtbz = bmSj.getJtbz();

        if ("1".equals(jtbz)) {
            Long rks = yhKhjbxx.getRks();
            BigDecimal rksqs = StringUtil.isNull(bmSj.getJtrkjs()) ? BigDecimal.ZERO : bmSj.getJtrkjs();//人口数起数
            BigDecimal jtzl = StringUtil.isNull(bmSj.getJtrksl()) ? BigDecimal.ZERO : bmSj.getJtrksl();//阶梯增量
            BigDecimal jtZszl = BigDecimal.ZERO;//阶梯止数增量


            if (rks != null && rks > 0) {
                if (BigDecimal.valueOf(rks).compareTo(rksqs) > 0) {
                    jtZszl = BigDecimal.valueOf(rks).subtract(rksqs).multiply(jtzl);
                }
            }
            Sjmx.Jtmx jtmx1 = null;
            Sjmx.Jtmx jtmx2 = null;
            Sjmx.Jtmx jtmx3 = null;
            Sjmx.Jtmx jtmx4 = null;
            BigDecimal yssl = BigDecimal.ZERO;
            BigDecimal yssf = BigDecimal.ZERO;

            BigDecimal jt1Zs = bmSj.getJt1Zs();
            BigDecimal jt1Sj = bmSj.getJt1Sj();
            BigDecimal sjJtZs = BigDecimal.ZERO;
            if (isEnabled(jt1Zs)) {
                jtmx1 = getJtSf(sl, jt1Zs.add(jtZszl), jt1Sj, sjJtZs, ljsl);
                sjJtZs = jt1Zs;
                yssl = yssl.add(jtmx1.getSl());
                yssf = yssf.add(jtmx1.getSf());
            }

            BigDecimal jt2Zs = bmSj.getJt2Zs();
            BigDecimal jt2Sj = bmSj.getJt2Sj();
            if (isEnabled(jt2Zs) && isEnabled(jt1Zs)) {
                jtmx2 = getJtSf(sl, jt2Zs.add(jtZszl), jt2Sj, sjJtZs.add(jtZszl), ljsl);
                sjJtZs = jt2Zs;
                yssl = yssl.add(jtmx2.getSl());
                yssf = yssf.add(jtmx2.getSf());
            }

            BigDecimal jt3Zs = bmSj.getJt3Zs();
            BigDecimal jt3Sj = bmSj.getJt3Sj();
            if (isEnabled(jt3Zs) && isEnabled(jt2Zs)) {
                jtmx3 = getJtSf(sl, jt3Zs.add(jtZszl), jt3Sj, sjJtZs.add(jtZszl), ljsl);
                sjJtZs = jt3Zs;
                yssl = yssl.add(jtmx3.getSl());
                yssf = yssf.add(jtmx3.getSf());
            }

            BigDecimal jt4Zs = bmSj.getJt4Zs();
            BigDecimal jt4Sj = bmSj.getJt4Sj();
            if (isEnabled(jt4Zs) && isEnabled(jt3Zs)) {
                jtmx4 = getJtSf(sl, jt4Zs.add(jtZszl), jt4Sj, sjJtZs.add(jtZszl), ljsl);
                //sjJtZs = jt4Zs;
                yssl = yssl.add(jtmx4.getSl());
                yssf = yssf.add(jtmx4.getSf());
            }

            if (ljsl.add(sl).compareTo(sjJtZs) > 0) {
                throw new FeesException(String.format("用户[%s]水量超过%s,无法进行计算！", yhKhjbxx.getYhbh(), sjJtZs), FeesErrorCode.BUSINESS_ERROR);
            }
            return new Sjmx(jtmx1, jtmx2, jtmx3, jtmx4, yssl, yssf);
        } else {
            BigDecimal sj = bmSj.getSj();
            BigDecimal sf = fyjs(sl, sj);
            return new Sjmx(sj, sl, sf);
        }

    }

    /**
     * 获取不同水价的水量
     * 返回值map key: LO是水价0（非一表多价),L1是水价1,L2是水价2,L3是水价3
     * 返回值map value: 水价编码_水量
     *
     * @param cbkxx 抄表卡信息
     * @param ljsl  累积水量（非阶梯时与本次实际水量相同）
     * @return
     */
    private TreeMap<String, String> getSlMap(YhCbkxx cbkxx, BigDecimal ljsl) {
        TreeMap<String, String> slMap = new TreeMap<>();
        String cbkid = cbkxx.getCbkid();
        String ybdjbz = cbkxx.getYbdjbz();
        if (StringUtils.isBlank(ybdjbz) || "0".equals(ybdjbz)) {
            String sjbm = cbkxx.getSjbm();
            if (StringUtils.isBlank(sjbm)) {
                throw new FeesException(String.format("水价未配置:%s", cbkid), FeesErrorCode.BUSINESS_ERROR);
            }

            slMap.put("L0", String.format("%s_%s", sjbm, ljsl));
            return slMap;
        } else {
            String sjbm1 = cbkxx.getSjbm();
            String sjbm2 = cbkxx.getSjbm1();
            String sjbm3 = cbkxx.getSjbm2();
            BigDecimal slbl1 = cbkxx.getSlbl();
            BigDecimal slbl2 = cbkxx.getSlbl1();
            BigDecimal slbl3 = cbkxx.getSlbl2();
            //定量
            BigDecimal sl1 = null;
            BigDecimal sl2 = null;
            BigDecimal sl3 = null;
            //BigDecimal sl4 = null;
            BigDecimal sysl = ljsl;//剩余水量
            if (slbl1 != null && slbl1.compareTo(BigDecimal.ZERO) > 0 && StringUtils.isNotEmpty(sjbm1)) {
                if (slbl1.compareTo(BigDecimal.ONE) > 0) {//按量
                    if (sysl.compareTo(slbl1) >= 0) {
                        sl1 = slbl1;
                        sysl = sysl.subtract(slbl1);
                    } else {
                        sl1 = sysl;
                        sysl = BigDecimal.ZERO;
                    }
                    slMap.put("L1", String.format("%s_%s", sjbm1, sl1));
                }

            }

            if (slbl2 != null && slbl2.compareTo(BigDecimal.ZERO) > 0 && StringUtils.isNotEmpty(sjbm2)) {
                if (slbl2.compareTo(BigDecimal.ONE) > 0) {//按量
                    if (sysl.compareTo(slbl2) >= 0) {
                        sl2 = slbl2;
                        sysl = sysl.subtract(slbl2);
                    } else {
                        sl2 = sysl;
                        sysl = BigDecimal.ZERO;
                    }
                    slMap.put("L2", String.format("%s_%s", sjbm2, sl2));
                }
            }

            if (slbl3 != null && slbl3.compareTo(BigDecimal.ZERO) > 0 && StringUtils.isNotEmpty(sjbm3)) {
                if (slbl3.compareTo(BigDecimal.ONE) > 0) {//按量
                    if (sysl.compareTo(slbl3) >= 0) {
                        sl3 = slbl3;
                        sysl = sysl.subtract(slbl3);
                    } else {
                        sl3 = sysl;
                        sysl = BigDecimal.ZERO;
                    }
                    slMap.put("L3", String.format("%s_%s", sjbm3, sl3));
                }
            }

            BigDecimal sysl2 = sysl;//按量以外的剩余水量
            if (slbl1 != null && slbl1.compareTo(BigDecimal.ZERO) > 0 && StringUtils.isNotEmpty(sjbm1)) {
                if (slbl1.compareTo(BigDecimal.ONE) <= 0) {//按比例
                    sl1 = sysl2.multiply(slbl1).setScale(0, RoundingMode.HALF_UP);
                    sysl = sysl.subtract(sl1);
                    slMap.put("L1", String.format("%s_%s", sjbm1, sl1));
                }
            }

            if (slbl2 != null && slbl2.compareTo(BigDecimal.ZERO) > 0 && StringUtils.isNotEmpty(sjbm2)) {
                if (slbl2.compareTo(BigDecimal.ONE) <= 0) {//按比例
                    //判断水价3是否存在，存在继续进行比例计算，否则按剩余量计算
                    if (slbl3 != null && slbl3.compareTo(BigDecimal.ZERO) > 0 && StringUtils.isNotEmpty(sjbm3)) {
                        sl2 = sysl2.multiply(slbl2).setScale(0, RoundingMode.HALF_UP);
                        sysl = sysl.subtract(sl2);
                    } else {
                        sl2 = sysl2.subtract(sl1);
                        sysl = BigDecimal.ZERO;
                    }
                    slMap.put("L2", String.format("%s_%s", sjbm2, sl2));
                }
            }

            if (slbl3 != null && slbl3.compareTo(BigDecimal.ZERO) > 0 && StringUtils.isNotEmpty(sjbm3)) {
                if (slbl3.compareTo(BigDecimal.ONE) <= 0 && sysl2.compareTo(BigDecimal.ZERO) > 0) {
                    sl3 = sysl2.subtract(sl1.add(sl2));
                    sysl = BigDecimal.ZERO;
                    slMap.put("L3", String.format("%s_%s", sjbm3, sl3));
                }
            }

            if (slbl1 != null && slbl1.compareTo(BigDecimal.ZERO) == 0 && StringUtils.isNotEmpty(sjbm1)) {
                sl1 = sysl;
                sysl = BigDecimal.ZERO;
                slMap.put("L1", String.format("%s_%s", sjbm1, sl1));

            }

            if (slbl2 != null && slbl2.compareTo(BigDecimal.ZERO) == 0 && StringUtils.isNotEmpty(sjbm2)) {
                sl2 = sysl;
                sysl = BigDecimal.ZERO;
                slMap.put("L2", String.format("%s_%s", sjbm2, sl2));
            }

            if (slbl3 != null && slbl3.compareTo(BigDecimal.ZERO) == 0 && StringUtils.isNotEmpty(sjbm3)) {
                sl3 = sysl;
                sysl = BigDecimal.ZERO;
                slMap.put("L3", String.format("%s_%s", sjbm3, sl3));
            }

            if (sysl.compareTo(BigDecimal.ZERO) > 0) {
                throw new FeesException(String.format("一表多价有水量未进入计算，剩余水量=%s:%s", sysl, cbkid), FeesErrorCode.BUSINESS_ERROR);
            }
            return slMap;
        }
    }

    private boolean isEnabled(BigDecimal jtZs) {
        return jtZs != null && jtZs.compareTo(BigDecimal.ZERO) > 0;
    }

    private Sjmx.Jtmx getJtSf(BigDecimal sl, BigDecimal jtZs, BigDecimal jtSj, BigDecimal sjJtZs, BigDecimal ljsl) {
        //累计水量小于阶梯止数 并且 累计水量+本次水量大于上一阶梯止数
        if (ljsl.compareTo(jtZs) < 0 && ljsl.add(sl).compareTo(sjJtZs) > 0) {
            BigDecimal jtSf;//阶梯水费
            BigDecimal ys = jtZs.subtract(ljsl.add(sl));//求阶梯余数
            BigDecimal jtsl;
            if (ys.compareTo(BigDecimal.ZERO) >= 0) {//阶梯余数大于0则没有超过阶梯止数
                if (ljsl.compareTo(sjJtZs) >= 0) {//累计水量大于上一阶梯止数则无需排除上一阶梯水量直接用sl
                    jtsl = sl;
                } else {//累计水量小于上一阶梯止数则需要排除上一阶梯的sl
                    jtsl = sl.subtract(sjJtZs).add(ljsl);
                }
            } else {//阶梯余数小于0则超过阶梯止数 需要求阶梯剩余水量
                if (ljsl.add(sl).compareTo(jtZs) > 0) {//累计水量加水量大于阶梯止数则直接求阶梯剩余水量
                    if (ljsl.compareTo(sjJtZs) > 0) {//累计水量大于上一阶梯止数则表示当前阶梯有累计水量
                        jtsl = jtZs.subtract(ljsl);
                    } else {
                        jtsl = jtZs.subtract(sjJtZs);
                    }
                } else {//累计水量小于上一阶梯止数则需要sl加上ljsl再减去上一阶梯止数求当前阶梯水量
                    jtsl = sl.subtract(sjJtZs).add(ljsl);
                }
            }
            jtSf = fyjs(jtsl, jtSj);
            return new Sjmx.Jtmx(jtSj, jtsl, jtSf);
        }
        return new Sjmx.Jtmx(jtSj, BigDecimal.ZERO, BigDecimal.ZERO);
    }

    /**
     * 费用算费
     */
    private BigDecimal fyjs(BigDecimal sl, BigDecimal sj) {
        if (sj != null) {
            return sl.multiply(sj);
        }

        return BigDecimal.ZERO;
    }

    public void ZfborZmb(String type, List<String> value) {
        LambdaQueryChainWrapper<YyCblr> eq = cblrService.lambdaQuery();
        if (type.equals("cbkid")) {
            eq.in(YyCblr::getCbkid, value);
        } else if (type.equals("cbb")) {
            eq.in(YyCblr::getSscbb, value);
        }

        //查询总表
        List<Map<String, String>> listzfcblr = eq.select(YyCblr::getCbkid)
                .eq(YyCblr::getCbbz, CbbzEnum.已抄表)
                .eq(YyCblr::getJsbz, JsbzEnum.未算费)
                .eq(YyCblr::getShbz, ShbzEnum.审核通过)
                .inSql(YyCblr::getCbkid, "select a.yhbh||a.cbkh cbkid from yh_bjfl_zb a " + " where a.type_id='1' and a.isdisabled='1'")
                .orderByAsc(YyCblr::getYhbh, YyCblr::getCbkh)
                .list().stream().map(e -> {
                    Map<String, String> map = new HashMap<>();
                    map.put("cbkid", e.getCbkid());
                    return map;
                }).collect(Collectors.toList());

        if (listzfcblr.size() > 0) {
            // 查询当前总表下属分表
            listzfcblr.forEach(item -> {
                String cbkid = item.get("cbkid");
                if (StringUtils.isNotBlank(cbkid)) {
                    Map map = cblrService.getZfCblrMap(cbkid);
                    if (Integer.parseInt(map.get("fbs").toString()) > Integer.parseInt(map.get("fbycs").toString())) {
                        cblrService.lambdaUpdate().set(YyCblr::getSl, -1).eq(YyCblr::getCbkid, cbkid).update();
                    } else {
                        cblrService.lambdaUpdate().setSql("SL=BCDS-SCDS-" + map.get("fbhjsl")).setSql("JJL=0-" + map.get("fbhjsl"))
                                .eq(YyCblr::getCbkid, cbkid).update();
                    }
                }
            });
        }

        //查询母表
        List<Map<String, String>> listzmcblr = eq.select(YyCblr::getCbkid)
                .eq(YyCblr::getCbbz, CbbzEnum.已抄表)
                .eq(YyCblr::getJsbz, JsbzEnum.未算费)
                .eq(YyCblr::getShbz, ShbzEnum.审核通过)
                .inSql(YyCblr::getCbkid, "select a.yhbh||a.cbkh cbkid from yh_bjfl_zb a " + " where a.type_id='2' and a.isdisabled='1'")
                .orderByAsc(YyCblr::getYhbh, YyCblr::getCbkh)
                .list().stream().map(e -> {
                    Map<String, String> map = new HashMap<>();
                    map.put("cbkid", e.getCbkid());
                    return map;
                }).collect(Collectors.toList());
        if (listzmcblr.size() > 0) {
            // 查询当前母表下属子表
            listzmcblr.forEach(item -> {
                String cbkid = item.get("cbkid");
                if (StringUtils.isNotBlank(cbkid)) {
                    Map map = cblrService.getZmCblrMap(cbkid);
                    if (Integer.parseInt(map.get("zbs").toString()) > Integer.parseInt(map.get("zbycs").toString())) {
                        cblrService.lambdaUpdate().set(YyCblr::getSl, -1).eq(YyCblr::getCbkid, cbkid).update();
                    } else {
                        cblrService.lambdaUpdate().setSql("SL=BCDS-SCDS+" + map.get("zbhjsl")).setSql("JJL=" + map.get("zbhjsl")).eq(YyCblr::getCbkid, cbkid).update();
                    }
                }
            });
        }
    }

    @Override
    public QftjabsSelectCount qftjabs(PageDto pageDto, QftjSeachFilter filter) {
        if (StringUtil.isEmpty(filter.getUserId())) {
            filter.setUserId(SecurityUtils.getUserId().toString());
        }
        List<Order> orders = pageDto.getOrders();
        if (orders.size() > 0) {
            orders = orders.stream().map(item -> {
                if (item.getColumn().equals("yhbh")) {
                    Order order = new Order();
                    order.setColumn("a.yhbh");
                    order.setAsc(item.isAsc());
                    return order;
                }
                return item;
            }).collect(Collectors.toList());
        } else {
            orders.add(new Order("a.yhbh", true));
        }

        pageDto.setOrders(orders);
        PageDto<QftjabsSelect> page = baseMapper.qftjabs(pageDto, filter);

        QftjabsSelectCount qftjabsSelectCount = new QftjabsSelectCount();
        qftjabsSelectCount.setList(page.toVo());
        //所有页合计
        QftjabsSelectCount tempModel = this.baseMapper.qftjabsCount(filter);
        if (StringUtil.isNotNull(tempModel)) {
            BeanUtils.copyProperties(tempModel, qftjabsSelectCount);
            qftjabsSelectCount.setList(page.toVo());
            //当前页合计
            qftjabsSelectCount.setYssf(page.getRecords().stream().map(QftjabsSelect::getSf).reduce(BigDecimal.ZERO, BigDecimal::add));
            qftjabsSelectCount.setYssl(page.getRecords().stream().map(QftjabsSelect::getQfsl).reduce(BigDecimal.ZERO, BigDecimal::add));
            qftjabsSelectCount.setYswsf(page.getRecords().stream().map(QftjabsSelect::getWsf).reduce(BigDecimal.ZERO, BigDecimal::add));
            qftjabsSelectCount.setYsljf(page.getRecords().stream().map(QftjabsSelect::getLjf).reduce(BigDecimal.ZERO, BigDecimal::add));
            qftjabsSelectCount.setYsecjyf(page.getRecords().stream().map(QftjabsSelect::getEcjyf).reduce(BigDecimal.ZERO, BigDecimal::add));
            qftjabsSelectCount.setYsfjf(page.getRecords().stream().map(QftjabsSelect::getFjf).reduce(BigDecimal.ZERO, BigDecimal::add));
            qftjabsSelectCount.setYsqt(page.getRecords().stream().map(QftjabsSelect::getQtf).reduce(BigDecimal.ZERO, BigDecimal::add));
            qftjabsSelectCount.setYsszyf(page.getRecords().stream().map(QftjabsSelect::getSzyf).reduce(BigDecimal.ZERO, BigDecimal::add));
            qftjabsSelectCount.setZnj(page.getRecords().stream().map(QftjabsSelect::getWyj).reduce(BigDecimal.ZERO, BigDecimal::add));
            qftjabsSelectCount.setQfje(page.getRecords().stream().map(QftjabsSelect::getQfje).reduce(BigDecimal.ZERO, BigDecimal::add));
            qftjabsSelectCount.setQfzje(page.getRecords().stream().map(QftjabsSelect::getQfzje).reduce(BigDecimal.ZERO, BigDecimal::add));
        }
        return qftjabsSelectCount;
    }

    @Override
    public List<QftjabsSelect> qftjabslist(QftjSeachFilter filter) {
        if (StringUtil.isEmpty(filter.getUserId())) {
            filter.setUserId(SecurityUtils.getUserId().toString());
        }
        List<QftjabsSelect> list = this.baseMapper.qftjabs(filter);
        list.stream().sorted(Comparator.comparing(QftjabsSelect::getYhbh)).collect(Collectors.toList());
        if (!list.isEmpty()) {
            QftjabsSelect qftjabsSelect = new QftjabsSelect();
            qftjabsSelect.setYhbh("合计");
            qftjabsSelect.setSf(list.stream().map(QftjabsSelect::getSf).reduce(BigDecimal.ZERO, BigDecimal::add));
            qftjabsSelect.setQfsl(list.stream().map(QftjabsSelect::getQfsl).reduce(BigDecimal.ZERO, BigDecimal::add));
            qftjabsSelect.setWsf(list.stream().map(QftjabsSelect::getWsf).reduce(BigDecimal.ZERO, BigDecimal::add));
            qftjabsSelect.setLjf(list.stream().map(QftjabsSelect::getLjf).reduce(BigDecimal.ZERO, BigDecimal::add));
            qftjabsSelect.setSzyf(list.stream().map(QftjabsSelect::getSzyf).reduce(BigDecimal.ZERO, BigDecimal::add));
            qftjabsSelect.setWyj(list.stream().map(QftjabsSelect::getWyj).reduce(BigDecimal.ZERO, BigDecimal::add));
            qftjabsSelect.setQfje(list.stream().map(QftjabsSelect::getQfje).reduce(BigDecimal.ZERO, BigDecimal::add));
            qftjabsSelect.setQfzje(list.stream().map(QftjabsSelect::getQfzje).reduce(BigDecimal.ZERO, BigDecimal::add));

            list.add(qftjabsSelect);
        }
        return list;
    }

    @Override
    public QftjSelectCount qftj(PageDto pageDto, QftjSeachFilter filter) {
        if (StringUtil.isEmpty(filter.getUserId())) {
            filter.setUserId(SecurityUtils.getUserId().toString());
        }
        List<Order> orders = pageDto.getOrders();
        if (orders.size() > 0) {
            orders = orders.stream().map(item -> {
                if (item.getColumn().equals("yhbh")) {
                    Order order = new Order();
                    order.setColumn("a.yhbh");
                    order.setAsc(item.isAsc());
                    return order;
                }
                return item;
            }).collect(Collectors.toList());
        } else {
            orders.add(new Order("a.yhbh", true));
        }
        pageDto.setOrders(orders);
        PageDto<QftjSelect> page = baseMapper.qftj(pageDto, filter);

        QftjSelectCount qftjSelectCount = new QftjSelectCount();
        qftjSelectCount.setList(page.toVo());
        //所有页合计
        QftjSelectCount tempModel = baseMapper.qftjCount(filter);
        if (ObjectUtil.isNotNull(tempModel)) {
            BeanUtils.copyProperties(tempModel, qftjSelectCount);
            qftjSelectCount.setList(page.toVo());

            List<QftjSelect> records = page.getRecords();
            if (CollectionUtil.isNotEmpty(records)) {
                //当前页合计
                qftjSelectCount.setYssf(records.stream().map(QftjSelect::getYssf).reduce(BigDecimal.ZERO, BigDecimal::add));
                qftjSelectCount.setYssl(records.stream().map(QftjSelect::getYssl).reduce(BigDecimal.ZERO, BigDecimal::add));
                qftjSelectCount.setYswsf(records.stream().map(QftjSelect::getYswsf).reduce(BigDecimal.ZERO, BigDecimal::add));
                qftjSelectCount.setYsljf(records.stream().map(QftjSelect::getYsljf).reduce(BigDecimal.ZERO, BigDecimal::add));
                qftjSelectCount.setYsszyf(records.stream().map(QftjSelect::getYsszyf).reduce(BigDecimal.ZERO, BigDecimal::add));
                qftjSelectCount.setZnj(records.stream().map(QftjSelect::getZnj).reduce(BigDecimal.ZERO, BigDecimal::add));
                qftjSelectCount.setQfje(records.stream().map(QftjSelect::getQfje).reduce(BigDecimal.ZERO, BigDecimal::add));
                qftjSelectCount.setQfzje(records.stream().map(QftjSelect::getQfzje).reduce(BigDecimal.ZERO, BigDecimal::add));
                // 二次加压、附加、消防栓统计
                qftjSelectCount.setEcjyfs(records.stream().filter(o -> ObjectUtil.isNotNull(o.getYsecjyf()))
                        .map(QftjSelect::getYsecjyf).reduce(BigDecimal.ZERO, BigDecimal::add));

                qftjSelectCount.setFjfs(records.stream().filter(o -> ObjectUtil.isNotNull(o.getYsfjf()))
                        .map(QftjSelect::getYsfjf).reduce(BigDecimal.ZERO, BigDecimal::add));

                qftjSelectCount.setQtfs(records.stream().filter(o -> ObjectUtil.isNotNull(o.getYsqt()))
                        .map(QftjSelect::getYsqt).reduce(BigDecimal.ZERO, BigDecimal::add));
            }
        }
        return qftjSelectCount;
    }


    @Override
    public List<YstjbbVo> bbglqftj(YyQfmxStatFilter filter) {
        List<String> permissions = yhsjqxService.queryByPermission();
        if (CollectionUtil.isEmpty(permissions)) {
            return new ArrayList<>();
        }

        filter.setCbbbms(permissions);
        List<YstjbbVo> bbglqftj = baseMapper.bbglqftj(filter);
        if (CollectionUtil.isEmpty(bbglqftj)) {
            return new ArrayList<>();
        }

        Integer tjlx = filter.getTjlx();
        // 0-按月统计 1-汇总统计
        if (1 == tjlx) {
            Map<String, List<YstjbbVo>> ysxmMap = bbglqftj.stream().collect(Collectors.groupingBy(YstjbbVo::getYsxm));
            List<YstjbbVo> qfmxhztj = qfmxhztj(ysxmMap);
            return qfmxhztj;
        } else {
            Map<String, List<YstjbbVo>> cwrqMap = bbglqftj.stream().collect(Collectors.groupingBy(YstjbbVo::getCwrq));
            List<YstjbbVo> qfmxaytj = qfmxaytj(cwrqMap);
            return qfmxaytj;
        }
    }

    @Override
    public List<YstjbbVo> bbglystj(YyQfmxStatFilter filter) {
        List<String> permissions = yhsjqxService.queryByPermission();
        if (CollectionUtil.isEmpty(permissions)) {
            return new ArrayList<>();
        }

        filter.setCbbbms(permissions);
        List<YstjbbVo> dataList = baseMapper.getMonthlyStatDetail(filter);
        if (CollectionUtil.isEmpty(dataList)) {
            return new ArrayList<>();
        }

        List<YstjbbVo> ystjresults = new ArrayList<>();
        List<YstjbbVo> xjlist = new ArrayList<>();

        Integer tjlx = filter.getTjlx();
        if (tjlx == 0) {
            ayystj(dataList, ystjresults, xjlist);
        } else {
            hzystj(dataList, ystjresults, xjlist);
        }

        YstjbbVo hj = YstjbbVo.tjhj(xjlist, "合计");
        ystjresults.add(hj);
        return ystjresults;
    }

    private void hzystj(List<YstjbbVo> dataList, List<YstjbbVo> ystjresults, List<YstjbbVo> xjlist) {
        Map<String, List<YstjbbVo>> ysxmMap = dataList.stream().collect(Collectors.groupingBy(YstjbbVo::getYsxm));

        for (Map.Entry<String, List<YstjbbVo>> entry : ysxmMap.entrySet()) {
            String ysxm = entry.getKey();
            List<YstjbbVo> ysxmList = entry.getValue();
            ystjresults.addAll(ysxmList);
            YstjbbVo xj = YstjbbVo.tjhj(ysxmList, "小计");

            xjlist.add(xj);
            ystjresults.add(xj);
        }
    }

    private void ayystj(List<YstjbbVo> dataList, List<YstjbbVo> ystjresults, List<YstjbbVo> xjlist) {
        Map<String, List<YstjbbVo>> cwrqMap = dataList.stream().collect(Collectors.groupingBy(YstjbbVo::getCwrq));

        for (Map.Entry<String, List<YstjbbVo>> entry : cwrqMap.entrySet()) {
            String cwrq = entry.getKey();
            List<YstjbbVo> cwrqList = entry.getValue();
            ystjresults.addAll(cwrqList);
            YstjbbVo xj = YstjbbVo.tjhj(cwrqList, "小计");

            xjlist.add(xj);
            ystjresults.add(xj);
        }
    }

    @Override
    public Long checkQfmxIsCharged(YyQfmx yyQfmx) {
        LambdaQueryWrapper<YyQfmx> wrapper = Wrappers.<YyQfmx>lambdaQuery()
                .eq(YyQfmx::getYhbh, yyQfmx.getYhbh())
                .eq(YyQfmx::getCwrq, yyQfmx.getCwrq())
                .eq(YyQfmx::getSfbz, "1");
        return baseMapper.selectCount(wrapper);
    }

    private List<YstjbbVo> qfmxhztj(Map<String, List<YstjbbVo>> ysxmMap) {
        List<YstjbbVo> results = new ArrayList<>();

        for (Map.Entry<String, List<YstjbbVo>> entry : ysxmMap.entrySet()) {
            String ysxm = entry.getKey();
            List<YstjbbVo> xmlist = entry.getValue();
            xmlist.forEach(o -> o.mxhjjs());

            YstjbbVo xmmx = new YstjbbVo();
            xmmx.setCwrq(StrUtil.EMPTY);
            xmmx.setYsxm(ysxm);
            xmmx.setSj(xmlist.get(0).getSj());
            xmmx.setSl(xmlist.stream().map(YstjbbVo::getSl).reduce(BigDecimal.ZERO, BigDecimal::add));
            xmmx.setSf(xmlist.stream().map(YstjbbVo::getSf).reduce(BigDecimal.ZERO, BigDecimal::add));
            xmmx.setWsf(xmlist.stream().map(YstjbbVo::getWsf).reduce(BigDecimal.ZERO, BigDecimal::add));
            xmmx.setSzyf(xmlist.stream().map(YstjbbVo::getSzyf).reduce(BigDecimal.ZERO, BigDecimal::add));
            xmmx.setEcjyf(xmlist.stream().map(YstjbbVo::getEcjyf).reduce(BigDecimal.ZERO, BigDecimal::add));
            xmmx.setFjf(xmlist.stream().map(YstjbbVo::getFjf).reduce(BigDecimal.ZERO, BigDecimal::add));
            xmmx.setQtf(xmlist.stream().map(YstjbbVo::getQtf).reduce(BigDecimal.ZERO, BigDecimal::add));
            results.add(xmmx);
        }

        YstjbbVo tjhj = YstjbbVo.tjhj(results, "合计");
        YstjbbVo xj = BeanUtil.copyProperties(tjhj, YstjbbVo.class);
        xj.setYsxm("小计");
        results.add(xj);
        results.add(tjhj);
        return results;
    }

    private List<YstjbbVo> qfmxaytj(Map<String, List<YstjbbVo>> cwrqMap) {
        List<YstjbbVo> results = new ArrayList<>();
        List<YstjbbVo> xjlist = new ArrayList<>();

        for (Map.Entry<String, List<YstjbbVo>> entry : cwrqMap.entrySet()) {
            String cwrq = entry.getKey();
            List<YstjbbVo> xmlist = entry.getValue();
            xmlist.forEach(o -> o.mxhjjs());

            results.addAll(xmlist);

            YstjbbVo xj = YstjbbVo.tjhj(xmlist, "小计");
            results.add(xj);
            xjlist.add(xj);
        }
        YstjbbVo hj = YstjbbVo.tjhj(xjlist, "合计");
        results.add(hj);
        return results;
    }

    private List<Jzhztjmx> jsjzhzmxByqf(JzhztjDto jzhztjDto, List<QftjSelect> qfmxList) {
        List<Jzhztjmx> details = new ArrayList<>();
        Map<String, List<QftjSelect>> sjbmmxmap = qfmxList.stream().collect(Collectors.groupingBy(QftjSelect::getSjbm));

        Integer type = jzhztjDto.getType();
        for (Map.Entry<String, List<QftjSelect>> sjbmmxEntry : sjbmmxmap.entrySet()) {
            List<QftjSelect> ysmxs = sjbmmxEntry.getValue();
            QftjSelect yyQfmxSelect = ysmxs.get(0);
            Jzhztjmx jzhztjmx = Jzhztjmx.buildBySjmc(yyQfmxSelect.getSjmc());
            jzhztjmx.setHs(ysmxs.size());
            jzhztjmx.setDw("吨");

            BigDecimal sl = ysmxs.stream().filter(o -> ObjUtil.isNotNull(o.getYssl()))
                    .map(QftjSelect::getYssl)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            jzhztjmx.setSl(sl);

            // 水费、污水费、水资源费单价
            if (1 == type) {
                BigDecimal sj = yyQfmxSelect.getSj();
                jzhztjmx.setDj(sj);
                jzhztjmx.setJe(sl.multiply(sj));
            } else if (2 == type) {
                BigDecimal wsfdj = yyQfmxSelect.getWsfdj();
                jzhztjmx.setDj(wsfdj);
                jzhztjmx.setJe(sl.multiply(wsfdj));
            } else if (3 == type) {
                BigDecimal szyfDj = yyQfmxSelect.getSzyfdj();
                jzhztjmx.setDj(szyfDj);
                jzhztjmx.setJe(sl.multiply(szyfDj));
            }
            jzhztjmx.setBz(StrUtil.EMPTY);
            details.add(jzhztjmx);
        }

        // 水费类型增加 附加费、加压费
        if (1 == type) {
            List<QftjSelect> ecjymxs = qfmxList.stream().filter(o -> ObjUtil.isNotNull(o.getYsecjyf())
                    && o.getYsecjyf().compareTo(BigDecimal.ZERO) != 0).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(ecjymxs)) {
                BigDecimal ecjyfs = ecjymxs.stream().map(QftjSelect::getYsecjyf).reduce(BigDecimal.ZERO, BigDecimal::add);
                Jzhztjmx jzhztjmx = new Jzhztjmx();
                jzhztjmx.setXm("二次加压");
                jzhztjmx.setHs(ecjymxs.size());
                jzhztjmx.setDw("吨");
                jzhztjmx.setSl(BigDecimal.ZERO);
                jzhztjmx.setDj(BigDecimal.ZERO);
                jzhztjmx.setJe(ecjyfs);
                details.add(jzhztjmx);
            }

            List<QftjSelect> fjfmxs = qfmxList.stream().filter(o -> ObjUtil.isNotNull(o.getYsfjf())
                    && o.getYsfjf().compareTo(BigDecimal.ZERO) != 0).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(fjfmxs)) {
                BigDecimal fjfs = fjfmxs.stream().map(QftjSelect::getYsfjf).reduce(BigDecimal.ZERO, BigDecimal::add);
                Jzhztjmx jzhztjmx = new Jzhztjmx();
                jzhztjmx.setXm("附加");
                jzhztjmx.setHs(fjfmxs.size());
                jzhztjmx.setDw("吨");
                jzhztjmx.setSl(BigDecimal.ZERO);
                jzhztjmx.setDj(BigDecimal.ZERO);
                jzhztjmx.setJe(fjfs);
                details.add(jzhztjmx);
            }
        }

        if (CollectionUtil.isNotEmpty(details)) {
            BigDecimal hjsl = details.stream().filter(o -> ObjUtil.isNotNull(o.getSl()))
                    .map(Jzhztjmx::getSl).reduce(BigDecimal.ZERO, BigDecimal::add);
            jzhztjDto.setHjsl(hjsl);

            BigDecimal hjje = details.stream().filter(o -> ObjUtil.isNotNull(o.getJe()))
                    .map(Jzhztjmx::getJe).reduce(BigDecimal.ZERO, BigDecimal::add);
            jzhztjDto.setHjje(hjje);

            Integer hjhs = details.stream().filter(o -> ObjUtil.isNotNull(o.getHs()))
                    .map(Jzhztjmx::getHs).reduce(Integer::sum).orElse(0);
            jzhztjDto.setHjhs(hjhs);
        } else {
            jzhztjDto.setHjsl(BigDecimal.ZERO);
            jzhztjDto.setHjje(BigDecimal.ZERO);
            jzhztjDto.setHjhs(0);
        }

        jzhztjDto.setDetails(details);
        return details;
    }

    @Override
    public Map qftjhj(QftjSeachFilter filter) {
        Map map = this.baseMapper.qftjhj(filter);
        return map;
    }

    @Override
    public List<QftjSelect> qftjlist(QftjSeachFilter filter) {
        if (StringUtil.isEmpty(filter.getUserId())) {
            filter.setUserId(SecurityUtils.getUserId().toString());
        }
        List<QftjSelect> list = this.baseMapper.qftj(filter);
//        list.stream().sorted(Comparator.comparing(QftjSelect::getYhbh)).collect(Collectors.toList());
        if (!list.isEmpty()) {
            BigDecimal ysslsum = list.stream().map(QftjSelect::getYssl).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal yssfsum = list.stream().map(QftjSelect::getYssf).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal yswsfsum = list.stream().map(QftjSelect::getYswsf).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal ysljfsum = list.stream().map(QftjSelect::getYsljf).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal ysszyfsum = list.stream().map(QftjSelect::getYsszyf).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal znjsum = list.stream().map(QftjSelect::getZnj).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal qfjesum = list.stream().map(QftjSelect::getQfje).reduce(BigDecimal.ZERO, BigDecimal::add);
            QftjSelect qftjSelect = new QftjSelect();
            qftjSelect.setYhbh("总计");
            qftjSelect.setYssl(ysslsum);
            qftjSelect.setYssf(yssfsum);
            qftjSelect.setYswsf(yswsfsum);
            qftjSelect.setYsljf(ysljfsum);
            qftjSelect.setYsszyf(ysszyfsum);
            qftjSelect.setZnj(znjsum);
            qftjSelect.setQfje(qfjesum);
            list.add(qftjSelect);
        }
        return list;
    }

    @Override
    public PageResult<YsqdSelect> ysqd(PageDto pageDto, QftjSeachFilter filter) {
        if (StringUtil.isEmpty(filter.getUserId())) {
            filter.setUserId(SecurityUtils.getUserId().toString());
        }
        List<Order> orders = pageDto.getOrders();
        if (orders.size() > 0) {
            orders = orders.stream().map(item -> {
                if (item.getColumn().equals("yhbh")) {
                    Order order = new Order();
                    order.setColumn("a.yhbh");
                    order.setAsc(item.isAsc());
                    return order;
                }
                return item;
            }).collect(Collectors.toList());
        } else {
            orders.add(new Order("a.yhbh", true));
        }
        pageDto.setOrders(orders);
        PageDto<YsqdSelect> page = baseMapper.ysqd(pageDto, filter);
        return page.toVo();
    }

    @Override
    public Sltjzj slcbtj(PageDto pageDto, QftjSeachFilter filter) {
        Sltjzj sltjzj = new Sltjzj();

        // 获取人员信息
        YhkhjbxxFilter userQuery = new YhkhjbxxFilter();
        userQuery.setSsgs(filter.getSsgs());
        userQuery.setSscbpq(filter.getSscbpq());
        userQuery.setSscbb(filter.getSscbb());
        userQuery.setSearchText(filter.getSearchText());
        PageResult<YhkhjbxxSelect2> userInfoPage = khjbxxService.getUserInfoPage(pageDto, userQuery);
        List<YhkhjbxxSelect2> records = userInfoPage.getRecords();

        // 查询抄表次数、抄表水量
        if (CollectionUtil.isNotEmpty(records)) {
            List<String> yhbhs = records.stream().map(YhkhjbxxSelect2::getYhbh).distinct().collect(Collectors.toList());
            filter.setYhbhs(yhbhs);
            List<YyCblrSelect> cbjlByYhbhs = cblrService.getCbjl(filter);

            if (CollectionUtil.isNotEmpty(cbjlByYhbhs)) {
                zzcslcs(records, cbjlByYhbhs);
            }

            ZcbcssltjDto zcbcszsltj = cblrService.zcbcszsltj(filter);
            sltjzj.setZcbcs(zcbcszsltj.getZcbcs());
            sltjzj.setZcbsl(zcbcszsltj.getZcbsl());
        } else {
            sltjzj.setZcbcs(0);
            sltjzj.setZcbsl(BigDecimal.ZERO);
        }

        sltjzj.setZyhs(userInfoPage.getTotal());
        sltjzj.setTotal(userInfoPage.getTotal());
        sltjzj.setRecords(records);

        return sltjzj;
    }

    private void zzcslcs(List<YhkhjbxxSelect2> records, List<YyCblrSelect> cbjlByYhbhs) {
        Map<String, List<YyCblrSelect>> cbMap = cbjlByYhbhs.stream()
                .filter(o -> ShbzEnum.审核通过 == o.getShbz())
                .collect(Collectors.groupingBy(YyCblrSelect::getYhbh));

        for (YhkhjbxxSelect2 record : records) {
            String yhbh = record.getYhbh();
            List<YyCblrSelect> yyCblrSelects = cbMap.get(yhbh);
            if (CollectionUtil.isNotEmpty(yyCblrSelects)) {
                int cbcs = yyCblrSelects.size();
                BigDecimal addCbsl = yyCblrSelects.stream().filter(o -> ObjectUtil.isNotNull(o.getSjsl()))
                        .map(YyCblrSelect::getSjsl)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
                record.setCbcs(cbcs);
                record.setCbsl(addCbsl.toString());
            } else {
                record.setCbcs(0);
                record.setCbsl("0");
            }
        }
    }

    @Override
    public List<YsqdSelect> ysqdlist(QftjSeachFilter filter) {
        if (StringUtil.isEmpty(filter.getUserId())) {
            filter.setUserId(SecurityUtils.getUserId().toString());
        }
        List<YsqdSelect> list = this.baseMapper.ysqd(filter);
        list.stream().sorted(Comparator.comparing(YsqdSelect::getYhbh)).collect(Collectors.toList());
        return list;
    }

    @Override
    public List<LjftjSelect> wsljf(LjftjFilter filter) {
        List<LjftjSelect> list = this.baseMapper.wsljf(filter);
        if (list.size() > 0) {
            LjftjSelect ljftjSelect = new LjftjSelect();
            ljftjSelect.setCwrq("合计");
            ljftjSelect.setNum(list.stream().mapToLong(LjftjSelect::getNum).sum());
            ljftjSelect.setAmount(list.stream().map(LjftjSelect::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
            list.add(ljftjSelect);
        }
        return list;
    }

    @Override
    public List<LjftjSelect> ysljf(LjftjFilter filter) {
        List<LjftjSelect> list = this.baseMapper.ysljf(filter);
        if (list.size() > 0) {
            LjftjSelect ljftjSelect = new LjftjSelect();
            ljftjSelect.setCwrq("合计");
            ljftjSelect.setNum(list.stream().mapToLong(LjftjSelect::getNum).sum());
            ljftjSelect.setAmount(list.stream().map(LjftjSelect::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
            list.add(ljftjSelect);
        }
        return list;
    }

    @Override
    public List<LjftjSelect> yisljf(LjftjFilter filter) {
        List<LjftjSelect> list = this.baseMapper.yisljf(filter);
        if (list.size() > 0) {
            LjftjSelect ljftjSelect = new LjftjSelect();
            ljftjSelect.setCwrq("合计");
            ljftjSelect.setNum(list.stream().mapToLong(LjftjSelect::getNum).sum());
            ljftjSelect.setAmount(list.stream().map(LjftjSelect::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
            list.add(ljftjSelect);
        }
        return list;
    }

    @Override
    public YkfpmxtjPageSelect getYcfpmxtj(PageDto pageDto, YkfpmxtjFilter filter) {
        YkfpmxtjPageSelect ykfpmxtjPageSelect = this.baseMapper.getYcfpmxhj(filter);
        PageDto<YkfpmxtjSelect> page = this.baseMapper.getYcfpmxpage(pageDto, filter);
        ykfpmxtjPageSelect.setYkfpmxtjSelectPageResult(page.toVo());
        return ykfpmxtjPageSelect;
    }

    @Override
    public List<YkfpmxtjSelect> exportYcfpmxtj(YkfpmxtjFilter filter) {
        List<YkfpmxtjSelect> ykfpmxtjSelectList = this.baseMapper.getYcfpmxpage(filter);
        if (!ykfpmxtjSelectList.isEmpty()) {
            YkfpmxtjPageSelect ykfpmxtjPageSelect = this.baseMapper.getYcfpmxhj(filter);
            YkfpmxtjSelect ykfpmxtjSelect = new YkfpmxtjSelect();
            ykfpmxtjSelect.setYhbh("合计");
            ykfpmxtjSelect.setKpje(ykfpmxtjPageSelect.getKpje());
            ykfpmxtjSelect.setXzje(ykfpmxtjPageSelect.getXzje());
            ykfpmxtjSelectList.add(ykfpmxtjSelect);
        }
        return ykfpmxtjSelectList;
    }

    @Override
    public List<LjfjmVo> ljfjm(LjfjmDto dto) {
        List<LjfjmVo> listljfjm = this.baseMapper.ljfjm(dto);
        //计算合计行
        if (!listljfjm.isEmpty()) {
            LjfjmVo ljfjmVo = new LjfjmVo();
            ljfjmVo.setCwrq("合计");
            ljfjmVo.setCount(listljfjm.stream().map(LjfjmVo::getCount).reduce(BigDecimal.ZERO, BigDecimal::add));
            ljfjmVo.setWsf(listljfjm.stream().map(LjfjmVo::getWsf).reduce(BigDecimal.ZERO, BigDecimal::add));
            listljfjm.add(ljfjmVo);
        }
        return listljfjm;
    }

    @Override
    public PageResult<QfmxbgtjVo> qfmxbgPage(PageDto pageDto, QfmxbgtjDto dto) {
        return baseMapper.qfmxbgPage(pageDto, dto).toVo();
    }

    @Override
    public List<QfmxbgtjVo> qfmxbgPageList(QfmxbgtjDto dto) {
        return this.baseMapper.qfmxbgPageList(dto);
    }

    @Override
    public Boolean qfmxbgPlcj(String gdlsbh) {
        YyQfmxGd yyQfmxGd = yyQfmxGdService.getById(gdlsbh);
        if (yyQfmxGd.getIsplbg().equals("1")) {
            List<YyQfmx> yyQfmxList = this.lambdaQuery().eq(YyQfmx::getGdlsbh, gdlsbh).list();
            for (YyQfmx yyQfmx : yyQfmxList) {
                YyQfmx yyQfmx_new = yyQfmx;
                if (yyQfmx.getSfbz().equals("1")) {
                    throw new FeesException("当前欠费已缴费", FeesErrorCode.BUSINESS_ERROR);
                }
                yyQfmx.setChbz(PjztEnum.已冲红.getValue());
                yyQfmx.setSfbc("2");
                yyQfmx.setGdyx(yyQfmxGd.getGdyx());
                this.updateById(yyQfmx);

                YyQfmx YyQfmx_ch = this.createHp(yyQfmx, yyQfmx.getChsj());//红票
                YyQfmx_ch.setSfbc("2");
                YyQfmx_ch.setGdzt("");
                YyQfmx_ch.setGdlsbh("");
                YyQfmx_ch.setGdyx("");
                this.save(YyQfmx_ch);

                BeanUtils.copyProperties(yyQfmx, yyQfmx_new, NumberHelper.getNullPropertyNames(yyQfmx));
                yyQfmx_new.setGdzt("");
                yyQfmx_new.setGdlsbh("");
                yyQfmx_new.setGdyx("");
                yyQfmx_new.setChbz(PjztEnum.正常.getValue());
                yyQfmx_new.setCwrq(gdcsbService.selectCwrq());
                yyQfmx_new.setId(GuidGenerator.getGuid());
                BmSj bmSj = sjService.getById(yyQfmx_new.getSjbm());
                if (bmSj.getJtbz().equals("1")) {
                    yyQfmx_new.setJtzqljl(yyQfmx_new.getJtzqljlJsq().subtract(yyQfmx_new.getYssl()));
                } else {
                    yyQfmx_new.setJtzqljl(BigDecimal.ZERO);
                }
                if (yyQfmx_new.getYssl().compareTo(BigDecimal.ZERO) == 0) {
                    yyQfmx_new.setSfbz("4");
                } else {
                    yyQfmx_new.setSfbz("0");
                }
                yyQfmx_new.setLrrq(new Date());
                yyQfmx_new.setJsrq(yyQfmx_new.getLrrq());
                yyQfmx_new.setYssl(BigDecimal.ZERO);
                yyQfmx_new.setYssf(BigDecimal.ZERO);
                yyQfmx_new.setYsszyf(BigDecimal.ZERO);
                yyQfmx_new.setYsje(BigDecimal.ZERO);
                yyQfmx_new.setYswsf(BigDecimal.ZERO);
                yyQfmx_new.setYsljf(BigDecimal.ZERO);
                yyQfmx_new.setSl(BigDecimal.ZERO);
                yyQfmx_new.setSf(BigDecimal.ZERO);
                yyQfmx_new.setSl1(BigDecimal.ZERO);
                yyQfmx_new.setSf1(BigDecimal.ZERO);
                yyQfmx_new.setSl2(BigDecimal.ZERO);
                yyQfmx_new.setSf2(BigDecimal.ZERO);
                yyQfmx_new.setSl3(BigDecimal.ZERO);
                yyQfmx_new.setSf3(BigDecimal.ZERO);
                yyQfmx_new.setSzyf(BigDecimal.ZERO);
                yyQfmx_new.setSzyf1(BigDecimal.ZERO);
                yyQfmx_new.setSzyf2(BigDecimal.ZERO);
                yyQfmx_new.setSzyf3(BigDecimal.ZERO);
                yyQfmx_new.setWsf(BigDecimal.ZERO);
                yyQfmx_new.setWsf1(BigDecimal.ZERO);
                yyQfmx_new.setWsf2(BigDecimal.ZERO);
                yyQfmx_new.setWsf3(BigDecimal.ZERO);
                yyQfmx_new.setLjf(BigDecimal.ZERO);
                yyQfmx_new.setLjf1(BigDecimal.ZERO);
                yyQfmx_new.setLjf2(BigDecimal.ZERO);
                yyQfmx_new.setLjf3(BigDecimal.ZERO);
                yyQfmx_new.setJt1sf(BigDecimal.ZERO);
                yyQfmx_new.setJt2sf(BigDecimal.ZERO);
                yyQfmx_new.setJt3sf(BigDecimal.ZERO);
                yyQfmx_new.setJt4sf(BigDecimal.ZERO);
                yyQfmx_new.setJt1sl(BigDecimal.ZERO);
                yyQfmx_new.setJt2sl(BigDecimal.ZERO);
                yyQfmx_new.setJt3sl(BigDecimal.ZERO);
                yyQfmx_new.setJt4sl(BigDecimal.ZERO);
                yyQfmx_new.setSj1Jt1sf(BigDecimal.ZERO);
                yyQfmx_new.setSj1Jt2sf(BigDecimal.ZERO);
                yyQfmx_new.setSj1Jt3sf(BigDecimal.ZERO);
                yyQfmx_new.setSj1Jt4sf(BigDecimal.ZERO);
                yyQfmx_new.setSj1Jt1sl(BigDecimal.ZERO);
                yyQfmx_new.setSj1Jt2sl(BigDecimal.ZERO);
                yyQfmx_new.setSj1Jt3sl(BigDecimal.ZERO);
                yyQfmx_new.setSj1Jt4sl(BigDecimal.ZERO);
                yyQfmx_new.setSj2Jt1sf(BigDecimal.ZERO);
                yyQfmx_new.setSj2Jt2sf(BigDecimal.ZERO);
                yyQfmx_new.setSj2Jt3sf(BigDecimal.ZERO);
                yyQfmx_new.setSj2Jt4sf(BigDecimal.ZERO);
                yyQfmx_new.setSj2Jt1sl(BigDecimal.ZERO);
                yyQfmx_new.setSj2Jt2sl(BigDecimal.ZERO);
                yyQfmx_new.setSj2Jt3sl(BigDecimal.ZERO);
                yyQfmx_new.setSj2Jt4sl(BigDecimal.ZERO);
                yyQfmx_new.setBcds(yyQfmx_new.getScds());
                YyCblr yyCblr = cblrService.getById(yyQfmx_new.getCbkid());
                if (yyCblr.getCwrq().equals(yyQfmx_new.getCwrq())) {
                    cblrService.lambdaUpdate().set(YyCblr::getScds, yyQfmx_new.getScds()).set(YyCblr::getBcds, yyQfmx_new.getBcds()).set(YyCblr::getJjl, yyQfmx_new.getJjl()).set(YyCblr::getSl, yyQfmx_new.getSl()).set(YyCblr::getLrryxm, yyQfmx_new.getLrryxm()).set(YyCblr::getLrrybm, yyQfmx_new.getLrrybm()).set(YyCblr::getCblx, yyQfmx_new.getCblx()).set(YyCblr::getJbzd, yyQfmx_new.getJbzd()).set(YyCblr::getXbqd, yyQfmx_new.getXbqd()).eq(YyCblr::getCwrq, yyQfmx_new.getCwrq()).eq(YyCblr::getCbkid, yyQfmx_new.getCbkid());
                    if (bmSj.getJtbz().equals("1")) {
                        khjbxxService.lambdaUpdate().set(YhKhjbxx::getJtzqljl, yyQfmx_new.getJtzqljl()).eq(YhKhjbxx::getYhbh, yyQfmx_new.getYhbh()).update();
                    }
                }
                boolean tf = this.save(yyQfmx_new);
                if (tf) {
                    YyBgLog yyBgLog = new YyBgLog();
                    yyBgLog.setBglxid(yyQfmx.getId());
                    yyBgLog.setBglx(BglxEnum.QFMXBG.getValue());
                    yyBgLog.setBgqjson(JSONObject.toJSONString(yyQfmx));
                    yyBgLog.setBghjson(JSONObject.toJSONString(yyQfmx_new));
                    yyBgLog.setBgnr(String.format("欠费明细变更调整，用户编号%s-财务日期%s，调整日期：%s 调整人：%s", yyQfmx.getYhbh(), yyQfmx.getCwrq(), LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")), SecurityUtils.getUser().getRealName()

                    ));
                    yyBgLog.setGdzt("2");
                    yyBgLogService.bglogsave(yyBgLog);
//                    List<YyQfmx> list = new ArrayList<>();
//                    list.add(yyQfmx_new);
//                    znjCal.YyQfmxZnj(yyQfmx_new.getYhbh(), list);
                }
            }
        }
        return true;
    }

    @Override
    public PageResult<FylrtjVo> fylrtjPage(PageDto pageDto, FylrtjDto dto) {
        PageDto<FylrtjVo> resultPage = baseMapper.fylrtjPage(pageDto, dto);
        List<FylrtjVo> records = resultPage.getRecords();
        if (CollectionUtil.isNotEmpty(records)) {
            records.forEach(o -> {
                o.setYsecjyf(checkNumberFormat(o.getYsecjyf()));
                o.setYsfjf(checkNumberFormat(o.getYsfjf()));
                o.setYsqt(checkNumberFormat(o.getYsqt()));
            });
        }

        return resultPage.toVo();
    }

    @Override
    public List<FylrtjVo> fylrtjPageList(FylrtjDto dto) {
        return this.baseMapper.fylrtjPageList(dto);
    }

    @Override
    public List<YcyetjVo> getYcyetj(YcyetjDto dto) {
        String StartCwrq = dto.getCwrqStart();
        String EndCwrq = getPreviousMonth(dto.getCwrqEnd(), "add");

        List<YcyetjVo> ycyetjVoList = new ArrayList<>();
        while (!EndCwrq.equals(StartCwrq)) {


            String tempStartCwrq = StartCwrq;
            String tempEndCwrq = getPreviousMonth(StartCwrq, "add");

            //转换成具体日期
            String tempStartSfrq = tempStartCwrq.substring(0, 4) + "-" + tempStartCwrq.substring(4, 6) + "-01T00:00:00";
            String tempEndSfrq = tempEndCwrq.substring(0, 4) + "-" + tempEndCwrq.substring(4, 6) + "-01t00:00:00";

            LocalDateTime dt_tempStartSfrq = LocalDateTime.parse(tempStartSfrq, DateTimeFormatter.ISO_DATE_TIME);
            LocalDateTime dt_tempEndSfrq = LocalDateTime.parse(tempEndSfrq, DateTimeFormatter.ISO_DATE_TIME);
            YcyetjVo ycyetjVo = new YcyetjVo();
            ycyetjVo.setCwrq(tempStartCwrq);
            ycyetjVo.setQmye(this.baseMapper.getqmjyje(tempStartCwrq, "0003"));//期末
            ycyetjVo.setQcye(this.baseMapper.getqmjyje(getPreviousMonth(tempStartCwrq, "subtract"), "0003"));//期初
            ycyetjVo.setBckj(BigDecimal.ZERO);
            ycyetjVo.setBcyc(BigDecimal.ZERO);
            ycyetjVo.setBctf(BigDecimal.ZERO);
            ycyetjVoList.add(ycyetjVo);

            ycyetjVo = new YcyetjVo();
            ycyetjVo.setCwrq(tempStartCwrq);
            ycyetjVo.setQmye(this.baseMapper.getqmjyje(tempStartCwrq, "0002"));//期末
            ycyetjVo.setQcye(this.baseMapper.getqmjyje(getPreviousMonth(tempStartCwrq, "subtract"), "0002"));//期初
            ycyetjVo.setBckj(this.baseMapper.getbckj(dt_tempStartSfrq, dt_tempEndSfrq));
            ycyetjVo.setBcyc(this.baseMapper.getbcyeandtf(dt_tempStartSfrq, dt_tempEndSfrq, "0"));
            ycyetjVo.setBctf(this.baseMapper.getbcyeandtf(dt_tempStartSfrq, dt_tempEndSfrq, "1"));

            StartCwrq = tempEndCwrq;
            ycyetjVoList.add(ycyetjVo);
        }

        if (ycyetjVoList.size() > 0) {
            YcyetjVo ycyetjVo = new YcyetjVo();
            ycyetjVo.setCwrq("合计");

            ycyetjVo.setQmye(ycyetjVoList.stream().map(YcyetjVo::getQmye).reduce(BigDecimal.ZERO, BigDecimal::add));//期末
            ycyetjVo.setQcye(ycyetjVoList.stream().map(YcyetjVo::getQcye).reduce(BigDecimal.ZERO, BigDecimal::add));//期初

            ycyetjVo.setBckj(ycyetjVoList.stream().map(YcyetjVo::getBckj).reduce(BigDecimal.ZERO, BigDecimal::add));
            ycyetjVo.setBcyc(ycyetjVoList.stream().map(YcyetjVo::getBcyc).reduce(BigDecimal.ZERO, BigDecimal::add));
            ycyetjVo.setBctf(ycyetjVoList.stream().map(YcyetjVo::getBctf).reduce(BigDecimal.ZERO, BigDecimal::add));

            ycyetjVoList.add(ycyetjVo);
        }
        return ycyetjVoList;
    }

    @Override
    public List<FyhslSelect> getfyhslbb(FyhslFilter filter) {
        //获取应收固定数据
        List<YyHslStatGd> listGd0 = this.baseMapper.hslStatGd(filter, "", "ysyf,");
        List<YyHslStatGd> listGd1 = this.baseMapper.hslStatGd(filter, "1", "ysyf,");
        List<YyHslStatGd> listGd2 = this.baseMapper.hslStatGd(filter, "2", "ysyf,");
        List<YyHslStatGd> listGd3 = this.baseMapper.hslStatGd(filter, "3", "ysyf,");
        List<YyHslStatGd> listGd = new ArrayList<>();
        if (!listGd0.isEmpty()) {
            listGd.addAll(listGd0);
        }
        if (!listGd1.isEmpty()) {
            listGd.addAll(listGd1);
        }
        if (!listGd2.isEmpty()) {
            listGd.addAll(listGd2);
        }
        if (!listGd3.isEmpty()) {
            listGd.addAll(listGd3);
        }
        Map<String, List<YyHslStatGd>> yfyfGdMap = listGd.stream().filter(e -> StringUtils.isNotBlank(e.getYsyf()))
                // 显式指定类型 + 倒序排序
                .sorted(Comparator.comparingInt((YyHslStatGd e) -> Integer.parseInt(e.getYsyf())).reversed())
                // 使用 LinkedHashMap 保留键的顺序
                .collect(Collectors.groupingBy(YyHslStatGd::getYsyf, LinkedHashMap::new,  // 指定有序 Map
                        Collectors.toList()));
        //获取收费动态数据
        List<YyHslStat> listDt0 = this.baseMapper.hslStatDt(filter, "", "ysyf,");
        List<YyHslStat> listDt1 = this.baseMapper.hslStatDt(filter, "1", "ysyf,");
        List<YyHslStat> listDt2 = this.baseMapper.hslStatDt(filter, "2", "ysyf,");
        List<YyHslStat> listDt3 = this.baseMapper.hslStatDt(filter, "3", "ysyf,");
        List<YyHslStat> listDt = new ArrayList<>();
        if (!listDt0.isEmpty()) {
            listDt.addAll(listDt0);
        }
        if (!listDt1.isEmpty()) {
            listDt.addAll(listDt1);
        }
        if (!listDt2.isEmpty()) {
            listDt.addAll(listDt2);
        }
        if (!listDt3.isEmpty()) {
            listDt.addAll(listDt3);
        }
        Map<String, List<YyHslStat>> yfyfDtMap = listDt.stream().filter(e -> StringUtils.isNotBlank(e.getYsyf()))
                // 显式指定类型 + 倒序排序
                .sorted(Comparator.comparingInt((YyHslStat e) -> Integer.parseInt(e.getYsyf())).reversed())
                // 使用 LinkedHashMap 保留键的顺序
                .collect(Collectors.groupingBy(YyHslStat::getYsyf, LinkedHashMap::new,  // 指定有序 Map
                        Collectors.toList()));


        List<FyhslSelect> results = new ArrayList<>();
        yfyfGdMap.forEach((key, value) -> {
            List<FyhslSelect> result = new ArrayList<>();
            Map<String, List<YyHslStatGd>> cbryGdMap = value.stream()
                    .filter(e -> StringUtils.isNotBlank(e.getCbry()))
                    .collect(Collectors.groupingBy(
                            YyHslStatGd::getCbry,
                            () -> new TreeMap<>(Collator.getInstance(Locale.CHINA)),
                            Collectors.toList()
                    ));

            Map<String, List<YyHslStat>> cbryDtMap = new HashMap<>();
            if (yfyfDtMap.containsKey(key)) {
                cbryDtMap = yfyfDtMap.get(key).stream()
                        .filter(e -> StringUtils.isNotBlank(e.getCbry()))
                        .collect(Collectors.groupingBy(
                                YyHslStat::getCbry,
                                () -> new TreeMap<>(Collator.getInstance(Locale.CHINA)),
                                Collectors.toList()
                        ));
            }

            Map<String, List<YyHslStat>> finalCbryDtMap = cbryDtMap;
            cbryGdMap.forEach((cbry, cbryvalue) -> {
                List<FyhslSelect> item = new ArrayList<>();
                Map<String, List<YyHslStatGd>> sjmcGdMap = cbryvalue.stream()
                        .filter(e -> StringUtils.isNotBlank(e.getSjmc())
                                && !e.getSfbz().equals("4"))
                        .collect(Collectors.groupingBy(
                                YyHslStatGd::getSjmc,
                                () -> new TreeMap<>(Collator.getInstance(Locale.CHINA)),
                                Collectors.toList()
                        ));

                Map<String, List<YyHslStatGd>> sjmcGdbsfMap = cbryvalue.stream()
                        .filter(e -> StringUtils.isNotBlank(e.getSjmc())
                                && e.getSfbz().equals("4"))
                        .collect(Collectors.groupingBy(
                                YyHslStatGd::getSjmc,
                                () -> new TreeMap<>(Collator.getInstance(Locale.CHINA)),
                                Collectors.toList()
                        ));
                sjmcGdbsfMap.forEach((sjmc, sjmcGdbsfvalue) -> {
                    BigDecimal sl = sjmcGdbsfvalue.stream().map(YyHslStatGd::getSl).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal sf = sjmcGdbsfvalue.stream().map(YyHslStatGd::getSf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal wsf = sjmcGdbsfvalue.stream().map(YyHslStatGd::getWsf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal ljf = sjmcGdbsfvalue.stream().map(YyHslStatGd::getLjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal szyf = sjmcGdbsfvalue.stream().map(YyHslStatGd::getSzyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal znj = sjmcGdbsfvalue.stream().map(YyHslStatGd::getZnj).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal hs = sjmcGdbsfvalue.stream().map(YyHslStatGd::getHs).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);

                    FyhslSelect fyhslSelect = new FyhslSelect();
                    fyhslSelect.setYsyf(key);
                    fyhslSelect.setCbry(cbry);
                    fyhslSelect.setYslx(sjmc);
                    fyhslSelect.setYssl(sl);
                    fyhslSelect.setYfsf(sf);
                    fyhslSelect.setYszje(sf.add(wsf).add(ljf).add(szyf));
                    fyhslSelect.setSssf(BigDecimal.ZERO);
                    fyhslSelect.setSszje(BigDecimal.ZERO);
                    fyhslSelect.setSfhsl("0.00%");
                    fyhslSelect.setZfyhsl("0.00%");
                    fyhslSelect.setYshs(hs);
                    fyhslSelect.setQfhs(hs);
                    fyhslSelect.setSshs(BigDecimal.ZERO);
                    fyhslSelect.setHshsl("0.00%");
                    item.add(0, fyhslSelect);
                });

                Map<String, List<YyHslStat>> sjmcDtMap = new HashMap<>();
                if (finalCbryDtMap.containsKey(cbry)) {
                    sjmcDtMap = finalCbryDtMap.get(cbry).stream()
                            .filter(e -> StringUtils.isNotBlank(e.getSjmc()))
                            .collect(Collectors.groupingBy(x -> x.getSjmc()));
                }
                Map<String, List<YyHslStat>> finalSjmcDtMap = sjmcDtMap;
                sjmcGdMap.forEach((sjmc, sjmcGdvalue) -> {
                    List<YyHslStat> sjmcDtvalue = new ArrayList<>();
                    if (finalSjmcDtMap.containsKey(sjmc)) {
                        sjmcDtvalue = finalSjmcDtMap.get(sjmc);
                    }
                    BigDecimal sssf = BigDecimal.ZERO;
                    BigDecimal sswsf = BigDecimal.ZERO;
                    BigDecimal ssljf = BigDecimal.ZERO;
                    BigDecimal ssszyf = BigDecimal.ZERO;
                    BigDecimal ssznj = BigDecimal.ZERO;
                    BigDecimal sshs = BigDecimal.ZERO;
                    if (!sjmcDtvalue.isEmpty()) {
                        sssf = sjmcDtvalue.stream().map(YyHslStat::getSssf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                        sswsf = sjmcDtvalue.stream().map(YyHslStat::getSswsf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                        ssljf = sjmcDtvalue.stream().map(YyHslStat::getSsljf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                        ssszyf = sjmcDtvalue.stream().map(YyHslStat::getSsszyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                        ssznj = sjmcDtvalue.stream().map(YyHslStat::getSsznj).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                        sshs = sjmcDtvalue.stream().map(YyHslStat::getSshs).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                    }
                    BigDecimal sl = sjmcGdvalue.stream().map(YyHslStatGd::getSl).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal sf = sjmcGdvalue.stream().map(YyHslStatGd::getSf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal wsf = sjmcGdvalue.stream().map(YyHslStatGd::getWsf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal ljf = sjmcGdvalue.stream().map(YyHslStatGd::getLjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal szyf = sjmcGdvalue.stream().map(YyHslStatGd::getSzyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal znj = sjmcGdvalue.stream().map(YyHslStatGd::getZnj).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal hs = sjmcGdvalue.stream().map(YyHslStatGd::getHs).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);

                    FyhslSelect fyhslSelect = new FyhslSelect();
                    fyhslSelect.setYsyf(key);
                    fyhslSelect.setCbry(cbry);
                    fyhslSelect.setYslx(sjmc);
                    fyhslSelect.setYssl(sl);
                    fyhslSelect.setYfsf(sf);
                    fyhslSelect.setYszje(sf.add(wsf).add(ljf).add(szyf));
                    fyhslSelect.setSssf(sssf);
                    fyhslSelect.setSszje(sssf.add(sswsf).add(ssljf).add(ssszyf));
                    if (sssf.compareTo(BigDecimal.ZERO) > 0) {
                        fyhslSelect.setSfhsl(sssf.multiply(BigDecimal.valueOf(100)).divide(sf, 2, RoundingMode.HALF_UP) + "%");
                    } else {
                        fyhslSelect.setSfhsl("0.00%");
                    }
                    if (fyhslSelect.getSszje().compareTo(BigDecimal.ZERO) > 0) {
                        fyhslSelect.setZfyhsl(fyhslSelect.getSszje().multiply(BigDecimal.valueOf(100)).divide(fyhslSelect.getYszje(), 2, RoundingMode.HALF_UP) + "%");
                    } else {
                        fyhslSelect.setZfyhsl("0.00%");
                    }
                    fyhslSelect.setYshs(hs);
                    fyhslSelect.setQfhs(hs.subtract(sshs));
                    fyhslSelect.setSshs(sshs);
                    if (sshs.compareTo(BigDecimal.ZERO) > 0) {
                        fyhslSelect.setHshsl(sshs.multiply(BigDecimal.valueOf(100)).divide(hs, 2, RoundingMode.HALF_UP) + "%");
                    } else {
                        fyhslSelect.setHshsl("0.00%");
                    }
                    item.add(fyhslSelect);
                });
                //抄表员小计
                if (!item.isEmpty()) {
                    FyhslSelect fyhslSelect = new FyhslSelect();
                    fyhslSelect.setYsyf(key);
                    fyhslSelect.setCbry(cbry);
                    fyhslSelect.setYslx("小计");
                    fyhslSelect.setYssl(item.stream().map(FyhslSelect::getYssl).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add));
                    fyhslSelect.setYfsf(item.stream().map(FyhslSelect::getYfsf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add));
                    fyhslSelect.setYszje(item.stream().map(FyhslSelect::getYszje).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add));
                    fyhslSelect.setSssf(item.stream().map(FyhslSelect::getSssf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add));
                    fyhslSelect.setSszje(item.stream().map(FyhslSelect::getSszje).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add));
                    if (fyhslSelect.getSssf().compareTo(BigDecimal.ZERO) > 0) {
                        fyhslSelect.setSfhsl(fyhslSelect.getSssf().multiply(BigDecimal.valueOf(100)).divide(fyhslSelect.getYfsf(), 2, RoundingMode.HALF_UP) + "%");
                    } else {
                        fyhslSelect.setSfhsl("0.00%");
                    }
                    if (fyhslSelect.getSszje().compareTo(BigDecimal.ZERO) > 0) {
                        fyhslSelect.setZfyhsl(fyhslSelect.getSszje().multiply(BigDecimal.valueOf(100)).divide(fyhslSelect.getYszje(), 2, RoundingMode.HALF_UP) + "%");
                    } else {
                        fyhslSelect.setZfyhsl("0.00%");
                    }
                    fyhslSelect.setYshs(item.stream().map(FyhslSelect::getYshs).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add));
                    fyhslSelect.setQfhs(item.stream().map(FyhslSelect::getQfhs).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add));
                    fyhslSelect.setSshs(item.stream().map(FyhslSelect::getSshs).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add));
                    if (fyhslSelect.getSshs().compareTo(BigDecimal.ZERO) > 0) {
                        fyhslSelect.setHshsl(fyhslSelect.getSshs().multiply(BigDecimal.valueOf(100)).divide(fyhslSelect.getYshs(), 2, RoundingMode.HALF_UP) + "%");
                    } else {
                        fyhslSelect.setHshsl("0.00%");
                    }
                    item.add(fyhslSelect);
                }
                result.addAll(item);
            });
            //用水月份小计（只需查询出抄表员小计数据）
            if (!result.isEmpty()) {
                FyhslSelect fyhslSelect = new FyhslSelect();
                fyhslSelect.setYsyf(key);
                fyhslSelect.setCbry("小计");
                fyhslSelect.setYslx("");
                fyhslSelect.setYssl(result.stream().filter(i -> i.getYslx().equals("小计")).map(FyhslSelect::getYssl).reduce(BigDecimal.ZERO, BigDecimal::add));
                fyhslSelect.setYfsf(result.stream().filter(i -> i.getYslx().equals("小计")).map(FyhslSelect::getYfsf).reduce(BigDecimal.ZERO, BigDecimal::add));
                fyhslSelect.setYszje(result.stream().filter(i -> i.getYslx().equals("小计")).map(FyhslSelect::getYszje).reduce(BigDecimal.ZERO, BigDecimal::add));
                fyhslSelect.setSssf(result.stream().filter(i -> i.getYslx().equals("小计")).map(FyhslSelect::getSssf).reduce(BigDecimal.ZERO, BigDecimal::add));
                fyhslSelect.setSszje(result.stream().filter(i -> i.getYslx().equals("小计")).map(FyhslSelect::getSszje).reduce(BigDecimal.ZERO, BigDecimal::add));
                if (fyhslSelect.getSssf().compareTo(BigDecimal.ZERO) > 0) {
                    fyhslSelect.setSfhsl(fyhslSelect.getSssf().multiply(BigDecimal.valueOf(100)).divide(fyhslSelect.getYfsf(), 2, RoundingMode.HALF_UP) + "%");
                } else {
                    fyhslSelect.setSfhsl("0.00%");
                }
                if (fyhslSelect.getSszje().compareTo(BigDecimal.ZERO) > 0) {
                    fyhslSelect.setZfyhsl(fyhslSelect.getSszje().multiply(BigDecimal.valueOf(100)).divide(fyhslSelect.getYszje(), 2, RoundingMode.HALF_UP) + "%");
                } else {
                    fyhslSelect.setZfyhsl("0.00%");
                }
                fyhslSelect.setYshs(result.stream().filter(i -> i.getYslx().equals("小计")).map(FyhslSelect::getYshs).reduce(BigDecimal.ZERO, BigDecimal::add));
                fyhslSelect.setQfhs(result.stream().filter(i -> i.getYslx().equals("小计")).map(FyhslSelect::getQfhs).reduce(BigDecimal.ZERO, BigDecimal::add));
                fyhslSelect.setSshs(result.stream().filter(i -> i.getYslx().equals("小计")).map(FyhslSelect::getSshs).reduce(BigDecimal.ZERO, BigDecimal::add));
                if (fyhslSelect.getSshs().compareTo(BigDecimal.ZERO) > 0) {
                    fyhslSelect.setHshsl(fyhslSelect.getSshs().multiply(BigDecimal.valueOf(100)).divide(fyhslSelect.getYshs(), 2, RoundingMode.HALF_UP) + "%");
                } else {
                    fyhslSelect.setHshsl("0.00%");
                }
                result.add(fyhslSelect);
            }
            results.addAll(result);
        });
        //合计所有（只需查询出用水月份小计）
        if (!results.isEmpty()) {
            FyhslSelect fyhslSelect = new FyhslSelect();
            fyhslSelect.setYsyf("合计");
            fyhslSelect.setCbry("");
            fyhslSelect.setYslx("");
            fyhslSelect.setYssl(results.stream().filter(i -> i.getCbry().equals("小计")).map(FyhslSelect::getYssl).reduce(BigDecimal.ZERO, BigDecimal::add));
            fyhslSelect.setYfsf(results.stream().filter(i -> i.getCbry().equals("小计")).map(FyhslSelect::getYfsf).reduce(BigDecimal.ZERO, BigDecimal::add));
            fyhslSelect.setYszje(results.stream().filter(i -> i.getCbry().equals("小计")).map(FyhslSelect::getYszje).reduce(BigDecimal.ZERO, BigDecimal::add));
            fyhslSelect.setSssf(results.stream().filter(i -> i.getCbry().equals("小计")).map(FyhslSelect::getSssf).reduce(BigDecimal.ZERO, BigDecimal::add));
            fyhslSelect.setSszje(results.stream().filter(i -> i.getCbry().equals("小计")).map(FyhslSelect::getSszje).reduce(BigDecimal.ZERO, BigDecimal::add));
            if (fyhslSelect.getSssf().compareTo(BigDecimal.ZERO) > 0) {
                fyhslSelect.setSfhsl(fyhslSelect.getSssf().multiply(BigDecimal.valueOf(100)).divide(fyhslSelect.getYfsf(), 2, RoundingMode.HALF_UP) + "%");
            } else {
                fyhslSelect.setSfhsl("0.00%");
            }
            if (fyhslSelect.getSszje().compareTo(BigDecimal.ZERO) > 0) {
                fyhslSelect.setZfyhsl(fyhslSelect.getSszje().multiply(BigDecimal.valueOf(100)).divide(fyhslSelect.getYszje(), 2, RoundingMode.HALF_UP) + "%");
            } else {
                fyhslSelect.setZfyhsl("0.00%");
            }
            fyhslSelect.setYshs(results.stream().filter(i -> i.getCbry().equals("小计")).map(FyhslSelect::getYshs).reduce(BigDecimal.ZERO, BigDecimal::add));
            fyhslSelect.setQfhs(results.stream().filter(i -> i.getCbry().equals("小计")).map(FyhslSelect::getQfhs).reduce(BigDecimal.ZERO, BigDecimal::add));
            fyhslSelect.setSshs(results.stream().filter(i -> i.getCbry().equals("小计")).map(FyhslSelect::getSshs).reduce(BigDecimal.ZERO, BigDecimal::add));
            if (fyhslSelect.getSshs().compareTo(BigDecimal.ZERO) > 0) {
                fyhslSelect.setHshsl(fyhslSelect.getSshs().multiply(BigDecimal.valueOf(100)).divide(fyhslSelect.getYshs(), 2, RoundingMode.HALF_UP) + "%");
            } else {
                fyhslSelect.setHshsl("0.00%");
            }
            results.add(fyhslSelect);
        }
        return results;
    }

    @Override
    public YyQfmx createByPartialCharges(YyQfmx original, List<Integer> chargeTypes, String sflsbh) {
        if (ObjectUtil.isNull(original)) {
            throw new ToflyDeniedException("原欠费明细数据异常");
        }

        original.setSflsbh(null);
        log.info("原欠费明细: ==============> {}", JSONUtil.toJsonStr(original));

        YyQfmx chargeDetail = createChargeDetail(sflsbh);

        chargeTypes.forEach(type -> {
            initDetailByChargeType(type, original, chargeDetail);
        });

        BigDecimal tjysje = tjysje(chargeDetail);
        chargeDetail.setYsje(tjysje);
        log.info("部分缴费明细: ==============> {}", JSONUtil.toJsonStr(chargeDetail));
        statisticaCharge(chargeDetail);

        chargeDetail.setSflsbh(sflsbh);
        baseMapper.insert(chargeDetail);

        baseMapper.updateById(original);
        return chargeDetail;
    }

    private BigDecimal tjysje(YyQfmx chargeDetail) {
        BigDecimal yssf = checkNumberFormat(chargeDetail.getYssf());
        BigDecimal yswsf = checkNumberFormat(chargeDetail.getYswsf());
        BigDecimal ysszyf = checkNumberFormat(chargeDetail.getYsszyf());
        BigDecimal ysecjyf = checkNumberFormat(chargeDetail.getYsecjyf());
        BigDecimal ysfjf = checkNumberFormat(chargeDetail.getYsfjf());
        BigDecimal ysqtf = checkNumberFormat(chargeDetail.getYsqt());
        return yssf.add(yswsf).add(ysszyf).add(ysecjyf).add(ysfjf).add(ysqtf);
    }

    @Override
    public List<YyQfmx> selectQfmxBatch(List<String> yhbhs, String cwrq) {
        if (CollectionUtil.isEmpty(yhbhs)) {
            return new ArrayList<>();
        }

        LambdaQueryWrapper<YyQfmx> queryWrapper = Wrappers.<YyQfmx>lambdaQuery()
                .eq(YyQfmx::getCwrq, cwrq).in(YyQfmx::getYhbh, yhbhs)
                .eq(YyQfmx::getSfbz, "0");

        return baseMapper.selectList(queryWrapper);
    }


    private void statisticaCharge(YyQfmx chargeDetail) {
        BigDecimal yssf = checkNumberFormat(chargeDetail.getYssf());

        BigDecimal yswsf = checkNumberFormat(chargeDetail.getYswsf());

        BigDecimal ysszyf = checkNumberFormat(chargeDetail.getYsszyf());

        BigDecimal ysecjyf = checkNumberFormat(chargeDetail.getYsecjyf());

        BigDecimal ysfjf = checkNumberFormat(chargeDetail.getYsfjf());

        BigDecimal ysxfsf = checkNumberFormat(chargeDetail.getYsqt());

        BigDecimal ysje = yssf.add(yswsf).add(ysszyf).add(ysecjyf).add(ysfjf).add(ysxfsf);
        chargeDetail.setYsje(ysje);
    }

    private YyQfmx createChargeDetail(String sflsbh) {
        YyQfmx chargeDetail = new YyQfmx();
        long currentTimeMillis = System.currentTimeMillis();
        String partialId = String.valueOf(currentTimeMillis);
        chargeDetail.setId(partialId);
        chargeDetail.setSfrq(new Date());
        chargeDetail.setSfbz("1");
        chargeDetail.setSflsbh(sflsbh);
        return chargeDetail;
    }

    private YyQfmx initDetailByChargeType(Integer chargeType, YyQfmx original, YyQfmx chargeDetail) {

        // 新明细只保留已交费信息,原明细已交费部分置为0
        if (ChargeTypeEnum.WATER.getValue().equals(chargeType)) {

            BeanUtil.copyProperties(original, chargeDetail,
                    "id", "wsfdj3", "wsf3", "ljfdj3", "ljf3", "szyfDj3", "szyf3",
                    "ysljf", "ysszyf", "wsfdj", "wsf", "ljfdj", "ljf", "sfbz", "yswsf",
                    "szyfDj", "szyf", "wsfdj1", "wsf1", "ljfdj1", "ljf1", "szyfDj1", "szyf1",
                    "wsfdj2", "wsf2", "ljfdj2", "ljf2", "szyfDj2", "szyf2", "ecjyf",
                    "ecjyfdj", "ysecjyf", "fjf", "fjfdj", "ysfjf", "ysqt");

            // 原明细删减已缴费部分
            BigDecimal originalYsje = original.getYsje();
            BigDecimal subtract = originalYsje.subtract(original.getYssf());
            original.setYsje(subtract);

            original.setYssf(BigDecimal.ZERO);
            original.setSf(BigDecimal.ZERO);
            original.setSf1(BigDecimal.ZERO);
            original.setSf2(BigDecimal.ZERO);
            original.setSf3(BigDecimal.ZERO);

            original.setSj(BigDecimal.ZERO);
            original.setSl(BigDecimal.ZERO);
            original.setSj1(BigDecimal.ZERO);
            original.setSl1(BigDecimal.ZERO);
            original.setSj2(BigDecimal.ZERO);
            original.setSl2(BigDecimal.ZERO);
            original.setSj3(BigDecimal.ZERO);
            original.setSl3(BigDecimal.ZERO);
        } else if (ChargeTypeEnum.EFFLUENT.getValue().equals(chargeType)) {
            BeanUtil.copyProperties(original, chargeDetail, "id", "sf3", "ljfdj3", "ljf3",
                    "szyfDj3", "szyf3", "yssf", "ysljf", "ysszyf", "ysqt", "jt1sl", "jt1sj", "jt1sf",
                    "jt2sl", "jt2sj", "jt2sf", "jt3sl", "jt3sj", "jt3sf", "jt4sl", "jt4sj", "jt4sf", "znjts", "sfbz",
                    "znjfl", "znj", "znjjsrq", "sj1Jt1sl", "sj1Jt1sj", "sj1Jt1sf", "sj1Jt2sl", "sj1Jt2sj", "sj1Jt2sf",
                    "sj1Jt3sl", "sj1Jt3sj", "sj1Jt3sf", "sj1Jt4sl", "sj1Jt4sf", "sj1Jt4sj", "sj2Jt1sl", "sj2Jt1sj",
                    "sj2Jt1sf", "sj2Jt2sl", "sj2Jt2sj", "sj2Jt2sf", "sj2Jt3sl", "sj2Jt3sj", "sj2Jt3sf", "sj2Jt4sl",
                    "sj2Jt4sj", "sj2Jt4sf", "sj", "sf", "ljfdj", "ljf", "szyfDj", "szyf", "sj1", "sl1",
                    "sf1", "ljfdj1", "szyfDj1", "szyf1", "sj2", "sl2", "sf2", "ljfdj2", "ljf2", "szyfDj2", "szyf2",
                    "sj3", "sl3", "ecjyf", "ecjyfdj", "ysecjyf", "fjf", "fjfdj", "ysfjf");

            BigDecimal originalYsje = original.getYsje();
            BigDecimal subtract = originalYsje.subtract(original.getYswsf());
            original.setYsje(subtract);

            original.setYswsf(BigDecimal.ZERO);
            original.setWsf(BigDecimal.ZERO);
            original.setWsf1(BigDecimal.ZERO);
            original.setWsf2(BigDecimal.ZERO);
            original.setWsf3(BigDecimal.ZERO);

            original.setWsfdj(BigDecimal.ZERO);
            original.setWsfdj1(BigDecimal.ZERO);
            original.setWsfdj2(BigDecimal.ZERO);
            original.setWsfdj3(BigDecimal.ZERO);
        } else if (ChargeTypeEnum.WATER_TAX.getValue().equals(chargeType)) {
            BeanUtil.copyProperties(original, chargeDetail, "id", "sf3", "ljfdj3", "ljf3",
                    "wsfdj3", "wsf3", "yssf", "ysljf", "yswsf", "ysqt", "jt1sl", "jt1sj", "jt1sf",
                    "jt2sl", "jt2sj", "jt2sf", "jt3sl", "jt3sj", "jt3sf", "jt4sl", "jt4sj", "jt4sf", "znjts", "sfbz",
                    "znjfl", "znj", "znjjsrq", "sj1Jt1sl", "sj1Jt1sj", "sj1Jt1sf", "sj1Jt2sl", "sj1Jt2sj", "sj1Jt2sf",
                    "sj1Jt3sl", "sj1Jt3sj", "sj1Jt3sf", "sj1Jt4sl", "sj1Jt4sf", "sj1Jt4sj", "sj2Jt1sl", "sj2Jt1sj",
                    "sj2Jt1sf", "sj2Jt2sl", "sj2Jt2sj", "sj2Jt2sf", "sj2Jt3sl", "sj2Jt3sj", "sj2Jt3sf", "sj2Jt4sl",
                    "sj2Jt4sj", "sj2Jt4sf", "sl", "sj", "sf", "ljfdj", "ljf", "wsfdj", "wsf", "sj1", "sl1",
                    "sf1", "ljfdj1", "wsfdj1", "wsf1", "sj2", "sl2", "sf2", "ljfdj2", "ljf2", "wsfdj2", "wsf2",
                    "sj3", "sl3", "ecjyf", "ecjyfdj", "ysecjyf", "fjf", "fjfdj", "ysfjf");

            BigDecimal originalYsje = original.getYsje();
            BigDecimal subtract = originalYsje.subtract(original.getYsszyf());
            original.setYsje(subtract);

            original.setYsszyf(BigDecimal.ZERO);
            original.setSzyf(BigDecimal.ZERO);
            original.setSzyf1(BigDecimal.ZERO);
            original.setSzyf2(BigDecimal.ZERO);
            original.setSzyf3(BigDecimal.ZERO);

            original.setSzyfDj(BigDecimal.ZERO);
            original.setSzyfDj1(BigDecimal.ZERO);
            original.setSzyfDj2(BigDecimal.ZERO);
            original.setSzyfDj3(BigDecimal.ZERO);
        } else if (ChargeTypeEnum.PRESSURIZE.getValue().equals(chargeType)) {

            BeanUtil.copyProperties(original, chargeDetail, "id", "sf3", "ljfdj3", "ljf3",
                    "wsfdj3", "wsf3", "yssf", "ysljf", "yswsf", "ysqt", "jt1sl", "jt1sj", "jt1sf",
                    "jt2sl", "jt2sj", "jt2sf", "jt3sl", "jt3sj", "jt3sf", "jt4sl", "jt4sj", "jt4sf", "znjts",
                    "znjfl", "znj", "znjjsrq", "sj1Jt1sl", "sj1Jt1sj", "sj1Jt1sf", "sj1Jt2sl", "sj1Jt2sj", "sj1Jt2sf",
                    "sj1Jt3sl", "sj1Jt3sj", "sj1Jt3sf", "sj1Jt4sl", "sj1Jt4sf", "sj1Jt4sj", "sj2Jt1sl", "sj2Jt1sj",
                    "sj2Jt1sf", "sj2Jt2sl", "sj2Jt2sj", "sj2Jt2sf", "sj2Jt3sl", "sj2Jt3sj", "sj2Jt3sf", "sj2Jt4sl",
                    "sj2Jt4sj", "sj2Jt4sf", "sl", "sj", "sf", "ljfdj", "ljf", "wsfdj", "wsf", "sj1", "sl1",
                    "sf1", "ljfdj1", "wsfdj1", "wsf1", "sj2", "sl2", "sf2", "ljfdj2", "ljf2", "wsfdj2", "wsf2",
                    "ysszyf", "szyf", "szyfDj", "szyf1", "szyfDj1", "szyf2", "szyfDj2", "szyf3", "szyfDj3", "sfbz",
                    "sj3", "sl3", "fjf", "fjfdj", "ysfjf");

            BigDecimal originalYsje = original.getYsje();
            BigDecimal ysecfjf = checkNumberFormat(original.getYsecjyf());
            BigDecimal subtract = originalYsje.subtract(ysecfjf);
            original.setYsje(subtract);

            original.setYsecjyf(BigDecimal.ZERO);
            original.setEcjyf(BigDecimal.ZERO);
            original.setEcjyfdj(BigDecimal.ZERO);
        } else if (ChargeTypeEnum.ADDITIONAL.getValue().equals(chargeType)) {

            BeanUtil.copyProperties(original, chargeDetail, "id", "sf3", "ljfdj3", "ljf3",
                    "wsfdj3", "wsf3", "yssf", "ysljf", "yswsf", "ysqt", "jt1sl", "jt1sj", "jt1sf",
                    "jt2sl", "jt2sj", "jt2sf", "jt3sl", "jt3sj", "jt3sf", "jt4sl", "jt4sj", "jt4sf", "znjts",
                    "znjfl", "znj", "znjjsrq", "sj1Jt1sl", "sj1Jt1sj", "sj1Jt1sf", "sj1Jt2sl", "sj1Jt2sj", "sj1Jt2sf",
                    "sj1Jt3sl", "sj1Jt3sj", "sj1Jt3sf", "sj1Jt4sl", "sj1Jt4sf", "sj1Jt4sj", "sj2Jt1sl", "sj2Jt1sj",
                    "sj2Jt1sf", "sj2Jt2sl", "sj2Jt2sj", "sj2Jt2sf", "sj2Jt3sl", "sj2Jt3sj", "sj2Jt3sf", "sj2Jt4sl",
                    "sj2Jt4sj", "sj2Jt4sf", "sl", "sj", "sf", "ljfdj", "ljf", "wsfdj", "wsf", "sj1", "sl1", "sfbz",
                    "sf1", "ljfdj1", "wsfdj1", "wsf1", "sj2", "sl2", "sf2", "ljfdj2", "ljf2", "wsfdj2", "wsf2",
                    "ysszyf", "szyf", "szyfDj", "szyf1", "szyfDj1", "szyf2", "szyfDj2", "szyf3", "szyfDj3",
                    "sj3", "sl3", "ecjyf", "ecjyfdj", "ysecjyf");

            BigDecimal originalYsje = original.getYsje();
            BigDecimal ysfjf = checkNumberFormat(original.getYsfjf());
            BigDecimal subtract = originalYsje.subtract(ysfjf);
            original.setYsje(subtract);

            original.setYsfjf(BigDecimal.ZERO);
            original.setFjf(BigDecimal.ZERO);
            original.setFjfdj(BigDecimal.ZERO);
        } else if (ChargeTypeEnum.FIRE_HYDRANT.getValue().equals(chargeType)) {

            BeanUtil.copyProperties(original, chargeDetail, "id", "sf3", "ljfdj3", "ljf3",
                    "wsfdj3", "wsf3", "yssf", "ysljf", "yswsf", "jt1sl", "jt1sj", "jt1sf",
                    "jt2sl", "jt2sj", "jt2sf", "jt3sl", "jt3sj", "jt3sf", "jt4sl", "jt4sj", "jt4sf", "znjts",
                    "znjfl", "znj", "znjjsrq", "sj1Jt1sl", "sj1Jt1sj", "sj1Jt1sf", "sj1Jt2sl", "sj1Jt2sj", "sj1Jt2sf",
                    "sj1Jt3sl", "sj1Jt3sj", "sj1Jt3sf", "sj1Jt4sl", "sj1Jt4sf", "sj1Jt4sj", "sj2Jt1sl", "sj2Jt1sj",
                    "sj2Jt1sf", "sj2Jt2sl", "sj2Jt2sj", "sj2Jt2sf", "sj2Jt3sl", "sj2Jt3sj", "sj2Jt3sf", "sj2Jt4sl",
                    "sj2Jt4sj", "sj2Jt4sf", "sl", "sj", "sf", "ljfdj", "ljf", "wsfdj", "wsf", "sj1", "sl1", "sfbz",
                    "sf1", "ljfdj1", "wsfdj1", "wsf1", "sj2", "sl2", "sf2", "ljfdj2", "ljf2", "wsfdj2", "wsf2",
                    "ysszyf", "szyf", "szyfDj", "szyf1", "szyfDj1", "szyf2", "szyfDj2", "szyf3", "szyfDj3",
                    "sj3", "sl3", "ecjyf", "ecjyfdj", "ysecjyf", "fjf", "fjfdj", "ysfjf");

            BigDecimal originalYsje = original.getYsje();
            BigDecimal ysxfsf = checkNumberFormat(original.getYsqt());
            BigDecimal subtract = originalYsje.subtract(ysxfsf);
            original.setYsje(subtract);

            original.setYsqt(BigDecimal.ZERO);
        }

        return chargeDetail;
    }

    private BigDecimal checkNumberFormat(BigDecimal fy) {
        return ObjectUtil.isNull(fy) ? BigDecimal.ZERO : fy;
    }

    /**
     * 欠费统计报表（按月统计）
     */
    @Override
    public List<YyQfmxMonthlyStat> monthlyStat1(YyQfmxStatFilter filter) {
        List<YySjStat> list = new ArrayList<>();

        String cwrqorysyf = "ysyf,";
        // 1、非阶梯费用
        List<YySjStat> list0 = this.baseMapper.sjStat(filter, "", cwrqorysyf);
        List<YySjStat> list1 = this.baseMapper.sjStat(filter, "1", cwrqorysyf);
        List<YySjStat> list2 = this.baseMapper.sjStat(filter, "2", cwrqorysyf);
        //List<YySjStat> list3 = this.baseMapper.sjStat(filter, "3", cwrqorysyf);

        if (CollectionUtil.isNotEmpty(list0)) {
            //费用不等于并且水量也不等于零
            list.addAll(list0.stream().filter(i ->
                    !i.getSf().add(i.getLjf()).add(i.getWsf()).add(i.getSzyf())
                            .add(i.getEcjyf()).add(i.getFjf()).add(i.getQtf()).equals(BigDecimal.ZERO) ||
                            !i.getSl().equals(BigDecimal.ZERO)).collect(Collectors.toList()));
        }
        if (CollectionUtil.isNotEmpty(list1)) {
            list.addAll(list1);
        }
        if (CollectionUtil.isNotEmpty(list2)) {
            list.addAll(list2);
        }
//        if (CollectionUtil.isNotEmpty(list3)) {
//            list.addAll(list3);
//        }
        BigDecimal bc = baseMapper.bcStat(filter) == null ? BigDecimal.ZERO : baseMapper.bcStat(filter);

        Map<String, List<YySjStat>> fjtcwrqMap = list.stream().filter(e -> StringUtils.isNotBlank(e.getYsyf()))
                .sorted(Comparator.comparingInt((YySjStat e) -> Integer.parseInt(e.getYsyf())))
                .collect(Collectors.groupingBy(YySjStat::getYsyf, LinkedHashMap::new, Collectors.toList()));

        // 2、阶梯费用
        List<YySjStat> jtlist = new ArrayList<>();
        List<YySjStat> list4 = this.baseMapper.sjjtStat(filter, "1", cwrqorysyf, "");
        List<YySjStat> list5 = this.baseMapper.sjjtStat(filter, "2", cwrqorysyf, "");
        List<YySjStat> list6 = this.baseMapper.sjjtStat(filter, "3", cwrqorysyf, "");
        if (CollectionUtil.isNotEmpty(list4)) {
            jtlist.addAll(list4);
        }
        if (CollectionUtil.isNotEmpty(list5)) {
            jtlist.addAll(list5);
        }
        if (CollectionUtil.isNotEmpty(list6)) {
            jtlist.addAll(list6);
        }

        Map<String, List<YySjStat>> jtcwrqMap = jtlist.stream().filter(e -> StringUtils.isNotBlank(e.getYsyf()))
                .sorted(Comparator.comparingInt((YySjStat e) -> Integer.parseInt(e.getYsyf())))
                .collect(Collectors.groupingBy(YySjStat::getYsyf, LinkedHashMap::new, Collectors.toList()));


        List<YyQfmxMonthlyStat> results = new ArrayList<>();
        List<BmSj> sjList = getSjMap();

        if (StringUtil.isNotEmpty(filter.getYslx())) {
            sjList = sjList.stream().filter(e -> e.getYslx().equals(filter.getYslx()))
                    .sorted(Comparator.comparing(e -> e.getName(), Collator.getInstance(Locale.CHINA)))
                    .collect(Collectors.toList());
        }

        // 用水月份
        List<String> cwrqlist = new ArrayList<>();
        cwrqlist.addAll(list.stream().map(e -> e.getYsyf()).distinct().collect(Collectors.toList()));
        cwrqlist.addAll(jtlist.stream().map(e -> e.getYsyf()).distinct().collect(Collectors.toList()));
        cwrqlist = cwrqlist.stream().distinct()
                .sorted(Comparator.comparingInt((String e) -> Integer.parseInt(e)))
                .collect(Collectors.toList());

        // 月份循环
        List<BmSj> finalSjList = sjList;
        cwrqlist.forEach(key -> {
            List<YyQfmxMonthlyStat> result = new ArrayList<>();
            //阶梯
            Map<String, List<YySjStat>> jtSjmxMap = Optional.ofNullable(jtcwrqMap)
                    .map(m -> m.getOrDefault(key, new ArrayList<>()))
                    .orElse(new ArrayList<>()).stream()
                    .filter(e -> StringUtils.isNotBlank(e.getSjbm()))
                    .collect(Collectors.groupingBy(x -> x.getSjbm()));
            // 非阶梯
            List<YySjStat> value = Optional.ofNullable(fjtcwrqMap)
                    .map(m -> m.getOrDefault(key, new ArrayList<>()))
                    .orElse(new ArrayList<>());

            // 需要收费记录
            Map<String, List<YySjStat>> sjmxMap = value.stream()
                    .filter(e -> StringUtils.isNotBlank(e.getSjbm()) && !e.getSfbz().equals("4"))
                    .collect(Collectors.groupingBy(x -> x.getSjbm()));

            // 不收费费用记录
            Map<String, List<YySjStat>> sjmxbsfMap = value.stream()
                    .filter(e -> StringUtils.isNotBlank(e.getSjbm()) && e.getSfbz().equals("4"))
                    .collect(Collectors.groupingBy(x -> x.getSjbm()));
            /*不收费费用记录不显示*/
//            if (!sjmxbsfMap.isEmpty()) {
//                for (List<YySjStat> yySjStats : sjmxbsfMap.values()) {
//                    BmSj bmsj = finalSjList.stream().filter(e -> e.getCode().equals(yySjStats.get(0).getSjbm())).findFirst().get();
//                    BigDecimal sl = yySjStats.stream().map(YySjStat::getSl).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                    BigDecimal sf = yySjStats.stream().map(YySjStat::getSf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                    BigDecimal wsf = yySjStats.stream().map(YySjStat::getWsf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                    BigDecimal ljf = yySjStats.stream().map(YySjStat::getLjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                    BigDecimal szyf = yySjStats.stream().map(YySjStat::getSzyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                    BigDecimal bs = yySjStats.stream().map(YySjStat::getBs).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                    BigDecimal znj = yySjStats.stream().map(YySjStat::getZnj).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//
//                    BigDecimal ecjyf = yySjStats.stream().map(YySjStat::getEcjyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                    BigDecimal fjf = yySjStats.stream().map(YySjStat::getFjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                    BigDecimal qtf = yySjStats.stream().map(YySjStat::getQtf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//
//                    BigDecimal add = sf.add(wsf).add(ljf).add(szyf).add(ecjyf).add(fjf).add(qtf);
//                    result.add(0, new YyQfmxMonthlyStat(key, bmsj.getName(), BigDecimal.ZERO, BigDecimal.ZERO, sl, sf, wsf, ljf, szyf, znj, add, bs, ecjyf, fjf, qtf));
//                }
//            }

            for (BmSj bmsj : finalSjList) {
                List<YySjStat> sjmxs = sjmxMap.getOrDefault(bmsj.getCode(), new ArrayList<>());
                BigDecimal sl = sjmxs.stream().map(YySjStat::getSl).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal sf = sjmxs.stream().map(YySjStat::getSf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal wsf = sjmxs.stream().map(YySjStat::getWsf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal ljf = sjmxs.stream().map(YySjStat::getLjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal szyf = sjmxs.stream().map(YySjStat::getSzyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal bs = sjmxs.stream().map(YySjStat::getBs).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal znj = sjmxs.stream().map(YySjStat::getZnj).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);

                BigDecimal ecjyf = sjmxs.stream().map(YySjStat::getEcjyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal fjf = sjmxs.stream().map(YySjStat::getFjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal qtf = sjmxs.stream().map(YySjStat::getQtf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);

                if (bmsj.getJtbz().equals("0")) {
                    BigDecimal hjysje = sf.add(wsf).add(ljf).add(szyf).add(ecjyf).add(fjf).add(qtf);
                    if (hjysje.compareTo(BigDecimal.ZERO) != 0 || !sl.equals(BigDecimal.ZERO)) {
                        BigDecimal hjsj = bmsj.getSj().add(bmsj.getWsfdj()).add(bmsj.getSzyfdj());
                        BigDecimal add = sf.add(wsf).add(ljf).add(szyf).add(ecjyf).add(fjf).add(qtf);
                        result.add(new YyQfmxMonthlyStat(key, bmsj.getName(), bmsj.getSj(), hjsj, sl, sf, wsf, ljf, szyf, znj, add, bs, ecjyf, fjf, qtf));
                    }
                } else {
                    List<YySjStat> jtsjmxs = jtSjmxMap.getOrDefault(bmsj.getCode(), new ArrayList<>());
                    //获取需要收费的阶梯费用明细
                    Map<BigDecimal, List<YySjStat>> jtsjmxsMap = jtsjmxs.stream().filter(
                            e -> StringUtils.isNotBlank(e.getSjbm())
                                    && !e.getSfbz().equals("4")
                            //&& e.getSj().compareTo(BigDecimal.ZERO) != 0
                    ).collect(Collectors.groupingBy(x -> x.getSj()));

                    //获取需要不收费的阶梯费用明细
                    List<YySjStat> jtbsfyySjStats = jtsjmxs.stream().filter(
                            e -> StringUtils.isNotBlank(e.getSjbm()) && e.getSfbz().equals("4")
                                    && e.getSl().compareTo(BigDecimal.ZERO) > 0
                    ).collect(Collectors.toList());
                    /*不收费费用记录不显示*/
//                    if (!jtbsfyySjStats.isEmpty()) {
//                        BigDecimal bsfsl = jtbsfyySjStats.stream().map(YySjStat::getSl).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                        BigDecimal bsfsf = jtbsfyySjStats.stream().map(YySjStat::getSf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                        BigDecimal bsfwsf = jtbsfyySjStats.stream().map(YySjStat::getWsf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                        BigDecimal bsfljf = jtbsfyySjStats.stream().map(YySjStat::getLjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                        BigDecimal bsfszyf = jtbsfyySjStats.stream().map(YySjStat::getSzyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                        BigDecimal bsfbs = jtbsfyySjStats.stream().map(YySjStat::getBs).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                        BigDecimal bsfznj = jtbsfyySjStats.stream().map(YySjStat::getZnj).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//
//                        BigDecimal ecjyfs = jtbsfyySjStats.stream().map(YySjStat::getEcjyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                        BigDecimal fjfs = jtbsfyySjStats.stream().map(YySjStat::getFjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                        BigDecimal qtfs = jtbsfyySjStats.stream().map(YySjStat::getQtf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//
//                        BigDecimal add = bsfsf.add(bsfwsf).add(bsfljf).add(bsfszyf).add(ecjyfs).add(fjfs).add(qtfs);
//                        result.add(0, new YyQfmxMonthlyStat(key, bmsj.getName(), BigDecimal.ZERO, BigDecimal.ZERO, bsfsl, bsfsf, bsfwsf, bsfljf, bsfszyf, bsfznj, add, bsfbs, ecjyfs, fjfs, qtfs));
//                    }
//                    List<YySjStat> zeroSjs = jtsjmxs.stream().filter(
//                            e -> StringUtils.isNotBlank(e.getSjbm())
//                                    && e.getSj().compareTo(BigDecimal.ZERO) == 0
//                                    && e.getSf().add(e.getWsf()).add(e.getLjf()).add(e.getSzyf()).compareTo(BigDecimal.ZERO) != 0
//                                    && !e.getSfbz().equals("4")
//                    ).collect(Collectors.toList());
//                    int i = 0;
                    for (List<YySjStat> yySjStats : jtsjmxsMap.values()) {
                        BigDecimal jtsl = yySjStats.stream().map(YySjStat::getSl).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                        BigDecimal jtsf = yySjStats.stream().map(YySjStat::getSf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                        BigDecimal jtwsf = yySjStats.stream().map(YySjStat::getWsf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                        BigDecimal jtljf = yySjStats.stream().map(YySjStat::getLjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                        BigDecimal jtszyf = yySjStats.stream().map(YySjStat::getSzyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                        BigDecimal jtbs = yySjStats.stream().map(YySjStat::getBs).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                        BigDecimal jtznj = yySjStats.stream().map(YySjStat::getZnj).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);

                        BigDecimal ecjyfs = yySjStats.stream().map(YySjStat::getEcjyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                        BigDecimal fjfs = yySjStats.stream().map(YySjStat::getFjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                        BigDecimal qtfs = yySjStats.stream().map(YySjStat::getQtf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);

                        BigDecimal jthjysje = jtsf.add(jtwsf).add(jtljf).add(jtszyf).add(ecjyfs).add(fjfs).add(qtfs);
                        if (jthjysje.compareTo(BigDecimal.ZERO) != 0 || !jtsl.equals(BigDecimal.ZERO)) {
                            BigDecimal jthjsj = yySjStats.get(0).getSj().add(bmsj.getWsfdj()).add(bmsj.getSzyfdj());
                            if (yySjStats.get(0).getSj().compareTo(BigDecimal.ZERO) <= 0) {
                                jthjsj = BigDecimal.ZERO;
                            }
                            result.add(new YyQfmxMonthlyStat(key, bmsj.getName(), yySjStats.get(0).getSj(), jthjsj, jtsl, jtsf, jtwsf, jtljf, jtszyf, jtznj, jthjysje, jtbs, ecjyfs, fjfs, qtfs));
                        }
                        //i++;
                    }
                }
            }

            //小计
            if (!result.isEmpty()) {
                BigDecimal sl = result.stream().map(YyQfmxMonthlyStat::getSl).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal sf = result.stream().map(YyQfmxMonthlyStat::getSf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal wsf = result.stream().map(YyQfmxMonthlyStat::getWsf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal ljf = result.stream().map(YyQfmxMonthlyStat::getLjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal szyf = result.stream().map(YyQfmxMonthlyStat::getSzyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal hj = result.stream().map(YyQfmxMonthlyStat::getHj).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal bs = result.stream().map(YyQfmxMonthlyStat::getBs).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal znj = result.stream().map(YyQfmxMonthlyStat::getZnj).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);

                BigDecimal ecjyf = result.stream().map(YyQfmxMonthlyStat::getEcjyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal fjf = result.stream().map(YyQfmxMonthlyStat::getFjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal qtf = result.stream().map(YyQfmxMonthlyStat::getQtf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);

                result.add(new YyQfmxMonthlyStat(key, "小计", BigDecimal.ZERO, BigDecimal.ZERO, sl, sf, wsf, ljf, szyf, znj, hj, bs, ecjyf, fjf, qtf));
            }

            results.addAll(result);
        });

        if (bc.compareTo(BigDecimal.ZERO) != 0) {
            results.add(new YyQfmxMonthlyStat(null, "水费补差", BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, bc, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO));
        }

        BigDecimal hjsl = results.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getSl).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal hjsf = results.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getSf).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal hjwsf = results.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getWsf).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal hjljf = results.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getLjf).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal hjszyf = results.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getSzyf).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal zhj = results.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getHj).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal zbs = results.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getBs).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal znj = results.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getZnj).reduce(BigDecimal.ZERO, BigDecimal::add);

        BigDecimal ecjyf = results.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getEcjyf).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal fjf = results.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getFjf).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal qtf = results.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getQtf).reduce(BigDecimal.ZERO, BigDecimal::add);

        if (zhj.compareTo(BigDecimal.ZERO) != 0) {
            results.add(new YyQfmxMonthlyStat(null, "合计", null, null, hjsl, hjsf, hjwsf, hjljf, hjszyf, znj, zhj, zbs, ecjyf, fjf, qtf));
        }

        return results;
    }

    /**
     * 欠费统计报表（汇总版）
     *
     * @param filter
     * @return
     */
    @Override
    public List<YyQfmxMonthlyStat> monthlyStatSummary1(YyQfmxStatFilter filter) {
        List<YySjStat> list0 = this.baseMapper.sjStat(filter, "", "");
        List<YySjStat> list1 = this.baseMapper.sjStat(filter, "1", "");
        List<YySjStat> list2 = this.baseMapper.sjStat(filter, "2", "");
        //List<YySjStat> list3 = this.baseMapper.sjStat(filter, "3", "");
        BigDecimal bc = this.baseMapper.bcStat(filter) == null ? BigDecimal.ZERO : this.baseMapper.bcStat(filter);
        //BigDecimal znj = this.baseMapper.qtStat(filter, "znj") == null ? BigDecimal.ZERO : this.baseMapper.qtStat(filter, "znj");//违约金
        List<YySjStat> list = new ArrayList<>();
        if ((long) list0.size() != 0) {
            //费用不等于并且水量也不等于零
            list.addAll(list0.stream().filter(i -> !i.getSf().add(i.getLjf()).add(i.getWsf()).add(i.getSzyf())
                    .add(i.getEcjyf()).add(i.getFjf()).add(i.getQtf()).equals(BigDecimal.ZERO) ||
                    !i.getSl().equals(BigDecimal.ZERO)).collect(Collectors.toList()));
        }
        if ((long) list1.size() != 0) {
            list.addAll(list1);
        }
        if ((long) list2.size() != 0) {
            list.addAll(list2);
        }
//        if ((long) list3.size() != 0) {
//            list.addAll(list3);
//        }

        List<BmSj> sjList = getSjMap();

        List<YyQfmxMonthlyStat> result = new ArrayList<>();

        Map<String, List<YySjStat>> sjmxMap = list.stream().filter(
                e -> StringUtils.isNotBlank(e.getSjbm())
                        && !e.getSfbz().equals("4")
        ).collect(Collectors.groupingBy(x -> x.getSjbm()));
        /*不收费费用明细查询*/
//        Map<String, List<YySjStat>> sjmxbsfMap = list.stream().filter(
//                e -> StringUtils.isNotBlank(e.getSjbm())
//                        && e.getSfbz().equals("4")
//
//        ).collect(Collectors.groupingBy(x -> x.getSjbm()));
//        if (!sjmxbsfMap.isEmpty()) {
//            for (List<YySjStat> yySjStats : sjmxbsfMap.values()) {
//                BmSj bmsj = sjList.stream().filter(e -> e.getCode().equals(yySjStats.get(0).getSjbm())).findFirst().get();
//                BigDecimal sl = yySjStats.stream().map(YySjStat::getSl).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                BigDecimal sf = yySjStats.stream().map(YySjStat::getSf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                BigDecimal wsf = yySjStats.stream().map(YySjStat::getWsf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                BigDecimal ljf = yySjStats.stream().map(YySjStat::getLjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                BigDecimal szyf = yySjStats.stream().map(YySjStat::getSzyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                BigDecimal bs = yySjStats.stream().map(YySjStat::getBs).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                BigDecimal znj = yySjStats.stream().map(YySjStat::getZnj).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//
//                BigDecimal fjf = yySjStats.stream().map(YySjStat::getFjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                ;
//                BigDecimal ecjyf = yySjStats.stream().map(YySjStat::getEcjyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                BigDecimal qtf = yySjStats.stream().map(YySjStat::getQtf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//
//                result.add(0, new YyQfmxMonthlyStat(null, bmsj.getName(), BigDecimal.ZERO, BigDecimal.ZERO, sl, sf, wsf, ljf, szyf, znj, fjf, ecjyf, qtf, sf.add(wsf).add(ljf).add(szyf).add(fjf).add(ecjyf).add(qtf), bs));
//            }
//        }

        for (BmSj bmsj : sjList) {
            List<YySjStat> sjmxs = sjmxMap.getOrDefault(bmsj.getCode(), new ArrayList<>());
            BigDecimal sl = sjmxs.stream().map(YySjStat::getSl).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal sf = sjmxs.stream().map(YySjStat::getSf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal wsf = sjmxs.stream().map(YySjStat::getWsf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal ljf = sjmxs.stream().map(YySjStat::getLjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal szyf = sjmxs.stream().map(YySjStat::getSzyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal bs = sjmxs.stream().map(YySjStat::getBs).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal znj = sjmxs.stream().map(YySjStat::getZnj).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);

            BigDecimal fjf = sjmxs.stream().map(YySjStat::getFjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal ecjyf = sjmxs.stream().map(YySjStat::getEcjyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal qtf = sjmxs.stream().map(YySjStat::getQtf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);

            if (bmsj.getJtbz().equals("0")) {
                BigDecimal hjysje = sf.add(wsf).add(ljf).add(szyf).add(fjf).add(ecjyf).add(qtf);
                if (hjysje.compareTo(BigDecimal.ZERO) != 0 || !sl.equals(BigDecimal.ZERO)) {
                    BigDecimal hjsj = bmsj.getSj().add(bmsj.getWsfdj()).add(bmsj.getSzyfdj());
                    result.add(new YyQfmxMonthlyStat(null, bmsj.getName(), bmsj.getSj(), hjsj, sl, sf, wsf, ljf, szyf, znj, hjysje, bs, ecjyf, fjf, qtf));
                }
            } else {
                //阶梯费用
                List<YySjStat> list4 = this.baseMapper.sjjtStat(filter, "1", "", bmsj.getCode());
                List<YySjStat> list5 = this.baseMapper.sjjtStat(filter, "2", "", bmsj.getCode());
                List<YySjStat> list6 = this.baseMapper.sjjtStat(filter, "3", "", bmsj.getCode());
                List<YySjStat> jtlist = new ArrayList<>();
                if ((long) list4.size() != 0) {
                    jtlist.addAll(list4);
                }
                if ((long) list5.size() != 0) {
                    jtlist.addAll(list5);
                }
                if ((long) list6.size() != 0) {
                    jtlist.addAll(list6);
                }
                //获取需要收费的阶梯费用明细
                Map<BigDecimal, List<YySjStat>> jtsjmxMap = jtlist.stream()
                        .filter(e -> StringUtils.isNotBlank(e.getSjbm())
                                && !e.getSfbz().equals("4"))
                        .collect(Collectors.groupingBy(x -> x.getSj()));
                //获取需要不收费的阶梯费用明细--不显示
//                List<YySjStat> jtbsfyySjStats = jtlist.stream().filter(
//                        e -> StringUtils.isNotBlank(e.getSjbm())
//                                && e.getSfbz().equals("4")
//                                && e.getSl().compareTo(BigDecimal.ZERO) > 0
//                ).collect(Collectors.toList());
//                if (!jtbsfyySjStats.isEmpty()) {
//                    BigDecimal bsfsl = jtbsfyySjStats.stream().map(YySjStat::getSl).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                    BigDecimal bsfsf = jtbsfyySjStats.stream().map(YySjStat::getSf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                    BigDecimal bsfwsf = jtbsfyySjStats.stream().map(YySjStat::getWsf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                    BigDecimal bsfljf = jtbsfyySjStats.stream().map(YySjStat::getLjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                    BigDecimal bsfszyf = jtbsfyySjStats.stream().map(YySjStat::getSzyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                    BigDecimal bsfbs = jtbsfyySjStats.stream().map(YySjStat::getBs).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                    BigDecimal bsfznj = jtbsfyySjStats.stream().map(YySjStat::getZnj).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                    BigDecimal bsfjf = jtbsfyySjStats.stream().map(YySjStat::getFjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                    BigDecimal bsecjyf = jtbsfyySjStats.stream().map(YySjStat::getEcjyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                    BigDecimal bsqtf = jtbsfyySjStats.stream().map(YySjStat::getQtf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
//                    result.add(0, new YyQfmxMonthlyStat(null, bmsj.getName(), BigDecimal.ZERO, BigDecimal.ZERO, bsfsl, bsfsf, bsfwsf, bsfljf, bsfszyf, bsfznj, bsfjf, bsecjyf, bsqtf, bsfsf.add(bsfwsf).add(bsfljf).add(bsfszyf).add(bsfjf).add(bsecjyf).add(bsqtf), bsfbs));
//                }

                for (List<YySjStat> yySjStats : jtsjmxMap.values()) {
                    BigDecimal jtsl = yySjStats.stream().map(YySjStat::getSl).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal jtsf = yySjStats.stream().map(YySjStat::getSf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal jtwsf = yySjStats.stream().map(YySjStat::getWsf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal jtljf = yySjStats.stream().map(YySjStat::getLjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal jtszyf = yySjStats.stream().map(YySjStat::getSzyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal jtbs = yySjStats.stream().map(YySjStat::getBs).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal jtznj = yySjStats.stream().map(YySjStat::getZnj).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal jtfjf = yySjStats.stream().map(YySjStat::getFjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal jtecjyf = yySjStats.stream().map(YySjStat::getEcjyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal jtqtf = yySjStats.stream().map(YySjStat::getQtf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);

                    BigDecimal jthjysje = jtsf.add(jtwsf).add(jtljf).add(jtszyf).add(jtfjf).add(jtecjyf).add(jtqtf);
                    if (jthjysje.compareTo(BigDecimal.ZERO) != 0) {
                        BigDecimal jthjsj = yySjStats.get(0).getSj().add(bmsj.getWsfdj()).add(bmsj.getSzyfdj());
                        if (yySjStats.get(0).getSj().compareTo(BigDecimal.ZERO) <= 0) {
                            jthjsj = BigDecimal.ZERO;
                        }
                        result.add(new YyQfmxMonthlyStat(null, bmsj.getName(), yySjStats.get(0).getSj(), jthjsj, jtsl, jtsf, jtwsf, jtljf, jtszyf, jtznj, jthjysje, jtbs, jtecjyf, jtfjf, jtqtf));
                    }
                    //i++;
                }
            }
        }
        //小计
        if (!result.isEmpty()) {
            BigDecimal sl = result.stream().map(YyQfmxMonthlyStat::getSl).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal sf = result.stream().map(YyQfmxMonthlyStat::getSf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal wsf = result.stream().map(YyQfmxMonthlyStat::getWsf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal ljf = result.stream().map(YyQfmxMonthlyStat::getLjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal szyf = result.stream().map(YyQfmxMonthlyStat::getSzyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal hj = result.stream().map(YyQfmxMonthlyStat::getHj).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal bs = result.stream().map(YyQfmxMonthlyStat::getBs).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal znj = result.stream().map(YyQfmxMonthlyStat::getZnj).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);

            BigDecimal fjf = result.stream().map(YyQfmxMonthlyStat::getFjf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal ecjyf = result.stream().map(YyQfmxMonthlyStat::getEcjyf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal qtf = result.stream().map(YyQfmxMonthlyStat::getQtf).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);

            result.add(new YyQfmxMonthlyStat(null, "小计", BigDecimal.ZERO, BigDecimal.ZERO, sl, sf, wsf, ljf, szyf, znj, hj, bs, ecjyf, fjf, qtf));
        }
//        if (znj.compareTo(BigDecimal.ZERO) != 0) {
//            results.add(new YyQfmxMonthlyStat("违约金", null, null, null, null, null, null, znj));
//        }
//            BigDecimal hj = result.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getHj).reduce(BigDecimal.ZERO, BigDecimal::add);
//            if (hj.compareTo(BigDecimal.ZERO) != 0) {
//                result.add(new YyQfmxMonthlyStat(key, "合计", BigDecimal.ZERO, BigDecimal.ZERO, null, null, null, null, null, hj));
//            }

        if (bc.compareTo(BigDecimal.ZERO) != 0) {
            result.add(new YyQfmxMonthlyStat(null, "水费补差", BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, bc, BigDecimal.ZERO));
        }
        BigDecimal hjsl = result.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getSl).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal hjsf = result.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getSf).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal hjwsf = result.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getWsf).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal hjljf = result.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getLjf).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal hjszyf = result.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getSzyf).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal zhj = result.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getHj).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal zbs = result.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getBs).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal znj = result.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getZnj).reduce(BigDecimal.ZERO, BigDecimal::add);

        BigDecimal fjf = result.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getFjf).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal ecjyf = result.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getEcjyf).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal qtf = result.stream().filter(Objects::nonNull).filter(e -> !e.getYsxm().equals("小计")).map(YyQfmxMonthlyStat::getQtf).reduce(BigDecimal.ZERO, BigDecimal::add);

        if (zhj.compareTo(BigDecimal.ZERO) != 0) {
            result.add(new YyQfmxMonthlyStat(null, "合计", null, null, hjsl, hjsf, hjwsf, hjljf, hjszyf, znj, zhj, zbs, ecjyf, fjf, qtf));
        }
        return result;
    }

    /**
     * 计算给定日期字符串的上一个月，并返回相同格式的字符串
     *
     * @param dateStr 格式为 yyyyMM 的日期字符串（如 "202501"）
     * @return 上一个月的日期字符串（如 "202412"）
     * @throws IllegalArgumentException 如果输入格式无效
     */
    public String getPreviousMonth(String dateStr, String type) {
        // 校验输入非空且为6位数字
        Objects.requireNonNull(dateStr, "输入日期不能为null");
        if (!dateStr.matches("\\d{6}")) {
            throw new IllegalArgumentException("输入格式错误，应为 yyyyMM");
        }

        // 解析日期并计算上个月
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
        YearMonth yearMonth = YearMonth.parse(dateStr, formatter);
        if (type.equals("add")) {
            return yearMonth.plusMonths(1).format(formatter);
        } else {
            return yearMonth.minusMonths(1).format(formatter);
        }
    }


    /**
     * 查询短信欠费合计
     */

    public PageResult<YyqfmxSumSelect> getQfmxSumSelect(PageDto pageDto, YyQfmxFilter filter) {
        PageDto<YyqfmxSumSelect> getSumSelect = baseMapper.getSumQfmx(pageDto, filter);
        return getSumSelect.toVo();
    }

    @Override
    public void yytkfch(YySspjxx chpjData, PjchDto pjchDto, String cwrq) {
        // 原欠费明细冲红
        baseMapper.yytkfch(chpjData, pjchDto, cwrq);
        String qfid = chpjData.getQfid();
        baseMapper.updateQfmxChbz(qfid, pjchDto);

        // 新增原欠费明细
        baseMapper.xzqfmx(qfid, pjchDto, cwrq);
        yyWyjtzService.gxwyjtzjl(qfid);
    }

    @Override
    public void ycdkch(YySspjxx yySspjxx, PjchDto pjchDto, String cwrq) {
        baseMapper.ycdkch(yySspjxx, pjchDto, cwrq);
        String qfid = yySspjxx.getQfid();
        baseMapper.updateQfmxChbz(qfid, pjchDto);

        // 新增原欠费明细
        baseMapper.xzqfmx(qfid, pjchDto, cwrq);
        yyWyjtzService.gxwyjtzjl(qfid);
    }


    @Override
    public void hbsf(YyCblr cblr, YhCbkxx cbkxx) throws Exception {
        sjCache();//缓存表价信息（计算前必须）
        zbFbsCache();//缓存总表的分表数与母表的子表数
        List<BmCbb> bmCbbs = cbbService.list();
        YhKhjbxx yhxx = khjbxxService.getById(cbkxx.getYhbh());
        if (yhxx == null) return;
        BigDecimal sjsl = cblr.getSl();
        if (sjsl.compareTo(BigDecimal.ZERO) < 0) {
            cblrService.updateJsbz(cblr.getCbkid());
            return;
        }
        YyQfmx yyQfmx = new YyQfmx();
        yyQfmx.setQflsbh(GuidGenerator.getQflsbh());
        BigDecimal cbkxxXfsf = cbkxx.getXfsf();

        if (sjsl.compareTo(BigDecimal.ZERO) == 0 && cbkxxXfsf.compareTo(BigDecimal.ZERO) == 0) {
            BeanUtils.copyProperties(yhxx, yyQfmx);
            BeanUtils.copyProperties(cblr, yyQfmx);
            yyQfmx.setJsrq(new Date());
            yyQfmx.setJtzqljlJsq(yhxx.getJtzqljl());
            yyQfmx.setSfbz("4");
            if (StringUtil.isNotEmpty(cbkxx.getSjbm())) {
                yyQfmx.setSjbm(cbkxx.getSjbm());
            }
            if (StringUtil.isNotEmpty(cbkxx.getSjbm1())) {
                yyQfmx.setSjbm1(cbkxx.getSjbm1());
            }
        } else {
            SfJsJg sfJsJg = sfJs(cbkxx, yhxx, sjsl);
            BeanUtils.copyProperties(yhxx, yyQfmx);
            BeanUtils.copyProperties(cblr, yyQfmx, "sl");
            BeanUtils.copyProperties(sfJsJg, yyQfmx);
        }
        //判断是否是当月首次抄表算费
        if (cblr.getCbcs().compareTo(BigDecimal.ONE) == 0) {
            // 附加费
            if (cbkxx.getFjf() != null && cbkxx.getFjf().compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal fjf = cbkxx.getFjf();
                yyQfmx.setYsfjf(fjf);
                yyQfmx.setFjf(fjf);
                yyQfmx.setFjfdj(fjf);
            }
            // 消防栓费
            if (cbkxxXfsf != null && cbkxxXfsf.compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal xfsf = cbkxx.getXfsf();
                yyQfmx.setYsqt(xfsf);
            }
            yyQfmx.setYsje(yyQfmx.getYsje().add(yyQfmx.getYsfjf()).add(yyQfmx.getYsqt()));
        }
        yyQfmx.setSfbc("0");
        yyQfmx.setFylx(BcFylxEnum.Zhfy.getValue().toString());
        yyQfmx.setFylxmc(BcFylxEnum.Zhfy.getName());
        //yyQfmx.setYsyf(new SimpleDateFormat("yyyyMM").format(cblr.getCbrq()));
        yyQfmx.setYsyf(ymjzConfigService.getCwrq(cblr.getCbrq()));
        yyQfmx.setChbz(PjztEnum.正常.getValue());
        BmCbb bmCbb = bmCbbs.stream().filter(e -> e.getCbbbm().equals(cblr.getSscbb())).findFirst().orElse(null);
        if (StringUtil.isNotNull(bmCbb)) {
            yyQfmx.setQyfzrbm(bmCbb.getQyfzr());
            yyQfmx.setQyfzrxm(bmCbb.getQyfzrxm());
        }
        if (!this.save(yyQfmx)) {
            throw new FeesException("", FeesErrorCode.BUSINESS_ERROR);
        }
        cblrService.updateJsbz(cblr.getCbkid());
    }

    @Override
    public long getQfyhs() {
        return baseMapper.getQfyhs();
    }

    @Override
    public List<Map> getYsbbmxList(YysSsbbFilter filter) {
        return baseMapper.getYsbbmxList(filter);
    }
}
