package cn.superdesk.uniorder.controller.accounting.customer;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.superdesk.uniorder.common.constants.ResponseMsgConstants;
import cn.superdesk.uniorder.common.enums.accounting.AccountingOrderDimCreateByEnum;
import cn.superdesk.uniorder.common.enums.common.CommonAccountingLockingEnum;
import cn.superdesk.uniorder.common.enums.common.CommonAccountingStateEnum;
import cn.superdesk.uniorder.common.enums.common.CommonOrderCompletStateEnum;
import cn.superdesk.uniorder.common.enums.common.CommonSourceFromEnum;
import cn.superdesk.uniorder.common.exception.utils.ExceptionUtils;
import cn.superdesk.uniorder.common.lamda.AnLamdaUtils;
import cn.superdesk.uniorder.common.rest.response.R;
import cn.superdesk.uniorder.common.rest.response.ResponseResultOuterUtils;
import cn.superdesk.uniorder.common.security.crypt.SuperdeskUniorderRsaUtils;
import cn.superdesk.uniorder.controller.base.BaseController;
import cn.superdesk.uniorder.dao.entity.accounting.score.customer.AccountingScoreCustomer;
import cn.superdesk.uniorder.dto._variable.AccountingScoreCustomerVariable;
import cn.superdesk.uniorder.dto.param.accounting.score.customer.AccountingOrderScoreCustomerCreateParam;
import cn.superdesk.uniorder.dto.param.accounting.score.customer.AccountingOrderScoreCustomerCreateSelectedCreditParam;
import cn.superdesk.uniorder.dto.param.accounting.score.customer.AccountingOrderScoreCustomerNotYetDimCreditScene2QueryCriteria;
import cn.superdesk.uniorder.dto.vo.accounting.score.customer.AccountingOrderScoreCustomerOpCreatePreviewReport;
import cn.superdesk.uniorder.dto.vo.accounting.score.customer.AccountingOrderScoreCustomerOpCreatePreviewStruct;
import cn.superdesk.uniorder.dto.vo.invoice.customer.InvoiceApplyDetailDimCreditItemVo;
import cn.superdesk.uniorder.dubbo.consumer._common.ProviderEnvConstantDubboCustomerService;
import cn.superdesk.uniorder.dubbo.consumer.accounting.customer.AccountingScoreCustomerDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.order.base.UnifiedOrderCreditDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.order.base.UnifiedOrderDubboConsumerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @Description: Java类作用描述
 * @Author: linjinyu
 * @CreateDate: 2022/6/6 11:40 上午
 * @UpdateUser: linjinyu
 * @UpdateDate: 2022/6/6 11:40 上午
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Api(value = "积分结算-创建对账单", tags = {"积分结算-创建对账单"})
@Slf4j
@RestController
@RequestMapping("/accounting/score/customer/opCreate")
public class ScoreCustomerOpCreateDimCreditController extends BaseController {

    @Autowired
    private UnifiedOrderDubboConsumerService       unifiedOrderDubboConsumerService;
    @Autowired
    private UnifiedOrderCreditDubboConsumerService unifiedOrderCreditDubboConsumerService;

    @Autowired
    private AccountingScoreCustomerDubboConsumerService accountingScoreCustomerDubboConsumerService;

    @Autowired
    private ProviderEnvConstantDubboCustomerService providerEnvConstantDubboCustomerService;

    /**************************************** op创建对账单 start ****************************************/



    /**
     * 积分结算(相当于客户结算)
     * | ----> 积分结算-未结算商品 | 此页面是以商品流水的维度去展示的 opt 搜索 下单时间 只能以订单维度 最终
     * | ----> | ----> 创建对账单 预览
     * <p>
     * goodsdetail
     *
     * @return
     */
    @ApiOperation(value = "积分结算-未对账流水-op创建对账单-预览", tags = "v2.0,v2.1,v2.2,v2.3,v2.5")
    @RequestMapping(value = "/createAccountingPreview", method = RequestMethod.POST)
    @ResponseBody
    public R<AccountingOrderScoreCustomerOpCreatePreviewStruct> createAccountingPreview(
            @RequestBody AccountingOrderScoreCustomerNotYetDimCreditScene2QueryCriteria queryCriteria) {


        if (StrUtil.isBlank(queryCriteria.getBatchs())) {
            return ResponseResultOuterUtils.createErrorResult("500", "参数[积分批次]不能为空或纯微信支付流水的创建对账单");
        }

        // 固化
        queryCriteria.setAutoComplete(AccountingOrderDimCreateByEnum.订单.getKey());
        queryCriteria.setAccountingStateCustomer(CommonAccountingStateEnum.未对账.getKey());

        log.info("createAccountingPreview params {}", JSONUtil.toJsonStr(queryCriteria));

        R<AccountingOrderScoreCustomerOpCreatePreviewStruct> response = new R<>();


        try {

            List<AccountingOrderScoreCustomerCreateSelectedCreditParam> selectCredits = queryCriteria.getCreditSelected();

            if (CollUtil.isEmpty(selectCredits)) {
                return ResponseResultOuterUtils.createErrorResult("500", "暂无对账数据,不允许创建对账单");
            }

            /**************************************** 取出选中未对账流水 start ****************************************/

            // mark by linjinyu at 20220413
            // 记录一下这段代码的问题，主要是页面多开时，状态有可能会变更

            // AccountingScoreCustomerNotYetDimCreditQueryCriteria.builder().idsCredit(idsCredit).build()
            // AccountingScoreCustomerNotYetDimCreditQueryCriteria.builder().creditSelected(selectCredits).build() 同理
//			List<Long> selectCreditIds = selectCredits.stream()
//					.map(s -> s.getUnifiedOrderCreditId())
//					.collect(Collectors.toList());

            /**************************************** 取出选中未对账流水   end ****************************************/


            /**************************************** 得出未对账流水(不包含已对账流水) start ****************************************/

            // 20220413 因为需求变更 加入 积分批次限定
            List<InvoiceApplyDetailDimCreditItemVo> resultListCredit = unifiedOrderDubboConsumerService.getScoreOrderReconciliationNotYetScene2(
                    queryCriteria,
                    getToken()
            );

            Map<String, List<InvoiceApplyDetailDimCreditItemVo>> batchs2InvoiceApplyDetailDimCreditItemVoMap = resultListCredit.stream()
                    .collect(Collectors.groupingBy(InvoiceApplyDetailDimCreditItemVo::getBatchs, Collectors.toList()));

            List<InvoiceApplyDetailDimCreditItemVo> appointBatchsListCredit = batchs2InvoiceApplyDetailDimCreditItemVoMap.get(queryCriteria.getBatchs());


            /**************************************** 得出未对账流水(不包含已对账流水) start ****************************************/


            /**************************************** 之前逻辑 start ****************************************/
            // 检查
            // 2. 对账单的订单数(流水条数)≥1,若为0不允许创建,1.5s提示"暂无对账数据,不允许创建对账单";
            // 1. 对账单的企业不为空,否则不允许创建,1.5s提示"企业信息缺失,请检查或重新创建";
            // 3. 无需检查积分类型是否为同一类型;

//            【【20220411调整需求】积分结算-创建对账单以及合并规则调整需求。】
//            https://www.tapd.cn/33003868/prong/stories/view/1133003868001004207


            /**
             * 数据变动
             */
            response = createAccountingCheck(appointBatchsListCredit);

            if (!response.isSuccess()) {
                return response;
            }

            /****************************************** 检查问题 start ******************************************/

            AccountingOrderScoreCustomerOpCreatePreviewReport report = new AccountingOrderScoreCustomerOpCreatePreviewReport();

            if (CollUtil.isEmpty(appointBatchsListCredit)) {
                report.setDataChangeReport(StrUtil.format("数据变动 input {} output {};", selectCredits.size(), appointBatchsListCredit.size()));
            } else if (selectCredits.size() != appointBatchsListCredit.size()) {
                report.setDataChangeReport(StrUtil.format("数据变动 input {} output {};", selectCredits.size(), appointBatchsListCredit.size()));
            }

            List<String> orderSnsDataChange              = createAccountingCheckByDataChange(appointBatchsListCredit, selectCredits);
            List<String> orderSnsCompletStateEq2         = createAccountingCheckByCompletStateEq2(appointBatchsListCredit);
            List<String> orderSnsOrderLockingSupplierEq1 = createAccountingCheckByOrderLockingSupplierEq1(appointBatchsListCredit);

            report.setOrderSnsDataChange(orderSnsDataChange);
            report.setOrderSnsCompletStateEq2(orderSnsCompletStateEq2);
            report.setOrderSnsOrderLockingSupplierEq1(orderSnsOrderLockingSupplierEq1);

            /****************************************** 检查问题   end ******************************************/

            // additionalInfoGetScoreOrderReconciliationNotYet
//			for (InvoiceApplyDetailDimCreditItemVo vo : appointBatchsListCredit) {
//
//				vo.setAccountingStateCustomerName(CommonAccountingStateEnum.getDesc(vo.getAccountingStateCustomer()));
//
//				vo.setInvoiceApplyStatusName(UnifiedOrderCreditInvoiceApplyStatusEnum.getDesc(vo.getInvoiceApplyStatus()));
//				vo.setInvoiceMakeStatusName(UnifiedOrderCreditInvoiceMakeStatusEnum.getDesc(vo.getInvoiceMakeStatus()));
//				vo.setBackStatusName(UnifiedOrderCreditBackStatusEnum.getDesc(vo.getBackStatus()));
//			}

            List<InvoiceApplyDetailDimCreditItemVo> composeListCredit = new ArrayList<>();
            composeListCredit.addAll(appointBatchsListCredit);

            if (CollUtil.isNotEmpty(batchs2InvoiceApplyDetailDimCreditItemVoMap.get("wechat"))) {
                composeListCredit.addAll(batchs2InvoiceApplyDetailDimCreditItemVoMap.get("wechat"));
            }


            List<InvoiceApplyDetailDimCreditItemVo> composeListCreditSortByOrderCreateTimeOrderSn = composeListCredit.stream()
                    .sorted(
                            Comparator
                                    .comparing(InvoiceApplyDetailDimCreditItemVo::getCreateTime)
                                    .thenComparing(InvoiceApplyDetailDimCreditItemVo::getOrderSn)
                    )
                    .collect(Collectors.toList());


            response.setData(AccountingOrderScoreCustomerOpCreatePreviewStruct.builder()
                    .list(composeListCreditSortByOrderCreateTimeOrderSn)
                    .groupByBatchs(batchs2InvoiceApplyDetailDimCreditItemVoMap)
                    .report(report)
                    .build());


        } catch (Exception e) {

            response.setCode(String.valueOf(e.hashCode()));
            response.setSuccess(false);
            response.setMessage("系统查找失败！");

            log.error(ExceptionUtils.getMessage(e));
            e.printStackTrace();

        }

        return response;
    }

    private List<String> createAccountingCheckByDataChange(
            List<InvoiceApplyDetailDimCreditItemVo> resultListCredit,
            List<AccountingOrderScoreCustomerCreateSelectedCreditParam> selectCredits) {

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

        if (CollUtil.isEmpty(resultListCredit)
                && CollUtil.isEmpty(selectCredits)
                && selectCredits.size() != resultListCredit.size()) {

            List<Long> selectCreditIds = selectCredits.stream()
                    .map(s -> s.getUnifiedOrderCreditId())
                    .collect(Collectors.toList());
            List<Long> resultCreditIds = resultListCredit.stream()
                    .map(s -> s.getUnifiedOrderCreditId())
                    .collect(Collectors.toList());
            // 差集
            List<Long> reduceCreditIds = selectCreditIds
                    .stream()
                    .filter(i -> !resultCreditIds.contains(i))
                    .collect(Collectors.toList());

            orderSns = unifiedOrderCreditDubboConsumerService.queryOrderSnsBySelectCreditIds(reduceCreditIds);


        }

        return orderSns;
    }

    /**
     * 统一订单的 只分三种 1-已完成 ; 2-未完成 ; 3-已取消
     *
     * @param resultListCredit
     * @return±
     */
    private List<String> createAccountingCheckByCompletStateEq2(List<InvoiceApplyDetailDimCreditItemVo> resultListCredit) {

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

        List<Predicate<InvoiceApplyDetailDimCreditItemVo>> predicatesScoreOrderReconciliationNotYetVoByCompletStateEq2 = new ArrayList<>();
        predicatesScoreOrderReconciliationNotYetVoByCompletStateEq2.add(
                r -> r.getCompletState() != null
                        && r.getCompletState().equals(CommonOrderCompletStateEnum.未完成.getKey())
        );

        List<InvoiceApplyDetailDimCreditItemVo> resultListCreditByCompletStateEq2 = AnLamdaUtils.filters(resultListCredit, predicatesScoreOrderReconciliationNotYetVoByCompletStateEq2);

        if (CollUtil.isNotEmpty(resultListCreditByCompletStateEq2)) {
            orderSns = resultListCreditByCompletStateEq2
                    .stream()
                    .filter(AnLamdaUtils.distinctByKey(o -> o.getOrderSn()))
                    .map(o -> o.getOrderSn())
                    .collect(Collectors.toList());
        }

        return orderSns;
    }

    /**
     * 当前是积分结算-未对账
     * 用的是供应商结算里边的锁单逻辑
     * 供应商结算-订单锁定:0-正常;1-销定;
     *
     * @param resultListCredit
     * @return
     */
    private List<String> createAccountingCheckByOrderLockingSupplierEq1(List<InvoiceApplyDetailDimCreditItemVo> resultListCredit) {

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

        List<Predicate<InvoiceApplyDetailDimCreditItemVo>> predicatesScoreOrderReconciliationNotYetVoByOrderLockingSupplierEq1 = new ArrayList<>();
        predicatesScoreOrderReconciliationNotYetVoByOrderLockingSupplierEq1.add(
//                【【结算中心-测试环境】积分结算-未对账流水-ME20220331095521666157--创建对账单-售后申请订单中无提示信息】https://www.tapd.cn/33003868/bugtrace/bugs/view?bug_id=1133003868001004559
                // 看了一下数据，锁定的为订单商品
//                r -> r.getOrderLockingSupplier() != null
//                        && r.getOrderLockingSupplier().compareTo(CommonAccountingLockingEnum.锁定.getKey()) == 0
                r -> r.getGoodsLockingSupplier() != null
                        && r.getGoodsLockingSupplier().compareTo(CommonAccountingLockingEnum.锁定.getKey()) == 0
        );

        List<InvoiceApplyDetailDimCreditItemVo> resultListCreditByOrderLockingSupplierEq1 = AnLamdaUtils.filters(resultListCredit, predicatesScoreOrderReconciliationNotYetVoByOrderLockingSupplierEq1);

        if (CollUtil.isNotEmpty(resultListCreditByOrderLockingSupplierEq1)) {
            orderSns = resultListCreditByOrderLockingSupplierEq1.stream().filter(AnLamdaUtils.distinctByKey(o -> o.getOrderSn())).map(o -> o.getOrderSn()).collect(Collectors.toList());
        }

        return orderSns;
    }

    /**
     * 数据变动
     *
     * @param resultListCredit
     * @return
     */
    private R createAccountingCheck(List<InvoiceApplyDetailDimCreditItemVo> resultListCredit) {

        StringBuffer report          = new StringBuffer();
        StringBuffer reportBenchmark = new StringBuffer();

//		log.info("createAccountingCheck \n{}", JSONUtil.toJsonStr(resultListCredit));

        // TODO 检查这些流水是不是同一个
        // 积分类型
        // 积分批次
        // 企业

        // 基准
        InvoiceApplyDetailDimCreditItemVo benchmark = null;


        for (InvoiceApplyDetailDimCreditItemVo iterator : resultListCredit) {

            /**************************************** 20220217 start ****************************************/

            // 积分结算2.1 后微信支付的需要纳入对账单 mark by linjinyu at 20220217
            // 【对映文档-2. 积分结算-2.3 未对账流水-初步整理-20220215】 https://www.tapd.cn/33003868/prong/stories/view/1133003868001003945

            /**************************************** 20220411 start ****************************************/

//                【【20220411 调整需求】积分结算-创建对账单以及合并规则调整需求。】
//                https://www.tapd.cn/33003868/prong/stories/view/1133003868001004207
            // ④当前所勾选的未对账流水数据必须为同一积分批次（wechat微信支付积分批次除外），若当前所勾选的未对账流水数据存在不同的积分批次，不允许创建对账单，1.5s提示“请选择相同积分批次创建”；【20220411调整】

            if ("wechat".equals(iterator.getBatchs())) {
                continue;
            }

            /**************************************** 20220411   end ****************************************/

            /**************************************** 20220217   end ****************************************/


//			log.info(JSONUtil.toJsonStr(iterator));

            // 排除 wechat ,当不是 wechat 时 ---- 作废 ---- mark by linjinyu at 20220217
            // 设定基准
            if (null == benchmark) {

                benchmark = iterator;

                reportBenchmark.append(StrUtil.format("基准为 {}\n", JSONUtil.toJsonStr(benchmark)));

            } else {

//				mark by linjinyu at 20220217【对映文档-2. 积分结算-2.3 未对账流水-初步整理-20220215】 https://www.tapd.cn/33003868/prong/stories/view/1133003868001003945
//				if (!iterator.getCreditName().equals(benchmark.getCreditName())) {
//					return ResponseResultOuterUtils.createErrorResult("500", "积分类型 不唯一,请重新生成！");
//				}

                /**************************************** 20200729 start ****************************************/
                // 20200729 注释 大概就是侨城汇生产上线后发现要允许多积分批次去创建 mark by linjinyu
                // 补充 因为 一个订单是可以用多种 积分批次来抵购的 所以这个不能

                /**************************************** 20220411 start ****************************************/

//                【【20220411 调整需求】积分结算-创建对账单以及合并规则调整需求。】
//                https://www.tapd.cn/33003868/prong/stories/view/1133003868001004207
                // ④当前所勾选的未对账流水数据必须为同一积分批次（wechat微信支付积分批次除外），若当前所勾选的未对账流水数据存在不同的积分批次，不允许创建对账单，1.5s提示“请选择相同积分批次创建”；【20220411调整】
                if (!iterator.getBatchs().equals(benchmark.getBatchs())) {
//                    return ResponseResultOuterUtils.createErrorResult("500", "请选择相同积分批次创建");

                    report.append(StrUtil.format("请选择相同积分批次创建 {}\n", JSONUtil.toJsonStr(iterator)));
                }
                if (iterator.getPurchaseVirtId() == null) {
//                    return ResponseResultOuterUtils.createErrorResult("500", "企业信息缺失,请检查或重新创建");

                    report.append(StrUtil.format("企业信息缺失,请检查或重新创建 {}\n", JSONUtil.toJsonStr(iterator)));
                }
                if (!iterator.getPurchaseVirtId().equals(benchmark.getPurchaseVirtId())) {
//                    return ResponseResultOuterUtils.createErrorResult("500", "企业信息不唯一,请检查或重新创建！");

                    report.append(StrUtil.format("请选择相同企业创建 {}\n", JSONUtil.toJsonStr(iterator)));
                }
            }
        }

        if (StrUtil.isNotBlank(report.toString())) {
            return ResponseResultOuterUtils.createErrorResult("500", StrUtil.format("\n{}\n{}", reportBenchmark.toString(), report.toString()));
        } else {
            return ResponseResultOuterUtils.createSuccesResult();
        }


    }


    /**
     * 积分结算-未对账流水-op创建对账单
     * v2.0
     * v2.1
     * v2.2
     * v2.3
     * v2.5
     *
     * @param accountingScoreCustomerCreateParam
     * @return
     * @RequestBody
     * @ModelAttribute
     * @Valid
     */
    @ApiOperation(value = "积分结算-未对账流水-op创建对账单", tags = "v2.0,v2.1,v2.2,v2.3,v2.5")
    @RequestMapping(value = "/createAccounting", method = RequestMethod.POST)
    @ResponseBody
    public R<AccountingScoreCustomer> createAccounting(@RequestBody AccountingOrderScoreCustomerCreateParam accountingScoreCustomerCreateParam) {


        accountingScoreCustomerCreateParam.setSourceFrom(CommonSourceFromEnum.结算中心.getSourceFromCode());

        R<AccountingScoreCustomer> response = new R<>();

        if (StrUtil.isBlank(accountingScoreCustomerCreateParam.getBatchs())) {
            return ResponseResultOuterUtils.createErrorResult("500", "参数[积分批次]不能为空或纯微信支付流水的创建对账单");
        }

        try {

            List<AccountingOrderScoreCustomerCreateSelectedCreditParam> selectCredits = accountingScoreCustomerCreateParam.getCreditSelected();

            if (CollUtil.isEmpty(selectCredits)) {

                return ResponseResultOuterUtils.createErrorResult("500", "至少选择一条数据");
            }

            // 取出选中未对账流水
            // AccountingScoreCustomerNotYetDimCreditQueryCriteria.builder().idsCredit(idsCredit).build()
            // AccountingScoreCustomerNotYetDimCreditQueryCriteria.builder().creditSelected(selectCredits).build() 同理
//			List<Long> selectCreditIds = selectCredits.stream()
//					.map(s -> s.getUnifiedOrderCreditId())
//					.collect(Collectors.toList());
            // 得出未对账流水(不包含已对账流水)
            List<InvoiceApplyDetailDimCreditItemVo> resultListCredit = unifiedOrderDubboConsumerService.getScoreOrderReconciliationNotYetScene2(
                    AccountingOrderScoreCustomerNotYetDimCreditScene2QueryCriteria
                            .builder()
                            .creditSelected(selectCredits)
                            //【【结算中心-正式环境】积分结算-对账单-混合积分支付中A、B积分批次账单都会含有微信支付数据】
                            // https://www.tapd.cn/33003868/bugtrace/bugs/view?bug_id=1133003868001005008
                            // 结论~此处不能再自动补全-逻辑上是已经过滤已对账的wechat流水
                            .autoComplete(AccountingOrderDimCreateByEnum.不补.getKey())
//                            .accountingStateCustomer()
                            /**************************************** 20220413 start ****************************************/

                            // 【后端已处理-20220412-【20220411调整需求】积分结算-创建对账单以及合并规则调整需求。】
                            // https://www.tapd.cn/33003868/prong/stories/view/1133003868001004207
                            .batchs(accountingScoreCustomerCreateParam.getBatchs())

                            /**************************************** 20220413 start ****************************************/

                            .build(), getToken()
            );

            log.info("积分结算 创建对账单 op确定创建\n{}", JSONUtil.toJsonPrettyStr(resultListCredit));

            // 检查
            // 2. 对账单的订单数(流水条数)≥1,若为0不允许创建,1.5s提示"暂无对账数据,不允许创建对账单";
            // 1. 对账单的企业不为空,否则不允许创建,1.5s提示"企业信息缺失,请检查或重新创建";
            // 3. 无需检查积分类型是否为同一类型;
            response = createAccountingCheck(resultListCredit);

            if (!response.isSuccess()) {
                return response;
            }

            /****************************************** 检查问题 start ******************************************/

            AccountingOrderScoreCustomerOpCreatePreviewReport report = new AccountingOrderScoreCustomerOpCreatePreviewReport();

            if (CollUtil.isEmpty(resultListCredit)) {
                report.setDataChangeReport(StrUtil.format("数据变动 input {} output {};", selectCredits.size(), resultListCredit.size()));

                response.setSuccess(false);
                response.setMessage("异常 ERROR CODE 00001");
                return response;

            }

//            【【结算中心-正式环境】积分结算-未对账流水-ME20220415092041761444-创建对账单-多积分批次商品-无法创建对账单】https://www.tapd.cn/33003868/bugtrace/bugs/view?bug_id=1133003868001004980
//            else if (selectCredits.size() != resultListCredit.size()) {
//                report.setDataChangeReport(StrUtil.format("数据变动 input {} output {};", selectCredits.size(), resultListCredit.size()));
//
//                response.setSuccess(false);
//                response.setMessage("异常 ERROR CODE 00002");
//                return response;
//            }

            List<String> orderSnsDataChange              = createAccountingCheckByDataChange(resultListCredit, selectCredits);
            List<String> orderSnsCompletStateEq2         = createAccountingCheckByCompletStateEq2(resultListCredit);
            List<String> orderSnsOrderLockingSupplierEq1 = createAccountingCheckByOrderLockingSupplierEq1(resultListCredit);

            report.setOrderSnsDataChange(orderSnsDataChange);
            report.setOrderSnsCompletStateEq2(orderSnsCompletStateEq2);
            report.setOrderSnsOrderLockingSupplierEq1(orderSnsOrderLockingSupplierEq1);

            /**************************************** 20220606 start ****************************************/

            AccountingScoreCustomerVariable accountingScoreCustomerVariable = providerEnvConstantDubboCustomerService.getAccountingScoreCustomerVariable();

            // 不允许时判定
            if (Boolean.FALSE.compareTo(accountingScoreCustomerVariable.getOpCreateInsistOnAble()) == 0) {
                if (CollUtil.isNotEmpty(orderSnsCompletStateEq2) || CollUtil.isNotEmpty(orderSnsOrderLockingSupplierEq1)) {
                    return ResponseResultOuterUtils.createErrorResult("500", "对账单存在“未完成/售后中”的订单流水，不允许创建对账单");
                }
            }

            /**************************************** 20220606 start ****************************************/



            /****************************************** 检查问题   end ******************************************/

            if (CollUtil.isNotEmpty(orderSnsDataChange)) {
                return ResponseResultOuterUtils.createErrorResult("500", "存在数据变动,不允许创建对账单");
            }


            // 统计结算单 积分总额 TODO 逻辑变动 积分结算2.1 后不在这里算了
//			BigDecimal accountingAmount = resultListCredit.stream().map(a -> a.getBalance()).reduce(BigDecimal.ZERO, BigDecimal::add);
//			accountingScoreCustomerCreateParam.setAccountingAmount(accountingAmount);


            // TODO 积分结算2.1 关于对账单周期 三种方式
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            Date startDate = sdf.parse(accountingScoreCustomerCreateParam.getStartTime());
            Date endDate   = sdf.parse(accountingScoreCustomerCreateParam.getEndTime());


            // 创建对账单 - 积分结算
            AccountingScoreCustomer accountingScoreCustomer = accountingScoreCustomerDubboConsumerService.createScoreAccountingCustomer(getToken(),
                    /* 提交过来的流水 */ resultListCredit,
                    /* 提交过来的表单 */ accountingScoreCustomerCreateParam
            );

            if (accountingScoreCustomer.getId() > 0) {

                response.setSuccess(true);
                response.setData(accountingScoreCustomer);

                Map<String, Object> headMap = new HashMap<>();

                headMap.put("encrypt_id", SuperdeskUniorderRsaUtils.encode(accountingScoreCustomer.getId().toString()));

                response.setHeadData(headMap);

            } else {

                response.setSuccess(false);
                response.setMessage("创建 结算单 失败！");

            }

        } catch (Exception e) {

            response.setSuccess(false);
            response.setMessage(ResponseMsgConstants.ERROR_UNKNOW);

            log.error(ExceptionUtils.getMessage(e));
            e.printStackTrace();
        }

        return response;
    }


    /**************************************** op创建对账单 start ****************************************/
}
