package com.openhis.web.paymentmanage.appservice.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.core.common.enums.DeleteFlag;
import com.core.common.exception.ServiceException;
import com.core.common.utils.DateUtils;
import com.core.common.utils.SecurityUtils;
import com.core.common.utils.StringUtils;
import com.openhis.administration.domain.*;
import com.openhis.administration.dto.ChargeItemBaseInfoDto;
import com.openhis.administration.dto.ChargeItemDefInfo;
import com.openhis.administration.dto.EncounterAccountDto;
import com.openhis.administration.service.*;
import com.openhis.clinical.domain.Condition;
import com.openhis.clinical.domain.ConditionDefinition;
import com.openhis.clinical.service.IConditionDefinitionService;
import com.openhis.clinical.service.IConditionService;
import com.openhis.common.constant.CommonConstants;
import com.openhis.common.constant.YbCommonConstants;
import com.openhis.common.enums.*;
import com.openhis.common.enums.ybenums.YbMedChrgItmType;
import com.openhis.common.enums.ybenums.YbPayment;
import com.openhis.financial.domain.Contract;
import com.openhis.financial.domain.PaymentRecDetail;
import com.openhis.financial.domain.PaymentReconciliation;
import com.openhis.financial.model.PaymentRecDetailAccountResult;
import com.openhis.financial.model.PaymentReconciliationAccountDel;
import com.openhis.financial.service.IContractService;
import com.openhis.financial.service.IPaymentRecDetailService;
import com.openhis.financial.service.IPaymentReconciliationService;
import com.openhis.medication.domain.MedicationDefinition;
import com.openhis.medication.service.IMedicationDefinitionService;
import com.openhis.web.paymentmanage.appservice.IChargeBillService;
import com.openhis.web.paymentmanage.dto.*;
import com.openhis.web.paymentmanage.mapper.ChargeBillMapper;
import com.openhis.workflow.domain.ActivityDefinition;
import com.openhis.workflow.service.IActivityDefinitionService;
import com.openhis.yb.domain.ClinicSettle;
import com.openhis.yb.domain.ClinicUnSettle;
import com.openhis.yb.domain.InfoPerson;
import com.openhis.yb.service.*;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class IChargeBillServiceImpl implements IChargeBillService {

    @Resource
    private IAccountService iAccountService;
    @Resource
    private IEncounterService iEncounterService;
    @Resource
    private IContractService iContractService;
    @Resource
    private IInvoiceService iInvoiceService;
    @Resource
    private IPaymentReconciliationService paymentReconciliationService;
    @Resource
    private IPaymentRecDetailService paymentRecDetailService;
    @Resource
    private IContractService contractService;
    @Resource
    private IChargeItemService chargeItemService;
    @Resource
    private IPatientService iPatientService;
    @Autowired
    private IChargeItemDefinitionService iChargeItemDefinitionService;
    @Autowired
    private IPerinfoService iPerinfoService;
    @Autowired
    private IEncounterDiagnosisService iEncounterDiagnosisService;
    @Autowired
    private IOrganizationService iOrganizationService;
    @Autowired
    private IConditionDefinitionService iConditionDefinitionService;
    @Autowired
    private IConditionService iConditionService;
    @Autowired
    private ChargeBillMapper chargeBillMapper;
    @Autowired
    private IMedicationDefinitionService iMedicationDefinitionService;
    @Autowired
    private IDeviceDefinitionService iDeviceDefinitionService;
    @Autowired
    private IActivityDefinitionService iActivityDefinitionService;
    @Autowired
    private IPractitionerService iPractitionerService;
    @Autowired
    private IHealthcareServiceService iHealthcareServiceService;
    @Autowired
    private IClinicSettleService iClinicSettleService;
    @Autowired
    private IClinicUnRegService iClinicUnRegService;
    @Autowired
    private IRegService iRegService;
    @Autowired
    private IClinicUnSettleService iClinicUnSettleService;

    @Override
    public Map getDetail(Long paymentId) {

        Map<String, Object> map = new HashMap<>();
        // 查询
        PaymentReconciliation paymentReconciliation = paymentReconciliationService.getById(paymentId);
        if (paymentReconciliation == null) {
            throw new ServiceException("未查询到付款信息");
        }
        map.put("paymentId", paymentReconciliation.getPaymentNo());// 结算id
        map.put("paymentAmount", paymentReconciliation.getTenderedAmount());// 应收金额
        Practitioner practitioner = iPractitionerService.getById(paymentReconciliation.getEntererId());
        map.put("paymentEmployee", practitioner == null ? "" : practitioner.getName());// 收费员
        map.put("chargeTime", paymentReconciliation.getBillDate());// 收费时间
        Patient patient = iPatientService.getById(paymentReconciliation.getPatientId());
        if (patient == null) {
            throw new ServiceException("未查询到患者信息");
        }
        map.put("patientName", patient.getName());// 患者姓名

        map.put("sex", patient.getGenderEnum());// 性别
        map.put("idCardNo", patient.getIdCard());// 身份证号
        map.put("birthDay", patient.getBirthDate());// 出生日期

        List<PaymentRecDetail> paymentRecDetails = paymentRecDetailService
            .list(new LambdaQueryWrapper<PaymentRecDetail>().eq(PaymentRecDetail::getReconciliationId, paymentId));

        if (paymentRecDetails.isEmpty()) {
            throw new ServiceException("未查询到付款信息");
        }
        map.put("detail", paymentRecDetails);// 支付详细

        for (PaymentRecDetail paymentRecDetail : paymentRecDetails) {
            if (Objects.equals(paymentRecDetail.getPayEnum(), YbPayment.SELF_YB_ZH_PAY.getValue())) {
                map.put("ybAccountPay", paymentRecDetail.getAmount());// 医保账户支付
            }
            if (Objects.equals(paymentRecDetail.getPayEnum(), YbPayment.BALC.getValue())) {
                map.put("ybAccountBalc", paymentRecDetail.getAmount());// 医保账户余额（现）
            }
            if (Objects.equals(paymentRecDetail.getPayEnum(), YbPayment.YB_FUND_PAY.getValue())) {
                map.put("ybFundPay", paymentRecDetail.getAmount());// 基金支付总额
            }
            if (Objects.equals(paymentRecDetail.getPayEnum(), YbPayment.YB_TC_FUND_AMOUNT.getValue())) {
                map.put("ybTcPay", paymentRecDetail.getAmount());// 统筹支付金额
            }
            if (Objects.equals(paymentRecDetail.getPayEnum(), YbPayment.YB_BC_GWY_BZ_VALUE.getValue())) {
                map.put("ybGWYPay", paymentRecDetail.getAmount());// 公务员补助
            }
            if (Objects.equals(paymentRecDetail.getPayEnum(), YbPayment.OTHER_PAY.getValue())) {
                map.put("ybOtherPay", paymentRecDetail.getAmount());// 其他支付
            }
            // 下面两个大额理赔有哪个用哪个，无所谓的
            if (Objects.equals(paymentRecDetail.getPayEnum(), YbPayment.YB_BC_DE_BZ_VALUE.getValue())) {
                map.put("ybDELPPay", paymentRecDetail.getAmount());// 大额理赔（常规）
            }
            if (Objects.equals(paymentRecDetail.getPayEnum(), YbPayment.YB_BC_ZG_DE_BZ_VALUE.getValue())) {
                map.put("ybDELPPay", paymentRecDetail.getAmount());// 大额理赔(企业)
            }
            if (Objects.equals(paymentRecDetail.getPayEnum(), YbPayment.E_WALLET.getValue())) {
                map.put("ybWallet", paymentRecDetail.getAmount());// 电子钱包
            }
            if (Objects.equals(paymentRecDetail.getPayEnum(), YbPayment.SUPPLEMENTARY_INSURANCE.getValue())) {
                map.put("ybWallet", paymentRecDetail.getAmount());// 居民大病报销
            }
            if (Objects.equals(paymentRecDetail.getPayEnum(), YbPayment.SELF_CASH_VALUE.getValue())) {
                map.put("cash", paymentRecDetail.getAmount());// 现金
            }
            if (Objects.equals(paymentRecDetail.getPayEnum(), YbPayment.SELF_CASH_VX_VALUE.getValue())) {
                map.put("wxCash", paymentRecDetail.getAmount());// 现金（微信）
            }
            if (Objects.equals(paymentRecDetail.getPayEnum(), YbPayment.SELF_CASH_ALI_VALUE.getValue())) {
                map.put("aliCash", paymentRecDetail.getAmount());// 现金（支付宝）
            }
            if (Objects.equals(paymentRecDetail.getPayEnum(), YbPayment.INSCP_SCP_AMT.getValue())) {
                map.put("FHZCAmount", paymentRecDetail.getAmount());// 符合政策金额
            }
        }

        Invoice invoice = iInvoiceService.getOne(new LambdaQueryWrapper<Invoice>()
            .eq(Invoice::getReconciliationId, paymentId).eq(Invoice::getStatusEnum, InvoiceStatus.ISSUED.getValue())
            .orderByDesc(Invoice::getCreateTime).last(YbCommonConstants.sqlConst.LIMIT1));
        if (invoice != null) {
            map.put("invoiceNo", invoice.getBillNo());// 支付详细
            map.put("pictureUrl", invoice.getPictureUrl());// 图片
        }

        List<Long> chargeItemIdList = Arrays.stream(paymentReconciliation.getChargeItemIds().split(","))
            .map(Long::parseLong).collect(Collectors.toList());

        List<ChargeItem> chargeItemList = chargeItemService.list(new LambdaQueryWrapper<ChargeItem>()
            .in(ChargeItem::getId, chargeItemIdList).eq(ChargeItem::getDeleteFlag, DelFlag.NO.getCode()));
        List<ChargeItemDetailVO> chargeItemDetailList = new ArrayList<>();
        ChargeItemDetailVO chargeItemDetailVO;
        for (ChargeItem chargeItem : chargeItemList) {
            chargeItemDetailVO = new ChargeItemDetailVO();
            BeanUtils.copyProperties(chargeItem, chargeItemDetailVO);
            if (CommonConstants.TableName.MED_MEDICATION_DEFINITION.equals(chargeItem.getProductTable())) {
                MedicationDefinition medication = iMedicationDefinitionService.getById(chargeItem.getProductId());
                chargeItemDetailVO.setDirClass(medication.getYbNo()).setChargeItemName(medication.getName())
                    .setTotalPrice(chargeItem.getTotalPrice()).setQuantityUnit(chargeItem.getQuantityUnit())
                    .setQuantityValue(chargeItem.getQuantityValue());
            } else if (CommonConstants.TableName.ADM_DEVICE_DEFINITION.equals(chargeItem.getProductTable())) {
                DeviceDefinition device = iDeviceDefinitionService.getById(chargeItem.getProductId());
                chargeItemDetailVO.setDirClass(device.getYbNo()).setChargeItemName(device.getName())
                    .setTotalPrice(chargeItem.getTotalPrice()).setQuantityUnit(chargeItem.getQuantityUnit())
                    .setQuantityValue(chargeItem.getQuantityValue());
            } else if (CommonConstants.TableName.WOR_ACTIVITY_DEFINITION.equals(chargeItem.getProductTable())) {
                ActivityDefinition activity = iActivityDefinitionService.getById(chargeItem.getProductId());
                chargeItemDetailVO.setDirClass(activity.getYbNo()).setChargeItemName(activity.getName())
                    .setTotalPrice(chargeItem.getTotalPrice()).setQuantityUnit(chargeItem.getQuantityUnit())
                    .setQuantityValue(chargeItem.getQuantityValue());
            } else {
                HealthcareService healthcareService = iHealthcareServiceService.getById(chargeItem.getServiceId());
                chargeItemDetailVO.setDirClass(healthcareService.getYbNo())
                    .setChargeItemName(healthcareService.getName()).setTotalPrice(chargeItem.getTotalPrice())
                    .setQuantityUnit(chargeItem.getQuantityUnit()).setQuantityValue(chargeItem.getQuantityValue());
            }
            chargeItemDetailList.add(chargeItemDetailVO);
        }
        map.put("chargeItem", chargeItemDetailList);// 收费项

        if (chargeItemList.isEmpty()) {
            throw new ServiceException("未查询到收费项");
        }
        Encounter encounter = iEncounterService.getById(paymentReconciliation.getEncounterId());
        if (encounter == null) {
            throw new ServiceException("未查询到就诊信息");
        }
        map.put("classEnum", encounter.getYbClassEnum());// 门诊/住院
        map.put("regNo", encounter.getBusNo());// 门诊号

        Account account = iAccountService.getOne(new LambdaQueryWrapper<Account>()
            .eq(Account::getEncounterId, encounter.getId()).eq(Account::getEncounterFlag, Whether.YES.getValue()));
        if (account == null) {
            throw new ServiceException("未查询到就诊信息");
        }

        InfoPerson perinfo = iPerinfoService.getOne(new LambdaQueryWrapper<InfoPerson>()
            .eq(InfoPerson::getCertno, patient.getIdCard()).eq(InfoPerson::getTenantId, patient.getTenantId())
            .orderByDesc(InfoPerson::getCreateTime).last(YbCommonConstants.sqlConst.LIMIT1));
        if (perinfo != null) {
            map.put("personType", perinfo.getInsutype());// 人员类别：职工医保，居民医保等；如果为空显示自费或其他
            map.put("insuplcAdmdvs", perinfo.getInsuplcAdmdvs());// 患者参保地区划
        }

        Contract contract =
            contractService.getOne(new LambdaQueryWrapper<Contract>().eq(Contract::getBusNo, account.getContractNo()));
        if (contract == null) {
            throw new ServiceException("未查询到合同信息");
        }
        // 查询主诊断信息
        EncounterDiagnosis encounterDiagnosis = iEncounterDiagnosisService.getOne(
            new LambdaQueryWrapper<EncounterDiagnosis>().eq(EncounterDiagnosis::getEncounterId, encounter.getId())
                .eq(EncounterDiagnosis::getMaindiseFlag, Whether.YES.getValue())
                .eq(EncounterDiagnosis::getDeleteFlag, DelFlag.NO.getCode())
                .orderByDesc(EncounterDiagnosis::getDiagSrtNo).last(YbCommonConstants.sqlConst.LIMIT1));

        if (encounterDiagnosis != null) {
            Condition condition = iConditionService.getById(encounterDiagnosis.getConditionId());
            if (condition != null) {
                ConditionDefinition conditionDefinition =
                    iConditionDefinitionService.getOne(new LambdaQueryWrapper<ConditionDefinition>()
                        .eq(ConditionDefinition::getId, condition.getDefinitionId()));
                if (conditionDefinition != null) {
                    map.put("conditionDefinition", conditionDefinition.getName());// 诊断名
                }
            }
        }

        BigDecimal sum01 = BigDecimal.ZERO;
        BigDecimal sum02 = BigDecimal.ZERO;
        BigDecimal sum03 = BigDecimal.ZERO;
        BigDecimal sum04 = BigDecimal.ZERO;
        BigDecimal sum05 = BigDecimal.ZERO;
        BigDecimal sum06 = BigDecimal.ZERO;
        BigDecimal sum07 = BigDecimal.ZERO;
        BigDecimal sum08 = BigDecimal.ZERO;
        BigDecimal sum09 = BigDecimal.ZERO;
        BigDecimal sum10 = BigDecimal.ZERO;
        BigDecimal sum11 = BigDecimal.ZERO;
        BigDecimal sum12 = BigDecimal.ZERO;
        BigDecimal sum13 = BigDecimal.ZERO;
        BigDecimal sum14 = BigDecimal.ZERO;

        for (ChargeItem chargeItem : chargeItemList) {

            Long definitionId = chargeItem.getDefinitionId();

            ChargeItemDefinition chargeItemDefinition = iChargeItemDefinitionService.getById(definitionId);


            YbMedChrgItmType medChrgItmType =
                YbMedChrgItmType.getByCode(Integer.parseInt(chargeItemDefinition.getYbType()));

            switch (medChrgItmType) {
                case BED_FEE:
                    sum01 = sum01.add(chargeItem.getTotalPrice());
                    break;
                case DIAGNOSTIC_FEE:
                    sum02 = sum02.add(chargeItem.getTotalPrice());
                    break;
                case CHECK_FEE:
                    sum03 = sum03.add(chargeItem.getTotalPrice());
                    break;
                case DIAGNOSTIC_TEST_FEE:
                    sum04 = sum04.add(chargeItem.getTotalPrice());
                    break;
                case MEDICAL_EXPENSE_FEE:
                    sum05 = sum05.add(chargeItem.getTotalPrice());
                    break;
                case OPERATION_FEE:
                    sum06 = sum06.add(chargeItem.getTotalPrice());
                    break;
                case NURSING_FEE:
                    sum07 = sum07.add(chargeItem.getTotalPrice());
                    break;
                case SANITARY_MATERIALS_FEE:
                    sum08 = sum08.add(chargeItem.getTotalPrice());
                    break;
                case WEST_MEDICINE:
                    sum09 = sum09.add(chargeItem.getTotalPrice());
                    break;
                case CHINESE_MEDICINE_SLICES_FEE:
                    sum10 = sum10.add(chargeItem.getTotalPrice());
                    break;
                case CHINESE_MEDICINE_FEE:
                    sum11 = sum11.add(chargeItem.getTotalPrice());
                    break;
                case GENERAL_CONSULTATION_FEE:
                    sum12 = sum12.add(chargeItem.getTotalPrice());
                    break;
                case REGISTRATION_FEE:
                    sum13 = sum13.add(chargeItem.getTotalPrice());
                    break;
                default:
                    sum14 = sum14.add(chargeItem.getTotalPrice());
                    break;
            }
        }
        map.put("BED_FEE", sum01);// 床位费
        map.put("DIAGNOSTIC_FEE", sum02);// 诊察费
        map.put("CHECK_FEE", sum03);// 检查费
        map.put("DIAGNOSTIC_TEST_FEE", sum04);// 化验费
        map.put("MEDICAL_EXPENSE_FEE", sum05);// 治疗费
        map.put("OPERATION_FEE", sum06);// 手术费
        map.put("NURSING_FEE", sum07);// 护理费
        map.put("SANITARY_MATERIALS_FEE", sum08);// 卫生材料费
        map.put("WEST_MEDICINE", sum09);// 西药费
        map.put("CHINESE_MEDICINE_SLICES_FEE", sum10);// 中药饮片费
        map.put("CHINESE_MEDICINE_FEE", sum11);// 中成药费
        map.put("GENERAL_CONSULTATION_FEE", sum12);// 一般诊疗费
        map.put("REGISTRATION_FEE", sum13);// 挂号费
        map.put("OTHER_FEE", sum14);// 其他费用

        // String ybSwitch = SecurityUtils.getLoginUser().getOptionJson().getString(CommonConstants.Option.YB_SWITCH);
        JSONObject optionJson = SecurityUtils.getLoginUser().getOptionJson();
        String fixmedinsName = optionJson.getString(CommonConstants.Option.FIXMEDINS_NAME);
        String fixmedinsCode = optionJson.getString(CommonConstants.Option.FIXMEDINS_CODE);

        map.put("fixmedinsName", fixmedinsName);// 医院名称
        map.put("fixmedinsCode", fixmedinsCode);// 医院编号

        return map;
    }

    /**
     * 农大版本
     * 
     * @param
     * @return
     */
    @Override
    public Map getTotal(String startTime, String endTime, Long entererId, String contractNo) {
        // String contractNo="220100";
        Map<String, Object> map = new HashMap<>();

        // SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
        Date startDate = DateUtils.parseDate(startTime);
        Date endDate = DateUtils.parseDate(endTime);

        // 查询所有的支付
        LambdaQueryWrapper<PaymentReconciliation> queryWrapper = new LambdaQueryWrapper<PaymentReconciliation>()
            .between(PaymentReconciliation::getBillDate, startDate, endDate)
            .eq(PaymentReconciliation::getDeleteFlag, DelFlag.NO.getCode())
            .in(PaymentReconciliation::getStatusEnum, PaymentStatus.SUCCESS.getValue(),
                PaymentStatus.REFUND_ALL.getValue())
            .eq(PaymentReconciliation::getKindEnum, PaymentKind.OUTPATIENT_CLINIC.getValue());
        if (entererId != null) {
            queryWrapper.eq(PaymentReconciliation::getEntererId, entererId);
        }
        List<PaymentReconciliation> paymentReconciliationList = paymentReconciliationService.list(queryWrapper);
        if (paymentReconciliationList.isEmpty()) {
            return getMap(map);
        }
        // 调试使用
        // for (PaymentReconciliation paymentReconciliation : paymentReconciliationList) {
        // String[] split = paymentReconciliation.getChargeItemIds().split(",");
        // List<String> strings = Arrays.asList(split);
        // for (String string : strings) {
        // ChargeItem byId = chargeItemService.getById(Long.parseLong(string));
        // if ("adm_healthcare_service".equals(byId.getServiceTable())) {
        // System.out.println("//****************************");
        // System.out.println(JSON.toJSONString(byId));
        // }
        // }
        // }

        // 查询所有的支付详情
        List<Long> paymentIdList =
            paymentReconciliationList.stream().map(PaymentReconciliation::getId).collect(Collectors.toList());
        List<PaymentRecDetail> paymentDetails = paymentRecDetailService
            .list(new LambdaQueryWrapper<PaymentRecDetail>().in(PaymentRecDetail::getReconciliationId, paymentIdList)
                .eq(PaymentRecDetail::getDeleteFlag, DelFlag.NO.getCode()).notIn(PaymentRecDetail::getPayEnum,
                    YbPayment.SUPPLEMENTARY_INSURANCE.getValue(), YbPayment.SUPPLEMENTARY_INSURANCE.getValue(),
                    YbPayment.FULAMT_OWNPAY_AMT.getValue(), YbPayment.OVERLMT_SELFPAY.getValue(),
                    YbPayment.PRESELFPAY_AMT.getValue(), YbPayment.INSCP_SCP_AMT.getValue(),
                    YbPayment.ACT_PAY_DEDC.getValue(), YbPayment.POOL_PROP_SELFPAY.getValue(),
                    YbPayment.BALC.getValue(), YbPayment.BIRTH_FUND.getValue(), YbPayment.RETIREE_MEDICAL.getValue(),
                    YbPayment.MEDICAL_ASSISTANCE.getValue(), YbPayment.URBAN_SERIOUS_ILLNESS.getValue(),
                    YbPayment.URBAN_BASIC_MEDICAL.getValue(), YbPayment.GOVERNMENT_SUBSIDY.getValue(),
                    YbPayment.ACCIDENT_INSURANCE.getValue(), YbPayment.CARE_INSURANCE.getValue(),
                    YbPayment.FINANCIAL_FUND.getValue(), YbPayment.HOSPITAL_ADVANCE.getValue(),
                    YbPayment.SUPPLEMENTARY_INSURANCE.getValue(),
                    YbPayment.BASIC_MEDICAL_INSURANCE_FOR_URBAN_EMPLOYEES.getValue(), YbPayment.E_WALLET.getValue(),
                    YbPayment.HEALTHCARE_PREPAYMENT.getValue()));
        if (paymentDetails.isEmpty()) {
            return getMap(map);
        }
        Map<Long, List<PaymentRecDetail>> paymentDetailsKV =
            paymentDetails.stream().collect(Collectors.groupingBy(PaymentRecDetail::getReconciliationId));
        // 声明变量，符合要求的付款记录
        Collection<PaymentReconciliation> PaymentReconciliationList;
        List<Account> accountList = new ArrayList<>();
        if (!StringUtils.isEmpty(contractNo)) {
            // 查询账户信息用来区分省市医保
            List<Long> accountIds =
                paymentDetails.stream().map(PaymentRecDetail::getAccountId).collect(Collectors.toList());
            if (accountIds.isEmpty()) {
                throw new ServiceException("查询账户信息为空");
            }
            accountList = iAccountService.list(new LambdaQueryWrapper<Account>().in(Account::getId, accountIds));

            // 留下符合条件的付款记录
            Map<Long, PaymentReconciliation> paymentMap = new HashMap<>();
            for (PaymentRecDetail paymentDetail : paymentDetails) {

                Optional<Account> first =
                    accountList.stream().filter(x -> x.getId().equals(paymentDetail.getAccountId())).findFirst();
                // 账户不符合要求的筛出掉
                if (first.isEmpty() || !first.get().getContractNo().equals(contractNo)) {
                    continue;
                }
                // 付款记录里匹配不上筛出掉
                Optional<PaymentReconciliation> first1 = paymentReconciliationList.stream()
                    .filter(x -> x.getId().equals(paymentDetail.getReconciliationId())).findFirst();
                if (first1.isEmpty()) {
                    continue;
                }

                paymentMap.put(paymentDetail.getReconciliationId(), first1.get());
            }
            // 符合省市医保或自费要求的付款实体集合
            PaymentReconciliationList = paymentMap.values();
        } else {
            // 时间段内的全部付款记录
            PaymentReconciliationList = paymentReconciliationList;
        }
        if (PaymentReconciliationList.isEmpty()) {
            return getMap(map);
        }
        // 查询所有的收费项
        List<String> chargeItemIdStrs = PaymentReconciliationList.stream().map(PaymentReconciliation::getChargeItemIds)
            .collect(Collectors.toList());
        List<Long> chargeItemIds = new ArrayList<>();
        for (String chargeItemIdStr : chargeItemIdStrs) {
            List<String> strings = Arrays.asList(chargeItemIdStr.split(","));
            for (String string : strings) {
                Long id = Long.parseLong(string);
                chargeItemIds.add(id);
            }
        }

        // for (Long chargeItemId : chargeItemIds) {
        // System.out.println(chargeItemId);
        // System.out.println(",");
        // }

        List<ChargeItem> chargeItemList = chargeItemService.list(new LambdaQueryWrapper<ChargeItem>()
            .in(ChargeItem::getId, chargeItemIds).eq(ChargeItem::getDeleteFlag, DelFlag.NO.getCode()));
        if (paymentDetails.isEmpty()) {
            throw new ServiceException("数据异常，该时间段内未查询到收费项");
        }

        // for (ChargeItem chargeItem : chargeItemList) {
        // if("adm_healthcare_service".equals(chargeItem.getServiceTable())){
        // System.out.println("//****************************");
        // System.out.println(JSON.toJSONString(chargeItem));
        // }
        // }

        // 查询收费定义列表
        List<Long> chargeItemDefinitionIdList =
            chargeItemList.stream().map(ChargeItem::getDefinitionId).collect(Collectors.toList());
        if (chargeItemDefinitionIdList.isEmpty()) {
            throw new ServiceException("未查询到收费记录，无收费项信息");
        }
        List<ChargeItemDefinition> chargeItemDefinitions =
            iChargeItemDefinitionService.listByIds(chargeItemDefinitionIdList);
        if (chargeItemDefinitions.isEmpty()) {
            throw new ServiceException("未查询到收费记录，无收费项信息");
        }
        Map<Long, List<ChargeItemDefinition>> chargeItemDefKV =
            chargeItemDefinitions.stream().collect(Collectors.groupingBy(ChargeItemDefinition::getId));

        // 查询医保结算id
        List<String> settleIds = new ArrayList<>();
        for (PaymentReconciliation paymentReconciliation : paymentReconciliationList) {
            if (!StringUtils.isEmpty(paymentReconciliation.getYbSettleIds())) {
                List<String> strings = Arrays.asList(paymentReconciliation.getYbSettleIds().split(","));
                settleIds.addAll(strings);
            }
        }
        List<ClinicSettle> clinicSettle = new ArrayList<>();
        if (!settleIds.isEmpty()) {
            clinicSettle = iClinicSettleService.getBySettleIds(settleIds);
            // List<String> collect = clinicSettle.stream().map(ClinicSettle::getInsutype).collect(Collectors.toList());
        }

        BigDecimal cashSum = BigDecimal.ZERO;// 现金总数 = rmbCashSum + vxCashSum + aliCashSum + uniCashSum
        BigDecimal rmbCashSum = BigDecimal.ZERO;// 现金总数
        BigDecimal vxCashSum = BigDecimal.ZERO;// 现金总数（）
        BigDecimal aliCashSum = BigDecimal.ZERO;// 现金总数（）
        BigDecimal uniCashSum = BigDecimal.ZERO;// 现金总数（）
        BigDecimal vxSum = BigDecimal.ZERO;// 微信总数
        BigDecimal aliSum = BigDecimal.ZERO;// 支付宝总数
        BigDecimal uniSum = BigDecimal.ZERO;// 银行卡总数
        BigDecimal tcSum = BigDecimal.ZERO;// 基本统筹
        BigDecimal zhSum = BigDecimal.ZERO;// 医保账户
        BigDecimal fundSum = BigDecimal.ZERO;// 基金支总额
        // 农大版本只查询收款员，日期，现金多少钱，挂号费多少钱
        for (PaymentRecDetail paymentDetail : paymentDetails) {

            if (!StringUtils.isEmpty(contractNo)) {
                Optional<Account> first =
                    accountList.stream().filter(x -> x.getId().equals(paymentDetail.getAccountId())).findFirst();
                if (first.isEmpty() || !first.get().getContractNo().equals(contractNo)) {
                    continue;
                }
            }

            if (YbPayment.SELF_CASH_PAY.getValue().equals(paymentDetail.getPayEnum())) {
                cashSum = cashSum.add(paymentDetail.getAmount());
            }
            if (YbPayment.SELF_CASH_VALUE.getValue().equals(paymentDetail.getPayEnum())) {
                rmbCashSum = rmbCashSum.add(paymentDetail.getAmount());
            }
            if (YbPayment.SELF_CASH_VX_VALUE.getValue().equals(paymentDetail.getPayEnum())) {
                vxCashSum = vxCashSum.add(paymentDetail.getAmount());
            }
            if (YbPayment.SELF_CASH_ALI_VALUE.getValue().equals(paymentDetail.getPayEnum())) {
                aliCashSum = aliCashSum.add(paymentDetail.getAmount());
            }
            if (YbPayment.SELF_CASH_UNION_VALUE.getValue().equals(paymentDetail.getPayEnum())) {
                uniCashSum = uniCashSum.add(paymentDetail.getAmount());
            }
            if (YbPayment.YB_TC_FUND_AMOUNT.getValue().equals(paymentDetail.getPayEnum())) {
                tcSum = tcSum.add(paymentDetail.getAmount());
            }
            if (YbPayment.YB_FUND_PAY.getValue().equals(paymentDetail.getPayEnum())) {
                fundSum = fundSum.add(paymentDetail.getAmount());
            }
            if (YbPayment.SELF_YB_ZH_PAY.getValue().equals(paymentDetail.getPayEnum())) {
                zhSum = zhSum.add(paymentDetail.getAmount());
            }
            // 其他的大病支付或者慢病特病支付往下接if
        }

        // 处理退费单
        List<ReturnBillVO> returnList = new ArrayList<>();
        List<PaymentReconciliation> returnPaymentList = new ArrayList<>();
        ReturnBillVO returnBillVO;
        for (PaymentReconciliation paymentReconciliation : paymentReconciliationList) {
            if (PaymentType.UN_PAY.getValue().equals(paymentReconciliation.getPaymentEnum())) {
                returnPaymentList.add(paymentReconciliation);
            }
        }
        if (!returnPaymentList.isEmpty()) {
            List<Long> returnIds =
                returnPaymentList.stream().map(PaymentReconciliation::getId).collect(Collectors.toList());

            List<Invoice> invoiceList = iInvoiceService.list(new LambdaUpdateWrapper<Invoice>()
                .in(Invoice::getReconciliationId, returnIds).eq(Invoice::getDeleteFlag, DelFlag.NO.getCode()));
            if (!invoiceList.isEmpty()) {
                Map<Long, List<Invoice>> invoiceKV =
                    invoiceList.stream().collect(Collectors.groupingBy(Invoice::getReconciliationId));
                for (PaymentReconciliation paymentReconciliation : returnPaymentList) {
                    returnBillVO = new ReturnBillVO();
                    returnBillVO.setTotalAmount(paymentReconciliation.getTenderedAmount());
                    List<PaymentRecDetail> paymentRecDetails = paymentDetailsKV.get(paymentReconciliation.getId());
                    for (PaymentRecDetail paymentRecDetail : paymentRecDetails) {
                        if (YbPayment.SELF_CASH_PAY.getValue().equals(paymentRecDetail.getPayEnum())) {
                            returnBillVO.setPaidAmount(paymentRecDetail.getAmount());
                        }
                    }

                    if (invoiceKV.get(paymentReconciliation.getId()) == null) {
                        returnBillVO.setInvoiceNo("");
                    } else {
                        Optional<Invoice> max = invoiceKV.get(paymentReconciliation.getId()).stream()
                            .max(Comparator.comparing(Invoice::getCreateTime));
                        if (max.isPresent()) {
                            returnBillVO.setInvoiceNo(max.get().getBillNo());
                        } else {
                            returnBillVO.setInvoiceNo("");
                        }
                    }
                    returnBillVO.setPaymentNo(paymentReconciliation.getPaymentNo());
                    returnList.add(returnBillVO);
                }
                map.put("returnList", returnList);// 退费单
            }
        }

        map.put("cashSum", cashSum);// 现金支付
        map.put("rmbCashSum", rmbCashSum);// 现金支付
        map.put("vxCashSum", vxCashSum);// 现金支付（）
        map.put("aliCashSum", aliCashSum);// 现金支付（）
        map.put("uniCashSum", uniCashSum);// 现金支付（）
        map.put("tcSum", tcSum);// 基本统筹
        map.put("zhSum", zhSum);// 账户支付
        map.put("fundSum", fundSum);// 基金支付总额

        BigDecimal sum01 = BigDecimal.ZERO;
        BigDecimal sum02 = BigDecimal.ZERO;
        BigDecimal sum03 = BigDecimal.ZERO;
        BigDecimal sum04 = BigDecimal.ZERO;
        BigDecimal sum05 = BigDecimal.ZERO;
        BigDecimal sum06 = BigDecimal.ZERO;
        BigDecimal sum07 = BigDecimal.ZERO;
        BigDecimal sum08 = BigDecimal.ZERO;
        BigDecimal sum09 = BigDecimal.ZERO;
        BigDecimal sum10 = BigDecimal.ZERO;
        BigDecimal sum11 = BigDecimal.ZERO;
        BigDecimal sum12 = BigDecimal.ZERO;
        BigDecimal sum13 = BigDecimal.ZERO;
        BigDecimal sum14 = BigDecimal.ZERO;
        BigDecimal sum15 = BigDecimal.ZERO;

        // 不同医院收费项统计内容不定，下面统计分两个for循环部分统计，一部分按照医保分类统计，一个是按照财务类型的字典去分类
        for (ChargeItem chargeItem : chargeItemList) {

            if (!chargeItem.getStatusEnum().equals(ChargeItemStatus.BILLED.getValue())
                && !chargeItem.getStatusEnum().equals(ChargeItemStatus.REFUNDING.getValue())) {
                continue;
            }

            Long definitionId = chargeItem.getDefinitionId();

            ChargeItemDefinition chargeItemDefinition = chargeItemDefKV.get(definitionId).get(0);

            YbMedChrgItmType medChrgItmType =
                YbMedChrgItmType.getByCode(Integer.parseInt(chargeItemDefinition.getYbType()));

            switch (medChrgItmType) {
                case BED_FEE:
                    sum01 = sum01.add(chargeItem.getTotalPrice());
                    break;
                case DIAGNOSTIC_FEE:
                    sum02 = sum02.add(chargeItem.getTotalPrice());
                    break;
                case CHECK_FEE:
                    sum03 = sum03.add(chargeItem.getTotalPrice());
                    break;
                case DIAGNOSTIC_TEST_FEE:
                    sum04 = sum04.add(chargeItem.getTotalPrice());
                    break;
                case MEDICAL_EXPENSE_FEE:
                    sum05 = sum05.add(chargeItem.getTotalPrice());
                    break;
                case OPERATION_FEE:
                    sum06 = sum06.add(chargeItem.getTotalPrice());
                    break;
                case NURSING_FEE:
                    sum07 = sum07.add(chargeItem.getTotalPrice());
                    break;
                case SANITARY_MATERIALS_FEE:
                    sum08 = sum08.add(chargeItem.getTotalPrice());
                    break;
                case WEST_MEDICINE:
                    sum09 = sum09.add(chargeItem.getTotalPrice());
                    break;
                case CHINESE_MEDICINE_SLICES_FEE:
                    sum10 = sum10.add(chargeItem.getTotalPrice());
                    break;
                case CHINESE_MEDICINE_FEE:
                    sum11 = sum11.add(chargeItem.getTotalPrice());
                    break;
                case GENERAL_CONSULTATION_FEE:
                    sum12 = sum12.add(chargeItem.getTotalPrice());
                    break;
                case REGISTRATION_FEE:
                    sum13 = sum13.add(chargeItem.getTotalPrice());
                    break;
                default:
                    sum14 = sum14.add(chargeItem.getTotalPrice());
                    break;
            }
        }
        map.put("BED_FEE", sum01);// 床位费
        map.put("DIAGNOSTIC_FEE", sum02);// 诊察费
        map.put("CHECK_FEE", sum03);// 检查费
        map.put("DIAGNOSTIC_TEST_FEE", sum04);// 化验费
        map.put("MEDICAL_EXPENSE_FEE", sum05);// 治疗费
        map.put("OPERATION_FEE", sum06);// 手术费
        map.put("NURSING_FEE", sum07);// 护理费
        map.put("SANITARY_MATERIALS_FEE", sum08);// 卫生材料费
        map.put("WEST_MEDICINE", sum09);// 西药费
        map.put("CHINESE_MEDICINE_SLICES_FEE", sum10);// 中药饮片费
        map.put("CHINESE_MEDICINE_FEE", sum11);// 中成药费
        map.put("GENERAL_CONSULTATION_FEE", sum12);// 一般诊疗费
        map.put("REGISTRATION_FEE", sum13);// 挂号费
        map.put("OTHER_FEE", sum14);// 其他费用
        sum15 = sum01.add(sum02).add(sum03).add(sum04).add(sum05).add(sum06).add(sum07).add(sum08).add(sum09).add(sum10)
            .add(sum11).add(sum12).add(sum13).add(sum14);
        map.put("SUM", sum15);// 合计费用

        // String ybSwitch = SecurityUtils.getLoginUser().getOptionJson().getString(CommonConstants.Option.YB_SWITCH);
        JSONObject optionJson = SecurityUtils.getLoginUser().getOptionJson();
        String fixmedinsName = optionJson.getString(CommonConstants.Option.FIXMEDINS_NAME);
        String fixmedinsCode = optionJson.getString(CommonConstants.Option.FIXMEDINS_CODE);

        map.put("fixmedinsName", fixmedinsName);
        map.put("fixmedinsCode", fixmedinsCode);

        // 以chargeItem 的def为循环分类依据
        for (ChargeItemDefinition chargeItemDefinition : chargeItemDefinitions) {
            if (chargeItemDefinition.getTypeCode() == null) {
                throw new ServiceException("收费定义未设置财务分类，提示信息chargeItemDefinitionId：" + chargeItemDefinition.getId());
            }
        }
        Map<String, List<ChargeItemDefinition>> chargeItemDefMapByTypeCode =
            chargeItemDefinitions.stream().collect(Collectors.groupingBy(ChargeItemDefinition::getTypeCode));
        Map<Long, List<ChargeItem>> chargeItemMapByDefinitionId =
            chargeItemList.stream().collect(Collectors.groupingBy(ChargeItem::getDefinitionId));

        for (Map.Entry<String, List<ChargeItemDefinition>> stringListEntry : chargeItemDefMapByTypeCode.entrySet()) {
            String key = stringListEntry.getKey();
            BigDecimal bigDecimal = BigDecimal.ZERO;
            for (ChargeItemDefinition chargeItemDefinition : stringListEntry.getValue()) {
                List<ChargeItem> chargeItems = chargeItemMapByDefinitionId.get(chargeItemDefinition.getId());
                for (ChargeItem chargeItem : chargeItems) {
                    if (chargeItem.getStatusEnum() != ChargeItemStatus.BILLED.getValue()) {
                        continue;
                    }
                    bigDecimal = bigDecimal.add(chargeItem.getTotalPrice());
                }
            }
            map.put(key, bigDecimal);
        }

        return map;
    }

    /**
     * 长大版本(门诊) 2025/08/06版
     *
     * @param
     * @return
     */
    @Override
    public Map getTotalCcu(String startTime, String endTime, Long entererId) {
        // String contractNo="220100";
        Map<String, Object> map = new HashMap<>();

        // SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
        Date startDate = DateUtils.parseDate(startTime);
        Date endDate = DateUtils.parseDate(endTime);

        // 查询所有的门诊支付记录（包含4种类型单据：a：该时间内的正向交易记录；b:该时间内的反向交易记录，但关联的正向单在该时间内；c：该时间内的反向交易记录，但是关联正向单在该时间之前；d：该时间内的正向交易记录，但是关联反向单在该时间之后；）
        LambdaQueryWrapper<PaymentReconciliation> queryWrapper = new LambdaQueryWrapper<PaymentReconciliation>()
            .between(PaymentReconciliation::getBillDate, startDate, endDate)
            .eq(PaymentReconciliation::getDeleteFlag, DelFlag.NO.getCode())
            .in(PaymentReconciliation::getStatusEnum, PaymentStatus.SUCCESS.getValue(),
                PaymentStatus.REFUND_ALL.getValue())
            .eq(PaymentReconciliation::getKindEnum, PaymentKind.OUTPATIENT_CLINIC.getValue());
        if (entererId != null) {
            queryWrapper.eq(PaymentReconciliation::getEntererId, entererId);
        }
        List<PaymentReconciliation> paymentReconciliationList = paymentReconciliationService.list(queryWrapper);
        if (paymentReconciliationList.isEmpty()) {
            return getMap(map);
        }

        // for (PaymentReconciliation paymentReconciliation : paymentReconciliationList) {
        // String[] split = paymentReconciliation.getChargeItemIds().split(",");
        // List<String> strings = Arrays.asList(split);
        // for (String string : strings) {
        // ChargeItem byId = chargeItemService.getById(Long.parseLong(string));
        // if ("adm_healthcare_service".equals(byId.getServiceTable())) {
        // System.out.println("//****************************");
        // System.out.println(JSON.toJSONString(byId));
        // }
        // }
        // }

        // 查询所有的支付详情
        List<Long> paymentIdList =
            paymentReconciliationList.stream().map(PaymentReconciliation::getId).collect(Collectors.toList());
        // List<PaymentRecDetail> paymentDetails = paymentRecDetailService
        // .list(new LambdaQueryWrapper<PaymentRecDetail>().in(PaymentRecDetail::getReconciliationId, paymentIdList)
        // .eq(PaymentRecDetail::getDeleteFlag, DelFlag.NO.getCode()));

        List<PaymentRecDetailAccountResult> PaymentRecDetailAccountResultList =
            paymentRecDetailService.getListByReconciliationIds(paymentIdList);
        if (PaymentRecDetailAccountResultList.isEmpty()) {
            return getMap(map);
        }

        // 根据主键分组
        Map<Long, List<PaymentRecDetailAccountResult>> paymentDetailsKV = PaymentRecDetailAccountResultList.stream()
            .collect(Collectors.groupingBy(PaymentRecDetailAccountResult::getReconciliationId));

        // 调试使用代码
        // for (PaymentReconciliation paymentReconciliation : paymentReconciliationList) {
        // List<PaymentRecDetailAccountResult> paymentRecDetailAccountResults =
        // paymentDetailsKV.get(paymentReconciliation.getId());
        // BigDecimal bigDecimal = BigDecimal.ZERO;
        // for (PaymentRecDetailAccountResult paymentRecDetailAccountResult : paymentRecDetailAccountResults) {
        // if (YbPayment.SELF_YB_ZH_PAY.getValue().equals(paymentRecDetailAccountResult.getPayEnum())) {
        // bigDecimal = bigDecimal.add(paymentRecDetailAccountResult.getAmount());
        // }
        // if (YbPayment.YB_FUND_PAY.getValue().equals(paymentRecDetailAccountResult.getPayEnum())) {
        // bigDecimal = bigDecimal.add(paymentRecDetailAccountResult.getAmount());
        // }
        // if (YbPayment.SELF_CASH_PAY.getValue().equals(paymentRecDetailAccountResult.getPayEnum())) {
        // bigDecimal = bigDecimal.add(paymentRecDetailAccountResult.getAmount());
        // }
        // }
        // if (bigDecimal.compareTo(paymentReconciliation.getTenderedAmount()) != 0) {
        // System.out.println("//////**********************///////");
        // System.out.println("payment:" + paymentReconciliation.getId());
        // System.out.println("paymentAmount:" + paymentReconciliation.getTenderedAmount());
        // System.out.println("payment应收:" + paymentReconciliation.getDisplayAmount());
        // System.out.println("//////**********************///////");
        // }
        // if (paymentReconciliation.getStatusEnum() == 3) {
        // continue;
        // }
        // List<Long> collect = Arrays.stream(paymentReconciliation.getChargeItemIds().split(","))
        // .map(e -> Long.parseLong(e)).collect(Collectors.toList());
        // List<ChargeItemBaseInfoDto> chargeItemBaseInfoByIds = chargeItemService.getChargeItemBaseInfoByIds(collect);
        // BigDecimal bigDecimal1 = BigDecimal.ZERO;
        // for (ChargeItemBaseInfoDto chargeItemBaseInfoById : chargeItemBaseInfoByIds) {
        // bigDecimal1 = bigDecimal1.add(chargeItemBaseInfoById.getTotalPrice());
        // System.out.println("收费项：" + chargeItemBaseInfoById.getTotalPrice());
        // }
        // System.out.println("付款：" + paymentReconciliation.getTenderedAmount());
        // if (bigDecimal1.compareTo(paymentReconciliation.getTenderedAmount()) != 0) {
        // System.out.println("//////**********************///////");
        // System.out.println("payment:" + paymentReconciliation.getId());
        // System.out.println("paymentAmount:" + paymentReconciliation.getTenderedAmount());
        // System.out.println("payment应收:" + paymentReconciliation.getDisplayAmount());
        // System.out.println("//////**********************///////");
        // }
        // }
        // List<ChargeItem> list1 = chargeItemService.list(new LambdaQueryWrapper<ChargeItem>()
        // .eq(ChargeItem::getStatusEnum, 5).between(ChargeItem::getCreateTime, startDate, endDate));
        // for (ChargeItem chargeItem : list1) {
        // PaymentReconciliation one =
        // paymentReconciliationService.getOne(new LambdaQueryWrapper<PaymentReconciliation>()
        // .like(PaymentReconciliation::getChargeItemIds, chargeItem.getId())
        // .eq(PaymentReconciliation::getStatusEnum, 1));
        // if (one == null) {
        // throw new ServiceException("收费项：" + chargeItem.getId());
        // }
        // }

        // 根据省市医保分组
        Map<String, List<PaymentRecDetailAccountResult>> paymentDetailsMapByContract = PaymentRecDetailAccountResultList
            .stream().collect(Collectors.groupingBy(PaymentRecDetailAccountResult::getContractNo));

        // 查询所有的收费项
        List<String> chargeItemIdStrs = paymentReconciliationList.stream().map(PaymentReconciliation::getChargeItemIds)
            .collect(Collectors.toList());
        List<Long> chargeItemIds = new ArrayList<>();
        for (String chargeItemIdStr : chargeItemIdStrs) {
            List<String> strings = Arrays.asList(chargeItemIdStr.split(","));
            for (String string : strings) {
                Long id = Long.parseLong(string);
                chargeItemIds.add(id);
            }
        }

        List<ChargeItem> chargeItemList = chargeItemService.list(new LambdaQueryWrapper<ChargeItem>()
            .in(ChargeItem::getId, chargeItemIds).eq(ChargeItem::getDeleteFlag, DelFlag.NO.getCode()));
        if (chargeItemList.isEmpty()) {
            throw new ServiceException("数据异常，该时间段内未查询到收费项");
        }

        // for (ChargeItem chargeItem : chargeItemList) {
        // if("adm_healthcare_service".equals(chargeItem.getServiceTable())){
        // System.out.println("//****************************");
        // System.out.println(JSON.toJSONString(chargeItem));
        // }
        // }

        // 查询收费定义列表
        List<Long> chargeItemDefinitionIdList =
            chargeItemList.stream().map(ChargeItem::getDefinitionId).collect(Collectors.toList());
        if (chargeItemDefinitionIdList.isEmpty()) {
            throw new ServiceException("未查询到收费记录，无收费项信息");
        }
        List<ChargeItemDefinition> chargeItemDefinitions =
            iChargeItemDefinitionService.listByIds(chargeItemDefinitionIdList);
        if (chargeItemDefinitions.isEmpty()) {
            throw new ServiceException("未查询到收费记录，无收费项信息");
        }
        Map<Long, List<ChargeItemDefinition>> chargeItemDefKV =
            chargeItemDefinitions.stream().collect(Collectors.groupingBy(ChargeItemDefinition::getId));

        // 查询医保结算id
        List<String> settleIds = new ArrayList<>();
        for (PaymentReconciliation paymentReconciliation : paymentReconciliationList) {
            if (!StringUtils.isEmpty(paymentReconciliation.getYbSettleIds())) {
                List<String> strings = Arrays.asList(paymentReconciliation.getYbSettleIds().split(","));
                settleIds.addAll(strings);
            }
        }

        List<ClinicSettle> clinicSettleList = new ArrayList<>();
        List<ClinicUnSettle> clinicUnSettleList = new ArrayList<>();
        if (!settleIds.isEmpty()) {
            clinicSettleList = iClinicSettleService.getBySettleIds(settleIds);
            clinicUnSettleList = iClinicUnSettleService.getBySettleIds(settleIds);
            // List<String> collect = clinicSettle.stream().map(ClinicSettle::getInsutype).collect(Collectors.toList());
        }

        BigDecimal cashSum = BigDecimal.ZERO;// 现金总数 = rmbCashSum + vxCashSum + aliCashSum + uniCashSum
        BigDecimal rmbCashSum = BigDecimal.ZERO;// 现金总数
        BigDecimal vxCashSum = BigDecimal.ZERO;// 现金总数（）
        BigDecimal aliCashSum = BigDecimal.ZERO;// 现金总数（）
        BigDecimal uniCashSum = BigDecimal.ZERO;// 现金总数（）
        BigDecimal vxSum = BigDecimal.ZERO;// 微信总数
        BigDecimal aliSum = BigDecimal.ZERO;// 支付宝总数
        BigDecimal uniSum = BigDecimal.ZERO;// 银行卡总数
        // BigDecimal tcSum = BigDecimal.ZERO;// 基本统筹
        // BigDecimal zhSum = BigDecimal.ZERO;// 医保账户
        // BigDecimal fundSum = BigDecimal.ZERO;// 基金支总额
        BigDecimal SelfCashSum = BigDecimal.ZERO;// 自费现金总额
        BigDecimal YbCashSum = BigDecimal.ZERO;// 医保现金总额
        // 长大版本要显示出来省市医保的区别
        List<Contract> redisContractList = iContractService.getRedisContractList();
        Map<String, List<Contract>> contractMapByBusNo =
            redisContractList.stream().collect(Collectors.groupingBy(Contract::getBusNo));
        for (Map.Entry<String, List<PaymentRecDetailAccountResult>> stringListEntry : paymentDetailsMapByContract
            .entrySet()) {
            String key = stringListEntry.getKey();
            List<PaymentRecDetailAccountResult> value = stringListEntry.getValue();
            BigDecimal tcSum = BigDecimal.ZERO;// 基本统筹
            BigDecimal cash = BigDecimal.ZERO;// 现金
            BigDecimal zhSum = BigDecimal.ZERO;// 医保账户
            BigDecimal fundSum = BigDecimal.ZERO;// 基金支总额
            for (PaymentRecDetailAccountResult paymentRecDetailAccountResult : value) {
                if (YbPayment.SELF_CASH_PAY.getValue().equals(paymentRecDetailAccountResult.getPayEnum())) {
                    cash = cash.add(paymentRecDetailAccountResult.getAmount());
                }
                if (YbPayment.SELF_CASH_VALUE.getValue().equals(paymentRecDetailAccountResult.getPayEnum())) {
                    rmbCashSum = rmbCashSum.add(paymentRecDetailAccountResult.getAmount());
                }
                if (YbPayment.SELF_CASH_VX_VALUE.getValue().equals(paymentRecDetailAccountResult.getPayEnum())) {
                    vxCashSum = vxCashSum.add(paymentRecDetailAccountResult.getAmount());
                }
                if (YbPayment.SELF_CASH_ALI_VALUE.getValue().equals(paymentRecDetailAccountResult.getPayEnum())) {
                    aliCashSum = aliCashSum.add(paymentRecDetailAccountResult.getAmount());
                }
                if (YbPayment.SELF_CASH_UNION_VALUE.getValue().equals(paymentRecDetailAccountResult.getPayEnum())) {
                    uniCashSum = uniCashSum.add(paymentRecDetailAccountResult.getAmount());
                }
                if (YbPayment.YB_TC_FUND_AMOUNT.getValue().equals(paymentRecDetailAccountResult.getPayEnum())) {
                    tcSum = tcSum.add(paymentRecDetailAccountResult.getAmount());
                }
                if (YbPayment.YB_FUND_PAY.getValue().equals(paymentRecDetailAccountResult.getPayEnum())) {
                    fundSum = fundSum.add(paymentRecDetailAccountResult.getAmount());
                }
                if (YbPayment.SELF_YB_ZH_PAY.getValue().equals(paymentRecDetailAccountResult.getPayEnum())) {
                    zhSum = zhSum.add(paymentRecDetailAccountResult.getAmount());
                }
                // 其他的大病支付或者慢病特病支付往下接if
                map.put(
                    contractMapByBusNo.get(key) == null ? key : contractMapByBusNo.get(key).get(0).getBusNo() + "cash",
                    cash);
                map.put(
                    contractMapByBusNo.get(key) == null ? key : contractMapByBusNo.get(key).get(0).getBusNo() + "tcSum",
                    tcSum);
                map.put(
                    contractMapByBusNo.get(key) == null ? key : contractMapByBusNo.get(key).get(0).getBusNo() + "zhSum",
                    zhSum);
                map.put(contractMapByBusNo.get(key) == null ? key
                    : contractMapByBusNo.get(key).get(0).getBusNo() + "fundSum", fundSum);
            }
        }
        // for (PaymentRecDetail paymentDetail : paymentDetails) {
        // if (YbPayment.SELF_CASH_PAY.getValue().equals(paymentDetail.getPayEnum())) {
        // cashSum = cashSum.add(paymentDetail.getAmount());
        // if (paymentDetail.getPayTransText() != null && paymentDetail.getPayTransText().length() > 10) {
        // YbCashSum = YbCashSum.add(paymentDetail.getAmount());
        // } else {
        // SelfCashSum = SelfCashSum.add(paymentDetail.getAmount());
        // }
        // }
        // if (YbPayment.SELF_CASH_VALUE.getValue().equals(paymentDetail.getPayEnum())) {
        // rmbCashSum = rmbCashSum.add(paymentDetail.getAmount());
        // }
        // if (YbPayment.SELF_CASH_VX_VALUE.getValue().equals(paymentDetail.getPayEnum())) {
        // vxCashSum = vxCashSum.add(paymentDetail.getAmount());
        // }
        // if (YbPayment.SELF_CASH_ALI_VALUE.getValue().equals(paymentDetail.getPayEnum())) {
        // aliCashSum = aliCashSum.add(paymentDetail.getAmount());
        // }
        // if (YbPayment.SELF_CASH_UNION_VALUE.getValue().equals(paymentDetail.getPayEnum())) {
        // uniCashSum = uniCashSum.add(paymentDetail.getAmount());
        // }
        // if (YbPayment.YB_TC_FUND_AMOUNT.getValue().equals(paymentDetail.getPayEnum())) {
        // tcSum = tcSum.add(paymentDetail.getAmount());
        // }
        // if (YbPayment.YB_FUND_PAY.getValue().equals(paymentDetail.getPayEnum())) {
        // fundSum = fundSum.add(paymentDetail.getAmount());
        // }
        // if (YbPayment.SELF_YB_ZH_PAY.getValue().equals(paymentDetail.getPayEnum())) {
        // zhSum = zhSum.add(paymentDetail.getAmount());
        // }
        // // 其他的大病支付或者慢病特病支付往下接if
        // }

        BigDecimal sum01 = BigDecimal.ZERO;
        BigDecimal sum02 = BigDecimal.ZERO;
        BigDecimal sum03 = BigDecimal.ZERO;
        BigDecimal sum04 = BigDecimal.ZERO;
        BigDecimal sum05 = BigDecimal.ZERO;
        BigDecimal sum06 = BigDecimal.ZERO;
        BigDecimal sum07 = BigDecimal.ZERO;
        BigDecimal sum08 = BigDecimal.ZERO;
        BigDecimal sum09 = BigDecimal.ZERO;
        BigDecimal sum10 = BigDecimal.ZERO;
        BigDecimal sum11 = BigDecimal.ZERO;
        BigDecimal sum12 = BigDecimal.ZERO;
        BigDecimal sum13 = BigDecimal.ZERO;
        BigDecimal sum14 = BigDecimal.ZERO;
        BigDecimal sum15 = BigDecimal.ZERO;

        // 处理退费单
        List<ReturnBillVO> returnList = new ArrayList<>();
        List<PaymentReconciliation> returnPaymentList = new ArrayList<>();
        ReturnBillVO returnBillVO;
        for (PaymentReconciliation paymentReconciliation : paymentReconciliationList) {
            if (PaymentType.UN_PAY.getValue().equals(paymentReconciliation.getPaymentEnum())) {
                returnPaymentList.add(paymentReconciliation);
            }
        }
        // 按照字典取值时使用的变量
        List<ChargeItemDefinition> beforeChargeItemDefinitions = new ArrayList<>();
        List<ChargeItem> beforeChargeItemList = new ArrayList<>();
        if (!returnPaymentList.isEmpty()) {
            List<Long> returnIds =
                returnPaymentList.stream().map(PaymentReconciliation::getId).collect(Collectors.toList());
            // 查原付款单子
            List<Long> relationIdList =
                returnPaymentList.stream().map(PaymentReconciliation::getRelationId).collect(Collectors.toList());
            if (relationIdList.isEmpty() || returnPaymentList.size() != relationIdList.size()) {
                throw new ServiceException("数据异常，存在无法关联到原单的退款单，请联系工程师");
            }
            // 原单是该时间段前付款的
            List<PaymentReconciliation> beforeList = new ArrayList<>();
            List<PaymentReconciliation> paymentReconciliations = paymentReconciliationService
                .list(new LambdaQueryWrapper<PaymentReconciliation>().in(PaymentReconciliation::getId, relationIdList)
                    .eq(PaymentReconciliation::getDeleteFlag, DelFlag.NO.getCode()));
            for (PaymentReconciliation paymentReconciliation : paymentReconciliations) {
                if (startDate.compareTo(paymentReconciliation.getBillDate()) > 0) {
                    beforeList.add(paymentReconciliation);
                }
            }
            if (!beforeList.isEmpty()) {
                // 拆解所有的chargeItemId，拼装成一个集合
                List<String> chargeItemIdList =
                    beforeList.stream().map(PaymentReconciliation::getChargeItemIds).collect(Collectors.toList());
                List<Long> beforeChargeItemIds = new ArrayList<>();
                for (String chargeItemId : chargeItemIdList) {
                    if (StringUtils.isNotEmpty(chargeItemId)) {
                        beforeChargeItemIds.addAll(Arrays
                            .stream(chargeItemId.replaceAll("\\[", "").replaceAll("\\]", "")
                                .split(CommonConstants.Common.COMMA))
                            .map(Long::parseLong).collect(Collectors.toList()));
                    }
                }
                beforeChargeItemList = chargeItemService.list(new LambdaQueryWrapper<ChargeItem>()
                    .in(ChargeItem::getId, beforeChargeItemIds).eq(ChargeItem::getDeleteFlag, DelFlag.NO.getCode()));
                if (beforeChargeItemList.isEmpty()) {
                    throw new ServiceException("数据异常，查找不到退费收费项信息");
                }
                List<Long> beforeChargeItemDefinitionIdList =
                    beforeChargeItemList.stream().map(ChargeItem::getDefinitionId).collect(Collectors.toList());
                if (beforeChargeItemDefinitionIdList.isEmpty()) {
                    throw new ServiceException("数据异常，查找不到收费项的定义信息");
                }
                beforeChargeItemDefinitions = iChargeItemDefinitionService.listByIds(beforeChargeItemDefinitionIdList);
                for (ChargeItem chargeItem : beforeChargeItemList) {

                    if (!chargeItem.getStatusEnum().equals(ChargeItemStatus.REFUNDED.getValue())) {
                        continue;
                    }

                    chargeItem.setTotalPrice(new BigDecimal("-1").multiply(chargeItem.getTotalPrice()));

                    Long definitionId = chargeItem.getDefinitionId();
                    // if(chargeItemDefKV.get(definitionId)==null){
                    // System.out.println(chargeItem.getId());
                    // System.out.println(JSON.toJSONString(chargeItem));
                    // }

                    ChargeItemDefinition chargeItemDefinition = chargeItemDefKV.get(definitionId).get(0);

                    YbMedChrgItmType medChrgItmType =
                        YbMedChrgItmType.getByCode(Integer.parseInt(chargeItemDefinition.getYbType()));

                    switch (medChrgItmType) {
                        case BED_FEE:
                            sum01 = sum01.add(chargeItem.getTotalPrice());
                            break;
                        case DIAGNOSTIC_FEE:
                            sum02 = sum02.add(chargeItem.getTotalPrice());
                            break;
                        case CHECK_FEE:
                            sum03 = sum03.add(chargeItem.getTotalPrice());
                            break;
                        case DIAGNOSTIC_TEST_FEE:
                            sum04 = sum04.add(chargeItem.getTotalPrice());
                            break;
                        case MEDICAL_EXPENSE_FEE:
                            sum05 = sum05.add(chargeItem.getTotalPrice());
                            break;
                        case OPERATION_FEE:
                            sum06 = sum06.add(chargeItem.getTotalPrice());
                            break;
                        case NURSING_FEE:
                            sum07 = sum07.add(chargeItem.getTotalPrice());
                            break;
                        case SANITARY_MATERIALS_FEE:
                            sum08 = sum08.add(chargeItem.getTotalPrice());
                            break;
                        case WEST_MEDICINE:
                            sum09 = sum09.add(chargeItem.getTotalPrice());
                            break;
                        case CHINESE_MEDICINE_SLICES_FEE:
                            sum10 = sum10.add(chargeItem.getTotalPrice());
                            break;
                        case CHINESE_MEDICINE_FEE:
                            sum11 = sum11.add(chargeItem.getTotalPrice());
                            break;
                        case GENERAL_CONSULTATION_FEE:
                            sum12 = sum12.add(chargeItem.getTotalPrice());
                            break;
                        case REGISTRATION_FEE:
                            sum13 = sum13.add(chargeItem.getTotalPrice());
                            break;
                        default:
                            sum14 = sum14.add(chargeItem.getTotalPrice());
                            break;
                    }
                }
            }

            List<Invoice> invoiceList = iInvoiceService.list(new LambdaUpdateWrapper<Invoice>()
                .in(Invoice::getReconciliationId, returnIds).eq(Invoice::getDeleteFlag, DelFlag.NO.getCode()));
            if (!invoiceList.isEmpty()) {
                Map<Long, List<Invoice>> invoiceKV =
                    invoiceList.stream().collect(Collectors.groupingBy(Invoice::getReconciliationId));
                for (PaymentReconciliation paymentReconciliation : returnPaymentList) {
                    returnBillVO = new ReturnBillVO();
                    returnBillVO.setTotalAmount(paymentReconciliation.getTenderedAmount());
                    List<PaymentRecDetailAccountResult> paymentRecDetails =
                        paymentDetailsKV.get(paymentReconciliation.getId());
                    for (PaymentRecDetailAccountResult paymentRecDetail : paymentRecDetails) {
                        if (YbPayment.SELF_CASH_PAY.getValue().equals(paymentRecDetail.getPayEnum())) {
                            returnBillVO.setPaidAmount(paymentRecDetail.getAmount());
                        }
                    }

                    if (invoiceKV.get(paymentReconciliation.getId()) == null) {
                        returnBillVO.setInvoiceNo("");
                    } else {
                        Optional<Invoice> max = invoiceKV.get(paymentReconciliation.getId()).stream()
                            .max(Comparator.comparing(Invoice::getCreateTime));
                        if (max.isPresent()) {
                            returnBillVO.setInvoiceNo(max.get().getBillNo());
                        } else {
                            returnBillVO.setInvoiceNo("");
                        }
                    }
                    returnBillVO.setPaymentNo(paymentReconciliation.getPaymentNo());
                    returnList.add(returnBillVO);
                }
                map.put("returnList", returnList);// 退费单
            }
        }

        // map.put("tcSum", tcSum);// 基本统筹
        // map.put("zhSum", zhSum);// 账户支付
        // map.put("fundSum", fundSum);// 基金支付总额
        map.put("ybCashSum", YbCashSum);// 医保现金
        map.put("selfCashSum", SelfCashSum);// 自费现金

        // 不同医院收费项统计内容不定，下面统计分两个for循环部分统计，一部分按照医保分类统计，一个是按照财务类型的字典去分类
        for (ChargeItem chargeItem : chargeItemList) {

            if (!chargeItem.getStatusEnum().equals(ChargeItemStatus.BILLED.getValue())
                && !chargeItem.getStatusEnum().equals(ChargeItemStatus.REFUNDING.getValue())) {
                continue;
            }

            Long definitionId = chargeItem.getDefinitionId();
            // if(chargeItemDefKV.get(definitionId)==null){
            // System.out.println(chargeItem.getId());
            // System.out.println(JSON.toJSONString(chargeItem));
            // }

            ChargeItemDefinition chargeItemDefinition = chargeItemDefKV.get(definitionId).get(0);

            YbMedChrgItmType medChrgItmType =
                YbMedChrgItmType.getByCode(Integer.parseInt(chargeItemDefinition.getYbType()));

            switch (medChrgItmType) {
                case BED_FEE:
                    sum01 = sum01.add(chargeItem.getTotalPrice());
                    break;
                case DIAGNOSTIC_FEE:
                    sum02 = sum02.add(chargeItem.getTotalPrice());
                    break;
                case CHECK_FEE:
                    sum03 = sum03.add(chargeItem.getTotalPrice());
                    break;
                case DIAGNOSTIC_TEST_FEE:
                    sum04 = sum04.add(chargeItem.getTotalPrice());
                    break;
                case MEDICAL_EXPENSE_FEE:
                    sum05 = sum05.add(chargeItem.getTotalPrice());
                    break;
                case OPERATION_FEE:
                    sum06 = sum06.add(chargeItem.getTotalPrice());
                    break;
                case NURSING_FEE:
                    sum07 = sum07.add(chargeItem.getTotalPrice());
                    break;
                case SANITARY_MATERIALS_FEE:
                    sum08 = sum08.add(chargeItem.getTotalPrice());
                    break;
                case WEST_MEDICINE:
                    sum09 = sum09.add(chargeItem.getTotalPrice());
                    break;
                case CHINESE_MEDICINE_SLICES_FEE:
                    sum10 = sum10.add(chargeItem.getTotalPrice());
                    break;
                case CHINESE_MEDICINE_FEE:
                    sum11 = sum11.add(chargeItem.getTotalPrice());
                    break;
                case GENERAL_CONSULTATION_FEE:
                    sum12 = sum12.add(chargeItem.getTotalPrice());
                    break;
                case REGISTRATION_FEE:
                    sum13 = sum13.add(chargeItem.getTotalPrice());
                    break;
                default:
                    sum14 = sum14.add(chargeItem.getTotalPrice());
                    break;
            }
        }
        map.put("BED_FEE", sum01);// 床位费
        map.put("DIAGNOSTIC_FEE", sum02);// 诊察费
        map.put("CHECK_FEE", sum03);// 检查费
        map.put("DIAGNOSTIC_TEST_FEE", sum04);// 化验费
        map.put("MEDICAL_EXPENSE_FEE", sum05);// 治疗费
        map.put("OPERATION_FEE", sum06);// 手术费
        map.put("NURSING_FEE", sum07);// 护理费
        map.put("SANITARY_MATERIALS_FEE", sum08);// 卫生材料费
        map.put("WEST_MEDICINE", sum09);// 西药费
        map.put("CHINESE_MEDICINE_SLICES_FEE", sum10);// 中药饮片费
        map.put("CHINESE_MEDICINE_FEE", sum11);// 中成药费
        map.put("GENERAL_CONSULTATION_FEE", sum12);// 一般诊疗费
        map.put("REGISTRATION_FEE", sum13);// 挂号费
        map.put("OTHER_FEE", sum14);// 其他费用
        sum15 = sum01.add(sum02).add(sum03).add(sum04).add(sum05).add(sum06).add(sum07).add(sum08).add(sum09).add(sum10)
            .add(sum11).add(sum12).add(sum13).add(sum14);
        map.put("SUM", sum15);// 合计费用

        // String ybSwitch = SecurityUtils.getLoginUser().getOptionJson().getString(CommonConstants.Option.YB_SWITCH);
        JSONObject optionJson = SecurityUtils.getLoginUser().getOptionJson();
        String fixmedinsName = optionJson.getString(CommonConstants.Option.FIXMEDINS_NAME);
        String fixmedinsCode = optionJson.getString(CommonConstants.Option.FIXMEDINS_CODE);

        map.put("fixmedinsName", fixmedinsName);
        map.put("fixmedinsCode", fixmedinsCode);

        // 以chargeItem 的def为循环分类依据
        for (ChargeItemDefinition chargeItemDefinition : chargeItemDefinitions) {
            if (chargeItemDefinition.getTypeCode() == null) {
                throw new ServiceException("收费定义未设置财务分类，提示信息chargeItemDefinitionId：" + chargeItemDefinition.getId());
            }
        }

        Map<String, List<ChargeItemDefinition>> chargeItemDefMapByTypeCode =
            chargeItemDefinitions.stream().collect(Collectors.groupingBy(ChargeItemDefinition::getTypeCode));
        Map<Long, List<ChargeItem>> chargeItemMapByDefinitionId =
            chargeItemList.stream().collect(Collectors.groupingBy(ChargeItem::getDefinitionId));

        for (Map.Entry<String, List<ChargeItemDefinition>> stringListEntry : chargeItemDefMapByTypeCode.entrySet()) {
            String key = stringListEntry.getKey();
            BigDecimal bigDecimal = BigDecimal.ZERO;
            for (ChargeItemDefinition chargeItemDefinition : stringListEntry.getValue()) {
                List<ChargeItem> chargeItems = chargeItemMapByDefinitionId.get(chargeItemDefinition.getId());
                for (ChargeItem chargeItem : chargeItems) {
                    if (chargeItem.getStatusEnum() != ChargeItemStatus.BILLED.getValue()) {
                        continue;
                    }
                    bigDecimal = bigDecimal.add(chargeItem.getTotalPrice());
                }
            }
            map.put(key, bigDecimal);
        }

        // 超本时间段的退费单统计
        if (!beforeChargeItemDefinitions.isEmpty() && !beforeChargeItemList.isEmpty()) {
            Map<String, List<ChargeItemDefinition>> beforeChargeItemDefMapByTypeCode =
                beforeChargeItemDefinitions.stream().collect(Collectors.groupingBy(ChargeItemDefinition::getTypeCode));
            Map<Long, List<ChargeItem>> beforeChargeItemMapByDefinitionId =
                beforeChargeItemList.stream().collect(Collectors.groupingBy(ChargeItem::getDefinitionId));
            for (Map.Entry<String, List<ChargeItemDefinition>> longListEntry : beforeChargeItemDefMapByTypeCode
                .entrySet()) {
                BigDecimal bigDecimal = map.get(longListEntry.getKey()) == null ? BigDecimal.ZERO
                    : new BigDecimal(String.valueOf(map.get(longListEntry.getKey())));
                for (ChargeItemDefinition chargeItemDefinition : longListEntry.getValue()) {
                    List<ChargeItem> chargeItems = beforeChargeItemMapByDefinitionId.get(chargeItemDefinition.getId());
                    for (ChargeItem chargeItem : chargeItems) {
                        if (!chargeItem.getStatusEnum().equals(ChargeItemStatus.REFUNDED.getValue())) {
                            continue;
                        }
                        // chargeItem.setTotalPrice(new BigDecimal("-1").multiply(chargeItem.getTotalPrice()));
                        bigDecimal = bigDecimal.add(chargeItem.getTotalPrice());
                    }
                }
                map.put(longListEntry.getKey(), bigDecimal);
            }
        }

        // 医保人次自费人次计算
        List<EncounterAccountDto> list = iEncounterService.getEncounterInfoByTime(startDate, endDate);
        Map<String, List<EncounterAccountDto>> encounterAccountDtoMapByContract =
            list.stream().collect(Collectors.groupingBy(EncounterAccountDto::getContractNo));
        for (Map.Entry<String, List<EncounterAccountDto>> stringListEntry : encounterAccountDtoMapByContract
            .entrySet()) {
            String key = stringListEntry.getKey();
            map.put(key + "reg", stringListEntry.getValue().size());
        }

        return map;
    }

    /**
     * 长大门诊日结单(最终版) ps：小范围区间内通用版本，需要时间检验
     * 
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param entererId 参与人id
     * @return 参数
     */
    public Map getTotalCommen(String startTime, String endTime, Long entererId, String contractNo) {

        // 声明变量 处理时间
        Map<String, Object> map = new HashMap<>();
        Date startDate = DateUtils.parseDate(startTime);
        Date endDate = DateUtils.parseDate(endTime);

        // 查询所有的门诊支付记录 ，大概的情况如下
        // startDate endDate
        // | 正 负 | a.该情况下的chargeItem 状态为8 不用统计
        // | 正 | b.该情况的chargeItem 状态为5 计入统计 做加法
        // 正 | 负 | c.该情况的chargeItem 状态为8 计入统计 做减法
        // | 正 | 负 d.该情况的chargeItem 状态为8 计入统计 做加法
        // | 正 负 | 负 e.该情况的chargeItem 状态8或5 区间内正负的chargeItem差值状态为5 计入统计 做加法
        // | 正 | 负 负 f.该情况下的chargeItem 状态为8或5 全部计入统计 做加法
        // 正 负 | 负 | g.该情况的chargeItem 状态8或5 负的chargeItem状态为8 计入统计 做减法
        LambdaQueryWrapper<PaymentReconciliation> queryWrapper = new LambdaQueryWrapper<PaymentReconciliation>()
            .between(PaymentReconciliation::getBillDate, startDate, endDate)
            .eq(PaymentReconciliation::getDeleteFlag, DelFlag.NO.getCode())
            .in(PaymentReconciliation::getStatusEnum, PaymentStatus.SUCCESS.getValue(),
                PaymentStatus.REFUND_ALL.getValue())
            .eq(PaymentReconciliation::getKindEnum, PaymentKind.OUTPATIENT_CLINIC.getValue());
        if (entererId != null) {
            queryWrapper.eq(PaymentReconciliation::getEntererId, entererId);
        }
        // List<PaymentReconciliation> paymentReconciliationList = paymentReconciliationService.list(queryWrapper);
        List<PaymentReconciliationAccountDel> paymentReconciliationList = paymentReconciliationService
            .getPaymentAccountContract(startTime, endTime, entererId, contractNo, PaymentStatus.SUCCESS.getValue(),
                PaymentStatus.REFUND_ALL.getValue(), PaymentKind.OUTPATIENT_CLINIC.getValue());

        if (paymentReconciliationList.isEmpty()) {
            return getMap(map);
        }

        // 查询所有的支付详情（业务注释：收集并统计不同支付渠道支付的费用）
        List<Long> paymentIdList =
            paymentReconciliationList.stream().map(PaymentReconciliationAccountDel::getId).collect(Collectors.toList());
        List<PaymentRecDetailAccountResult> PaymentRecDetailAccountResultList =
            paymentRecDetailService.getListByReconciliationIds(paymentIdList);
        if (PaymentRecDetailAccountResultList.isEmpty()) {
            return getMap(map);
        }

        // 支付详情根据主键分组
        Map<Long, List<PaymentRecDetailAccountResult>> paymentDetailsKV = PaymentRecDetailAccountResultList.stream()
            .collect(Collectors.groupingBy(PaymentRecDetailAccountResult::getReconciliationId));

        // 根据省市医保分组
        Map<String, List<PaymentRecDetailAccountResult>> paymentDetailsMapByContract = PaymentRecDetailAccountResultList
            .stream().collect(Collectors.groupingBy(PaymentRecDetailAccountResult::getContractNo));

        BigDecimal cashSum = BigDecimal.ZERO;// 现金总数 = rmbCashSum + vxCashSum + aliCashSum + uniCashSum
        BigDecimal rmbCashSum = BigDecimal.ZERO;// 现金总数
        BigDecimal vxCashSum = BigDecimal.ZERO;// 现金总数（）
        BigDecimal aliCashSum = BigDecimal.ZERO;// 现金总数（）
        BigDecimal uniCashSum = BigDecimal.ZERO;// 现金总数（）
        BigDecimal vxSum = BigDecimal.ZERO;// 微信总数
        BigDecimal aliSum = BigDecimal.ZERO;// 支付宝总数
        BigDecimal uniSum = BigDecimal.ZERO;// 银行卡总数
        BigDecimal SelfCashSum = BigDecimal.ZERO;// 自费现金总额
        BigDecimal YbCashSum = BigDecimal.ZERO;// 医保现金总额
        BigDecimal discountSum = BigDecimal.ZERO;// 优惠金额
        // 长大版本要显示出来省市医保的区别
        List<Contract> redisContractList = iContractService.getRedisContractList();
        Map<String, List<Contract>> contractMapByBusNo =
            redisContractList.stream().collect(Collectors.groupingBy(Contract::getBusNo));
        for (Map.Entry<String, List<PaymentRecDetailAccountResult>> stringListEntry : paymentDetailsMapByContract
            .entrySet()) {

            String key = stringListEntry.getKey();
            List<PaymentRecDetailAccountResult> value = stringListEntry.getValue();

            BigDecimal tcSum = BigDecimal.ZERO;// 基本统筹
            BigDecimal cash = BigDecimal.ZERO;// 现金
            BigDecimal zhSum = BigDecimal.ZERO;// 医保账户
            BigDecimal fundSum = BigDecimal.ZERO;// 基金支总额

            for (PaymentRecDetailAccountResult paymentRecDetailAccountResult : value) {
                if (YbPayment.SELF_CASH_PAY.getValue().equals(paymentRecDetailAccountResult.getPayEnum())) {
                    cash = cash.add(paymentRecDetailAccountResult.getAmount());
                }
                if (YbPayment.SELF_CASH_VALUE.getValue().equals(paymentRecDetailAccountResult.getPayEnum())) {
                    rmbCashSum = rmbCashSum.add(paymentRecDetailAccountResult.getAmount());
                }
                if (YbPayment.SELF_CASH_VX_VALUE.getValue().equals(paymentRecDetailAccountResult.getPayEnum())) {
                    vxCashSum = vxCashSum.add(paymentRecDetailAccountResult.getAmount());
                }
                if (YbPayment.SELF_CASH_ALI_VALUE.getValue().equals(paymentRecDetailAccountResult.getPayEnum())) {
                    aliCashSum = aliCashSum.add(paymentRecDetailAccountResult.getAmount());
                }
                if (YbPayment.SELF_CASH_UNION_VALUE.getValue().equals(paymentRecDetailAccountResult.getPayEnum())) {
                    uniCashSum = uniCashSum.add(paymentRecDetailAccountResult.getAmount());
                }
                if (YbPayment.YB_TC_FUND_AMOUNT.getValue().equals(paymentRecDetailAccountResult.getPayEnum())) {
                    tcSum = tcSum.add(paymentRecDetailAccountResult.getAmount());
                }
                if (YbPayment.YB_FUND_PAY.getValue().equals(paymentRecDetailAccountResult.getPayEnum())) {
                    fundSum = fundSum.add(paymentRecDetailAccountResult.getAmount());
                }
                if (YbPayment.SELF_YB_ZH_PAY.getValue().equals(paymentRecDetailAccountResult.getPayEnum())) {
                    zhSum = zhSum.add(paymentRecDetailAccountResult.getAmount());
                }
                if (YbPayment.DISCOUNT_PAY.getValue().equals(paymentRecDetailAccountResult.getPayEnum())) {
                    discountSum = discountSum.add(paymentRecDetailAccountResult.getAmount());
                }
                // 其他的大病支付或者慢病特病支付往下接if
                map.put(
                    contractMapByBusNo.get(key) == null ? key : contractMapByBusNo.get(key).get(0).getBusNo() + "cash",
                    cash);
                map.put(
                    contractMapByBusNo.get(key) == null ? key : contractMapByBusNo.get(key).get(0).getBusNo() + "tcSum",
                    tcSum);
                map.put(
                    contractMapByBusNo.get(key) == null ? key : contractMapByBusNo.get(key).get(0).getBusNo() + "zhSum",
                    zhSum);
                map.put(contractMapByBusNo.get(key) == null ? key
                    : contractMapByBusNo.get(key).get(0).getBusNo() + "fundSum", fundSum);
            }
        }
        map.put("ybCashSum", YbCashSum);// 医保现金
        // map.put("selfCashSum", SelfCashSum);// 自费现金
        map.put("rmbCashSum", rmbCashSum);// 自费现金纯现金
        map.put("vxCashSum", vxCashSum);// 自费现金vx
        map.put("uniCashSum", uniCashSum);// 自费现金银联
        map.put("aliCashSum", aliCashSum);// 自费现金ali
        map.put("discountSum", discountSum);// 优惠金额

        // 将所有的payment分组进行单独处理（业务注释：处理不同财务分类的金额，如西药费中药费等）
        List<PaymentReconciliationAccountDel> paymentList = new ArrayList<>();
        List<PaymentReconciliationAccountDel> returnList = new ArrayList<>();
        // List<PaymentReconciliation> partReturnList = new ArrayList<>();

        for (PaymentReconciliationAccountDel paymentReconciliation : paymentReconciliationList) {
            if (PaymentStatus.REFUND_ALL.getValue().equals(paymentReconciliation.getStatusEnum())) {
                returnList.add(paymentReconciliation);
            } else if (PaymentStatus.REFUND_PART.getValue().equals(paymentReconciliation.getStatusEnum())) {
                // partReturnList.add(paymentReconciliation);
                paymentList.add(paymentReconciliation);
            } else {
                paymentList.add(paymentReconciliation);
            }
        }

        Map<Long, List<PaymentReconciliationAccountDel>> returnPaymentMapByRelationId = new HashMap<>();
        if (!returnList.isEmpty()) {
            returnPaymentMapByRelationId =
                returnList.stream().collect(Collectors.groupingBy(PaymentReconciliationAccountDel::getRelationId));
        }

        List<String> addChargeItemIds = new ArrayList<>();
        List<String> subChargeItemIds = new ArrayList<>();
        for (PaymentReconciliationAccountDel paymentReconciliation : paymentList) {
            List<PaymentReconciliationAccountDel> paymentReconciliations =
                returnPaymentMapByRelationId.get(paymentReconciliation.getId());
            if (paymentReconciliations != null && !paymentReconciliations.isEmpty()) {
                // 情况a
                if (PaymentStatus.SUCCESS.getValue().equals(paymentReconciliation.getStatusEnum())) {
                    returnPaymentMapByRelationId.remove(paymentReconciliation.getId());
                    continue;
                }
                // 情况 e
                List<String> strings = Arrays.asList(paymentReconciliation.getChargeItemIds().split(","));
                List<String> split = new ArrayList<>();
                for (PaymentReconciliationAccountDel reconciliation : paymentReconciliations) {
                    split.addAll(Arrays.asList(reconciliation.getChargeItemIds().split(",")));
                }
                strings.removeAll(split);
                addChargeItemIds.addAll(strings);
                returnPaymentMapByRelationId.remove(paymentReconciliation.getId());
            } else {
                // 情况 b
                // 情况 d
                // 情况 f
                addChargeItemIds.addAll(Arrays.asList(paymentReconciliation.getChargeItemIds().split(",")));
            }
        }

        // 情况 c
        // 情况 g
        for (Map.Entry<Long, List<PaymentReconciliationAccountDel>> longListEntry : returnPaymentMapByRelationId
            .entrySet()) {
            for (PaymentReconciliationAccountDel paymentReconciliation : longListEntry.getValue()) {
                subChargeItemIds.addAll(Arrays.asList(paymentReconciliation.getChargeItemIds().split(",")));
            }
        }

        // 查询所有的收费项
        List<String> chargeItemIdStrs = new ArrayList<>();
        chargeItemIdStrs.addAll(addChargeItemIds);
        chargeItemIdStrs.addAll(subChargeItemIds);
        List<Long> chargeItemIds = new ArrayList<>();
        for (String chargeItemIdStr : chargeItemIdStrs) {
            String[] strings = chargeItemIdStr.split(",");
            for (String string : strings) {
                Long id = Long.parseLong(string);
                chargeItemIds.add(id);
            }
        }

        // 查不到收费项的情况下不统计了
        if (chargeItemIds.isEmpty()) {
            return getMap(map);
        }
        List<ChargeItemDefInfo> chargeItemDefInfoByIds = chargeItemService.getChargeItemDefInfoByIds(chargeItemIds);
        if (chargeItemDefInfoByIds.isEmpty()) {
            throw new ServiceException("数据异常，该时间段内未查询到收费项");
        }
        Map<Long, List<ChargeItemDefInfo>> chargeItemDefInfoKVById =
            chargeItemDefInfoByIds.stream().collect(Collectors.groupingBy(ChargeItemDefInfo::getId));

        // 省名变量
        BigDecimal bedFee = BigDecimal.ZERO;// 床位费
        BigDecimal diagnosticFee = BigDecimal.ZERO;// 诊察费
        BigDecimal checkFee = BigDecimal.ZERO;// 检查费
        BigDecimal diagnosticTestFee = BigDecimal.ZERO;// 化验费
        BigDecimal medicalExpenseFee = BigDecimal.ZERO;// 治疗费
        BigDecimal operationFee = BigDecimal.ZERO;// 手术费
        BigDecimal nursingFee = BigDecimal.ZERO;// 护理费
        BigDecimal sanitaryMaterialsFee = BigDecimal.ZERO;// 卫生材料费
        BigDecimal westMedicine = BigDecimal.ZERO;// 西药费
        BigDecimal chineseMedicineSlicesFee = BigDecimal.ZERO;// 中药饮片费
        BigDecimal chineseMedicineFee = BigDecimal.ZERO;// 中成药费
        BigDecimal generalConsultationFee = BigDecimal.ZERO;// 一般诊疗费
        BigDecimal registrationFee = BigDecimal.ZERO;// 挂号费
        BigDecimal otherFee = BigDecimal.ZERO;// 其他费用
        BigDecimal sum = BigDecimal.ZERO;// 合计费用

        ChargeItemDefInfo chargeItem;
        for (String addChargeItemId : addChargeItemIds) {
            List<ChargeItemDefInfo> chargeItems = chargeItemDefInfoKVById.get(Long.parseLong(addChargeItemId));
            if (chargeItems == null || chargeItems.isEmpty()) {
                continue;
            }
            chargeItem = chargeItems.get(0);
            YbMedChrgItmType medChrgItmType = YbMedChrgItmType.getByCode(Integer.parseInt(chargeItem.getYbType()));

            switch (medChrgItmType) {
                case BED_FEE:
                    bedFee = bedFee.add(chargeItem.getTotalPrice());
                    break;
                case DIAGNOSTIC_FEE:
                    diagnosticFee = diagnosticFee.add(chargeItem.getTotalPrice());
                    break;
                case CHECK_FEE:
                    checkFee = checkFee.add(chargeItem.getTotalPrice());
                    break;
                case DIAGNOSTIC_TEST_FEE:
                    diagnosticTestFee = diagnosticTestFee.add(chargeItem.getTotalPrice());
                    break;
                case MEDICAL_EXPENSE_FEE:
                    medicalExpenseFee = medicalExpenseFee.add(chargeItem.getTotalPrice());
                    break;
                case OPERATION_FEE:
                    operationFee = operationFee.add(chargeItem.getTotalPrice());
                    break;
                case NURSING_FEE:
                    nursingFee = nursingFee.add(chargeItem.getTotalPrice());
                    break;
                case SANITARY_MATERIALS_FEE:
                    sanitaryMaterialsFee = sanitaryMaterialsFee.add(chargeItem.getTotalPrice());
                    break;
                case WEST_MEDICINE:
                    westMedicine = westMedicine.add(chargeItem.getTotalPrice());
                    break;
                case CHINESE_MEDICINE_SLICES_FEE:
                    chineseMedicineSlicesFee = chineseMedicineSlicesFee.add(chargeItem.getTotalPrice());
                    break;
                case CHINESE_MEDICINE_FEE:
                    chineseMedicineFee = chineseMedicineFee.add(chargeItem.getTotalPrice());
                    break;
                case GENERAL_CONSULTATION_FEE:
                    generalConsultationFee = generalConsultationFee.add(chargeItem.getTotalPrice());
                    break;
                case REGISTRATION_FEE:
                    registrationFee = registrationFee.add(chargeItem.getTotalPrice());
                    break;
                default:
                    otherFee = otherFee.add(chargeItem.getTotalPrice());
                    break;
            }
        }

        for (String subChargeItemId : subChargeItemIds) {
            List<ChargeItemDefInfo> chargeItems = chargeItemDefInfoKVById.get(Long.parseLong(subChargeItemId));
            if (chargeItems == null || chargeItems.isEmpty()) {
                continue;
            }
            chargeItem = chargeItems.get(0);

            YbMedChrgItmType medChrgItmType = YbMedChrgItmType.getByCode(Integer.parseInt(chargeItem.getYbType()));

            switch (medChrgItmType) {
                case BED_FEE:
                    bedFee = bedFee.subtract(chargeItem.getTotalPrice());
                    break;
                case DIAGNOSTIC_FEE:
                    diagnosticFee = diagnosticFee.subtract(chargeItem.getTotalPrice());
                    break;
                case CHECK_FEE:
                    checkFee = checkFee.subtract(chargeItem.getTotalPrice());
                    break;
                case DIAGNOSTIC_TEST_FEE:
                    diagnosticTestFee = diagnosticTestFee.subtract(chargeItem.getTotalPrice());
                    break;
                case MEDICAL_EXPENSE_FEE:
                    medicalExpenseFee = medicalExpenseFee.subtract(chargeItem.getTotalPrice());
                    break;
                case OPERATION_FEE:
                    operationFee = operationFee.subtract(chargeItem.getTotalPrice());
                    break;
                case NURSING_FEE:
                    nursingFee = nursingFee.subtract(chargeItem.getTotalPrice());
                    break;
                case SANITARY_MATERIALS_FEE:
                    sanitaryMaterialsFee = sanitaryMaterialsFee.subtract(chargeItem.getTotalPrice());
                    break;
                case WEST_MEDICINE:
                    westMedicine = westMedicine.subtract(chargeItem.getTotalPrice());
                    break;
                case CHINESE_MEDICINE_SLICES_FEE:
                    chineseMedicineSlicesFee = chineseMedicineSlicesFee.subtract(chargeItem.getTotalPrice());
                    break;
                case CHINESE_MEDICINE_FEE:
                    chineseMedicineFee = chineseMedicineFee.subtract(chargeItem.getTotalPrice());
                    break;
                case GENERAL_CONSULTATION_FEE:
                    generalConsultationFee = generalConsultationFee.subtract(chargeItem.getTotalPrice());
                    break;
                case REGISTRATION_FEE:
                    registrationFee = registrationFee.subtract(chargeItem.getTotalPrice());
                    break;
                default:
                    otherFee = otherFee.subtract(chargeItem.getTotalPrice());
                    break;
            }
        }

        map.put("BED_FEE", bedFee);// 床位费
        map.put("DIAGNOSTIC_FEE", diagnosticFee);// 诊察费
        map.put("CHECK_FEE", checkFee);// 检查费
        map.put("DIAGNOSTIC_TEST_FEE", diagnosticTestFee);// 化验费
        map.put("MEDICAL_EXPENSE_FEE", medicalExpenseFee);// 治疗费
        map.put("OPERATION_FEE", operationFee);// 手术费
        map.put("NURSING_FEE", nursingFee);// 护理费
        map.put("SANITARY_MATERIALS_FEE", sanitaryMaterialsFee);// 卫生材料费
        map.put("WEST_MEDICINE", westMedicine);// 西药费
        map.put("CHINESE_MEDICINE_SLICES_FEE", chineseMedicineSlicesFee);// 中药饮片费
        map.put("CHINESE_MEDICINE_FEE", chineseMedicineFee);// 中成药费
        map.put("GENERAL_CONSULTATION_FEE", generalConsultationFee);// 一般诊疗费
        map.put("REGISTRATION_FEE", registrationFee);// 挂号费
        map.put("OTHER_FEE", otherFee);// 其他费用
        sum = bedFee.add(diagnosticFee).add(checkFee).add(diagnosticTestFee).add(medicalExpenseFee).add(operationFee)
            .add(nursingFee).add(sanitaryMaterialsFee).add(westMedicine).add(chineseMedicineFee)
            .add(chineseMedicineSlicesFee).add(generalConsultationFee).add(registrationFee).add(otherFee).subtract(discountSum);
        map.put("SUM", sum);// 合计费用

        Map<String, List<ChargeItemDefInfo>> chargeItemDefKVByTypeCode =
            chargeItemDefInfoByIds.stream().collect(Collectors.groupingBy(ChargeItemDefInfo::getTypeCode));
        for (Map.Entry<String, List<ChargeItemDefInfo>> longListEntry : chargeItemDefKVByTypeCode.entrySet()) {
            String key = longListEntry.getKey();
            BigDecimal bigDecimal = BigDecimal.ZERO;
            for (ChargeItemDefInfo itemDefinition : longListEntry.getValue()) {
                if (subChargeItemIds.contains(itemDefinition.getId().toString())) {
                    bigDecimal = bigDecimal.subtract(itemDefinition.getTotalPrice());
                } else {
                    bigDecimal = bigDecimal.add(itemDefinition.getTotalPrice());
                }
            }
            map.put(key, bigDecimal);
        }

        // 体检人次(长大专用)
        List<ChargeItemDefInfo> chargeItemDefInfos = chargeItemDefKVByTypeCode.get("9999");
        BigDecimal peisCnt = BigDecimal.ZERO;
        if (chargeItemDefInfos != null) {
            for (ChargeItemDefInfo chargeItemDefInfo : chargeItemDefInfos) {
                peisCnt = peisCnt.add(chargeItemDefInfo.getQuantityValue());
            }
        }
        map.put("peisCnt", peisCnt);// 体检人次

        // 处理退费单
        List<ReturnBillVO> returnBillVOList = new ArrayList<>();
        ReturnBillVO returnBillVO;

        if (!returnList.isEmpty()) {
            List<Long> returnIds =
                returnList.stream().map(PaymentReconciliationAccountDel::getId).collect(Collectors.toList());
            // 查原付款单子
            List<Long> relationIdList =
                returnList.stream().map(PaymentReconciliationAccountDel::getRelationId).collect(Collectors.toList());
            if (relationIdList.isEmpty() || returnList.size() != relationIdList.size()) {
                throw new ServiceException("数据异常，存在无法关联到原单的退款单，请联系工程师");
            }

            List<Invoice> invoiceList = iInvoiceService.list(new LambdaUpdateWrapper<Invoice>()
                .in(Invoice::getReconciliationId, returnIds).eq(Invoice::getDeleteFlag, DelFlag.NO.getCode()));
            if (!invoiceList.isEmpty()) {
                Map<Long, List<Invoice>> invoiceKV =
                    invoiceList.stream().collect(Collectors.groupingBy(Invoice::getReconciliationId));
                for (PaymentReconciliationAccountDel paymentReconciliation : returnList) {
                    returnBillVO = new ReturnBillVO();
                    returnBillVO.setTotalAmount(paymentReconciliation.getTenderedAmount());
                    List<PaymentRecDetailAccountResult> paymentRecDetails =
                        paymentDetailsKV.get(paymentReconciliation.getId());
                    for (PaymentRecDetailAccountResult paymentRecDetail : paymentRecDetails) {
                        if (YbPayment.SELF_CASH_PAY.getValue().equals(paymentRecDetail.getPayEnum())) {
                            returnBillVO.setPaidAmount(paymentRecDetail.getAmount());
                        }
                    }

                    if (invoiceKV.get(paymentReconciliation.getId()) == null) {
                        returnBillVO.setInvoiceNo("");
                    } else {
                        Optional<Invoice> max = invoiceKV.get(paymentReconciliation.getId()).stream()
                            .max(Comparator.comparing(Invoice::getCreateTime));
                        if (max.isPresent()) {
                            returnBillVO.setInvoiceNo(max.get().getBillNo());
                        } else {
                            returnBillVO.setInvoiceNo("");
                        }
                    }
                    returnBillVO.setPaymentNo(paymentReconciliation.getPaymentNo());
                    returnBillVOList.add(returnBillVO);
                }
                map.put("returnList", returnBillVOList);// 退费单
            }
        }

        // map.put("tcSum", tcSum);// 基本统筹
        // map.put("zhSum", zhSum);// 账户支付
        // map.put("fundSum", fundSum);// 基金支付总额

        // 医保人次自费人次计算
        List<EncounterAccountDto> list = iEncounterService.getEncounterInfoByTime(startDate, endDate);
        Map<String, List<EncounterAccountDto>> encounterAccountDtoMapByContract =
            list.stream().collect(Collectors.groupingBy(EncounterAccountDto::getContractNo));
        for (Map.Entry<String, List<EncounterAccountDto>> stringListEntry : encounterAccountDtoMapByContract
            .entrySet()) {
            String key = stringListEntry.getKey();
            map.put(key + "reg", stringListEntry.getValue().size());
        }

        return map;
    }

    private Map getMap(Map<String, Object> map) {

        JSONObject optionJson = SecurityUtils.getLoginUser().getOptionJson();
        String fixmedinsName = optionJson.getString(CommonConstants.Option.FIXMEDINS_NAME);
        String fixmedinsCode = optionJson.getString(CommonConstants.Option.FIXMEDINS_CODE);

        map.put("fixmedinsName", fixmedinsName);
        map.put("fixmedinsCode", fixmedinsCode);

        map.put("BED_FEE", BigDecimal.ZERO);// 床位费
        map.put("DIAGNOSTIC_FEE", BigDecimal.ZERO);// 诊察费
        map.put("CHECK_FEE", BigDecimal.ZERO);// 检查费
        map.put("DIAGNOSTIC_TEST_FEE", BigDecimal.ZERO);// 化验费
        map.put("MEDICAL_EXPENSE_FEE", BigDecimal.ZERO);// 治疗费
        map.put("OPERATION_FEE", BigDecimal.ZERO);// 手术费
        map.put("NURSING_FEE", BigDecimal.ZERO);// 护理费
        map.put("SANITARY_MATERIALS_FEE", BigDecimal.ZERO);// 卫生材料费
        map.put("WEST_MEDICINE", BigDecimal.ZERO);// 西药费
        map.put("CHINESE_MEDICINE_SLICES_FEE", BigDecimal.ZERO);// 中药饮片费
        map.put("CHINESE_MEDICINE_FEE", BigDecimal.ZERO);// 中成药费
        map.put("GENERAL_CONSULTATION_FEE", BigDecimal.ZERO);// 一般诊疗费
        map.put("REGISTRATION_FEE", BigDecimal.ZERO);// 挂号费
        map.put("OTHER_FEE", BigDecimal.ZERO);// 其他费用
        map.put("SUM", BigDecimal.ZERO);// 合计费用
        map.put("ybCashSum", BigDecimal.ZERO);// 医保现金
        map.put("selfCashSum", BigDecimal.ZERO);// 自费现金
        map.put("selfReg", 0);
        map.put("ybReg", 0);

        map.put("cashSum", BigDecimal.ZERO);// 现金支付
        map.put("rmbCashSum", BigDecimal.ZERO);// 现金支付
        map.put("vxCashSum", BigDecimal.ZERO);// 现金支付（）
        map.put("aliCashSum", BigDecimal.ZERO);// 现金支付（）
        map.put("uniCashSum", BigDecimal.ZERO);// 现金支付（）
        map.put("tcSum", BigDecimal.ZERO);// 基本统筹
        map.put("zhSum", BigDecimal.ZERO);// 账户支付
        map.put("fundSum", BigDecimal.ZERO);// 基金支付总额

        return map;
    }

    /**
     *
     * @param paymentId
     * @return
     */
    @Override
    public Map getMedicalExpenseCoverageSummary(Long paymentId) {
        return null;
    }

    @Override
    public Map getChargeItemByOrg(ChargeSummaryDto chargeSummaryDto) {
        Map<String, Object> map = new HashMap<>();

        // SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
        Date startDate = DateUtils.parseDate(chargeSummaryDto.getStartTime());
        Date endDate = DateUtils.parseDate(chargeSummaryDto.getEndTime());

        // 查询所有的支付
        LambdaQueryWrapper<PaymentReconciliation> queryWrapper = new LambdaQueryWrapper<PaymentReconciliation>()
            .between(PaymentReconciliation::getBillDate, startDate, endDate)
            .eq(PaymentReconciliation::getDeleteFlag, DelFlag.NO.getCode())
            .in(PaymentReconciliation::getStatusEnum, PaymentStatus.SUCCESS.getValue(),
                PaymentStatus.REFUND_ALL.getValue())
            .eq(PaymentReconciliation::getKindEnum, PaymentKind.OUTPATIENT_CLINIC.getValue());

        List<PaymentReconciliation> paymentReconciliationList = paymentReconciliationService.list(queryWrapper);
        if (paymentReconciliationList.isEmpty()) {
            return null;
        }

        List<Long> chargeItemIds = paymentReconciliationList.stream().map(PaymentReconciliation::getChargeItemIds) // 获取逗号分隔的字符串字段
            .flatMap(str -> Arrays.stream(str.split(","))) // 拆分字符串并扁平化
            .map(String::trim) // 去除前后空格
            .filter(s -> !s.isEmpty()) // 过滤空字符串
            .map(Long::valueOf) // 转换为Long
            .collect(Collectors.toList());

        List<ChargeItemExtendInfoDto> ChargeItemExtendInfoDtoList =
            chargeBillMapper.selectChargeItemExtendInfoList(chargeItemIds, chargeSummaryDto.getOrgIdList());

        Map<Long, List<ChargeItemExtendInfoDto>> chargeItemExtendInfoDtoListGroupByOrgIdMap =
            ChargeItemExtendInfoDtoList.stream().collect(Collectors.groupingBy(ChargeItemExtendInfoDto::getOrgId));
        LambdaQueryWrapper<Organization> organizationLambdaQueryWrapper =
            new LambdaQueryWrapper<Organization>().eq(Organization::getTypeEnum, OrganizationType.DEPARTMENT.getValue())
                .eq(Organization::getDeleteFlag, DeleteFlag.NOT_DELETED.getCode())
                .orderByDesc(Organization::getDisplayOrder);
        if (chargeSummaryDto.getOrgIdList() != null && !chargeSummaryDto.getOrgIdList().isEmpty()) {
            organizationLambdaQueryWrapper.in(Organization::getId, chargeSummaryDto.getOrgIdList());
        }
        List<Organization> organizationList = iOrganizationService.list(organizationLambdaQueryWrapper);
        if (organizationList.isEmpty()) {
            throw new ServiceException("未查询到科室信息");
        }
        List<OrgIncomeDto> orgIncomeList = new ArrayList();
        OrgIncomeDto orgIncomeDto;
        for (Organization organization : organizationList) {
            orgIncomeDto = new OrgIncomeDto();
            orgIncomeDto.setOrgName(organization.getName());
            List<ChargeItemExtendInfoDto> chargeItemExtendInfoDtos =
                chargeItemExtendInfoDtoListGroupByOrgIdMap.get(organization.getId());
            if (chargeItemExtendInfoDtos == null) {
                orgIncomeList.add(orgIncomeDto);
                continue;
            }
            for (ChargeItemExtendInfoDto chargeItemExtendInfoDto : chargeItemExtendInfoDtos) {
                // 挂号费单独 未计入应收
                switch (YbMedChrgItmType.getByValue(chargeItemExtendInfoDto.getYbType())) {
                    case WEST_MEDICINE:
                    case CHINESE_MEDICINE_SLICES_FEE:
                    case CHINESE_MEDICINE_FEE:
                        orgIncomeDto.setAmount(orgIncomeDto.getAmount().add(chargeItemExtendInfoDto.getTotalPrice()));
                        orgIncomeDto.setMedFee(orgIncomeDto.getMedFee().add(chargeItemExtendInfoDto.getTotalPrice()));
                        break;
                    case REGISTRATION_FEE:
                        orgIncomeDto.setAmount(orgIncomeDto.getAmount().add(chargeItemExtendInfoDto.getTotalPrice()));
                        orgIncomeDto.setPersonCnt(orgIncomeDto.getPersonCnt() + 1);
                        orgIncomeDto.setRegistrationFee(
                            orgIncomeDto.getRegistrationFee().add(chargeItemExtendInfoDto.getTotalPrice()));
                        break;
                    case SANITARY_MATERIALS_FEE:
                        orgIncomeDto.setAmount(orgIncomeDto.getAmount().add(chargeItemExtendInfoDto.getTotalPrice()));
                        orgIncomeDto
                            .setDeviceFee(orgIncomeDto.getDeviceFee().add(chargeItemExtendInfoDto.getTotalPrice()));
                        break;
                    default:
                        orgIncomeDto.setAmount(orgIncomeDto.getAmount().add(chargeItemExtendInfoDto.getTotalPrice()));
                        orgIncomeDto
                            .setServiceFee(orgIncomeDto.getServiceFee().add(chargeItemExtendInfoDto.getTotalPrice()));
                }
            }

            orgIncomeList.add(orgIncomeDto);
        }
        // 住院部分数据tbd

        map.put("clinic", orgIncomeList);

        return map;
    }

    /**
     * 小票信息（农大）
     *
     * @param paymentId 付款id
     * @return 结果
     */
    @Override
    public Map getReceiptDetailsND(Long paymentId) {

        Map<String, Object> map = new HashMap<>();
        // 查询
        PaymentReconciliation paymentReconciliation = paymentReconciliationService.getById(paymentId);
        if (paymentReconciliation == null) {
            throw new ServiceException("未查询到付款信息");
        }
        map.put("paymentId", paymentReconciliation.getPaymentNo());// 结算id
        map.put("paymentAmount", paymentReconciliation.getTenderedAmount());// 应收金额
        Practitioner practitioner = iPractitionerService.getById(paymentReconciliation.getEntererId());
        map.put("paymentEmployee", practitioner == null ? "" : practitioner.getName());// 收费员
        map.put("chargeTime", paymentReconciliation.getBillDate());// 收费时间
        Patient patient = iPatientService.getById(paymentReconciliation.getPatientId());
        if (patient == null) {
            throw new ServiceException("未查询到患者信息");
        }
        map.put("patientName", patient.getName());// 患者姓名

        map.put("sex", patient.getGenderEnum());// 性别
        map.put("idCardNo", patient.getIdCard());// 身份证号
        map.put("birthDay", patient.getBirthDate());// 出生日期

        List<PaymentRecDetail> paymentRecDetails = paymentRecDetailService
            .list(new LambdaQueryWrapper<PaymentRecDetail>().eq(PaymentRecDetail::getReconciliationId, paymentId));

        if (paymentRecDetails.isEmpty()) {
            throw new ServiceException("未查询到付款信息");
        }
        map.put("detail", paymentRecDetails);// 支付详细

        for (PaymentRecDetail paymentRecDetail : paymentRecDetails) {
            if (Objects.equals(paymentRecDetail.getPayEnum(), YbPayment.SELF_YB_ZH_PAY.getValue())) {
                map.put("ybAccountPay", paymentRecDetail.getAmount());// 医保账户支付
            }
            if (Objects.equals(paymentRecDetail.getPayEnum(), YbPayment.BALC.getValue())) {
                map.put("ybAccountBalc", paymentRecDetail.getAmount());// 医保账户余额（现）
            }
            if (Objects.equals(paymentRecDetail.getPayEnum(), YbPayment.YB_FUND_PAY.getValue())) {
                map.put("ybFundPay", paymentRecDetail.getAmount());// 基金支付总额
            }
            if (Objects.equals(paymentRecDetail.getPayEnum(), YbPayment.YB_TC_FUND_AMOUNT.getValue())) {
                map.put("ybTcPay", paymentRecDetail.getAmount());// 统筹支付金额
            }
            if (Objects.equals(paymentRecDetail.getPayEnum(), YbPayment.YB_BC_GWY_BZ_VALUE.getValue())) {
                map.put("ybGWYPay", paymentRecDetail.getAmount());// 公务员补助
            }
            if (Objects.equals(paymentRecDetail.getPayEnum(), YbPayment.OTHER_PAY.getValue())) {
                map.put("ybOtherPay", paymentRecDetail.getAmount());// 其他支付
            }
            // 下面两个大额理赔有哪个用哪个，无所谓的
            if (Objects.equals(paymentRecDetail.getPayEnum(), YbPayment.YB_BC_DE_BZ_VALUE.getValue())) {
                map.put("ybDELPPay", paymentRecDetail.getAmount());// 大额理赔（常规）
            }
            if (Objects.equals(paymentRecDetail.getPayEnum(), YbPayment.YB_BC_ZG_DE_BZ_VALUE.getValue())) {
                map.put("ybDELPPay", paymentRecDetail.getAmount());// 大额理赔(企业)
            }
            if (Objects.equals(paymentRecDetail.getPayEnum(), YbPayment.E_WALLET.getValue())) {
                map.put("ybWallet", paymentRecDetail.getAmount());// 电子钱包
            }
            if (Objects.equals(paymentRecDetail.getPayEnum(), YbPayment.SUPPLEMENTARY_INSURANCE.getValue())) {
                map.put("ybWallet", paymentRecDetail.getAmount());// 居民大病报销
            }
            if (Objects.equals(paymentRecDetail.getPayEnum(), YbPayment.SELF_CASH_VALUE.getValue())) {
                map.put("cash", paymentRecDetail.getAmount());// 现金
            }
            if (Objects.equals(paymentRecDetail.getPayEnum(), YbPayment.SELF_CASH_VX_VALUE.getValue())) {
                map.put("wxCash", paymentRecDetail.getAmount());// 现金（微信）
            }
            if (Objects.equals(paymentRecDetail.getPayEnum(), YbPayment.SELF_CASH_ALI_VALUE.getValue())) {
                map.put("aliCash", paymentRecDetail.getAmount());// 现金（支付宝）
            }
        }

        Invoice invoice = iInvoiceService.getOne(new LambdaQueryWrapper<Invoice>()
            .eq(Invoice::getReconciliationId, paymentId).eq(Invoice::getStatusEnum, InvoiceStatus.ISSUED.getValue())
            .orderByDesc(Invoice::getCreateTime).last(YbCommonConstants.sqlConst.LIMIT1));
        if (invoice != null) {
            map.put("invoiceNo", invoice.getBillNo());// 支付详细
            map.put("pictureUrl", invoice.getPictureUrl());// 图片
        }

        List<Long> chargeItemIds =
            Arrays.stream(paymentReconciliation.getChargeItemIds().split(",")).map(Long::parseLong) // 将字符串转换为 Long
                .collect(Collectors.toList());
        List<ChargeItemBaseInfoDto> chargeItemBaseInfoByIds =
            chargeItemService.getChargeItemBaseInfoByIds(chargeItemIds);

        for (ChargeItemBaseInfoDto chargeItemBaseInfoById : chargeItemBaseInfoByIds) {
            if (chargeItemBaseInfoById.getDeptName() == null) {
                throw new ServiceException("收费项" + chargeItemBaseInfoById.getName() + "无开单科室");
            }
            if (chargeItemBaseInfoById.getTypeCode() == null) {
                throw new ServiceException("收费项" + chargeItemBaseInfoById.getName() + "无财务分类");
            }
            if (!CommonConstants.BusinessName.DEFAULT_CONTRACT_NO.equals(chargeItemBaseInfoById.getContractNo())) {
                Object o = map.get(chargeItemBaseInfoById.getContractNo() + "-" + chargeItemBaseInfoById.getTypeCode());
                if (o == null) {
                    map.put(chargeItemBaseInfoById.getContractNo() + "-" + chargeItemBaseInfoById.getTypeCode(),
                        chargeItemBaseInfoById.getTotalPrice());
                } else {
                    BigDecimal bigDecimal = new BigDecimal(String.valueOf(o));
                    bigDecimal = bigDecimal.add(chargeItemBaseInfoById.getTotalPrice());
                    map.put(chargeItemBaseInfoById.getContractNo() + "-" + chargeItemBaseInfoById.getTypeCode(),
                        bigDecimal);
                }
            } else {
                // 根据科室的分类来
                Object o = map.get(chargeItemBaseInfoById.getDeptName() + "-" + chargeItemBaseInfoById.getTypeCode());
                if (o == null) {
                    map.put(chargeItemBaseInfoById.getDeptName() + "-" + chargeItemBaseInfoById.getTypeCode(),
                        chargeItemBaseInfoById.getTotalPrice());
                } else {
                    BigDecimal bigDecimal = new BigDecimal(String.valueOf(o));
                    bigDecimal = bigDecimal.add(chargeItemBaseInfoById.getTotalPrice());
                    map.put(chargeItemBaseInfoById.getDeptName() + "-" + chargeItemBaseInfoById.getTypeCode(),
                        bigDecimal);
                }
            }
        }

        Encounter encounter = iEncounterService.getById(paymentReconciliation.getEncounterId());
        if (encounter == null) {
            throw new ServiceException("未查询到就诊信息");
        }
        map.put("classEnum", encounter.getYbClassEnum());// 门诊/住院
        map.put("regNo", encounter.getBusNo());// 门诊号

        InfoPerson perinfo = iPerinfoService.getOne(new LambdaQueryWrapper<InfoPerson>()
            .eq(InfoPerson::getCertno, patient.getIdCard()).eq(InfoPerson::getTenantId, patient.getTenantId())
            .orderByDesc(InfoPerson::getCreateTime).last(YbCommonConstants.sqlConst.LIMIT1));
        if (perinfo != null) {
            map.put("personType", perinfo.getInsutype());// 人员类别：职工医保，居民医保等；如果为空显示自费或其他
            map.put("insuplcAdmdvs", perinfo.getInsuplcAdmdvs());// 患者参保地区划
        }

        // 查询主诊断信息
        EncounterDiagnosis encounterDiagnosis = iEncounterDiagnosisService.getOne(
            new LambdaQueryWrapper<EncounterDiagnosis>().eq(EncounterDiagnosis::getEncounterId, encounter.getId())
                .eq(EncounterDiagnosis::getMaindiseFlag, Whether.YES.getValue())
                .eq(EncounterDiagnosis::getDeleteFlag, DelFlag.NO.getCode())
                .orderByDesc(EncounterDiagnosis::getDiagSrtNo).last(YbCommonConstants.sqlConst.LIMIT1));

        if (encounterDiagnosis != null) {
            Condition condition = iConditionService.getById(encounterDiagnosis.getConditionId());
            if (condition != null) {
                ConditionDefinition conditionDefinition =
                    iConditionDefinitionService.getOne(new LambdaQueryWrapper<ConditionDefinition>()
                        .eq(ConditionDefinition::getId, condition.getDefinitionId()));
                if (conditionDefinition != null) {
                    map.put("conditionDefinition", conditionDefinition.getName());// 诊断名
                }
            }
        }

        JSONObject optionJson = SecurityUtils.getLoginUser().getOptionJson();
        String fixmedinsName = optionJson.getString(CommonConstants.Option.FIXMEDINS_NAME);
        String fixmedinsCode = optionJson.getString(CommonConstants.Option.FIXMEDINS_CODE);

        map.put("fixmedinsName", fixmedinsName);// 医院名称
        map.put("fixmedinsCode", fixmedinsCode);// 医院编号

        return map;
    }
}
