package cn.superdesk.uniorder.service.order.base.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import cn.superdesk.uniorder.common.enums.accounting.AccountingOrderDimCreateByEnum;
import cn.superdesk.uniorder.common.enums.common.CommonAccountingStateEnum;
import cn.superdesk.uniorder.common.enums.common.CommonServiceNoEnum;
import cn.superdesk.uniorder.common.enums.login.SysLoginTypeEnum;
import cn.superdesk.uniorder.common.enums.order.UnifiedOrderCreditBackAccountStatusEnum;
import cn.superdesk.uniorder.common.enums.order.UnifiedOrderCreditInvoiceApplyStatusEnum;
import cn.superdesk.uniorder.common.enums.order.UnifiedOrderCreditInvoiceMakeStatusEnum;
import cn.superdesk.uniorder.common.numerical.AnCollectionUtils;
import cn.superdesk.uniorder.common.rest.response.R;
import cn.superdesk.uniorder.common.security.dto.LoginSysUser;
import cn.superdesk.uniorder.common.security.sensitive.DesensitizedUtils;
import cn.superdesk.uniorder.common.security.sensitive.constants.SensitiveRequireSwitchEnum;
import cn.superdesk.uniorder.dao.entity.base.UnifiedOrder;
import cn.superdesk.uniorder.dao.entity.base.UnifiedOrderReturn;
import cn.superdesk.uniorder.dao.entity.channel.UnifiedChannelProfitSync;
import cn.superdesk.uniorder.dao.entity.unified.UnifiedOrderProfit;
import cn.superdesk.uniorder.dao.mapper.base.*;
import cn.superdesk.uniorder.dao.mapper.channel.UnifiedChannelProfitSyncMapper;
import cn.superdesk.uniorder.dao.mapper.channel.UnifiedChannelProfitSyncMapperEx;
import cn.superdesk.uniorder.dao.mapper.unified.UnifiedOrderProfitMapper;
import cn.superdesk.uniorder.dao.mapper.unified.UnifiedOrderProfitMapperEx;
import cn.superdesk.uniorder.dto.param.accounting.score.customer.*;
import cn.superdesk.uniorder.dto.param.order.AutoCompleteUnifiedOrderCreditDimOrderGoodsStep01QueryCriteria;
import cn.superdesk.uniorder.dto.param.order.AutoCompleteUnifiedOrderCreditDimOrderGoodsStep02QueryCriteria;
import cn.superdesk.uniorder.dto.param.order.AutoCompleteUnifiedOrderCreditDimOrderStep01QueryCriteria;
import cn.superdesk.uniorder.dto.vo.invoice.customer.InvoiceApplyDetailDimCreditItemVo;
import cn.superdesk.uniorder.dto.vo.order.AutoCompleteUnifiedOrderCreditDimOrderGoodsStep01Vo;
import cn.superdesk.uniorder.dto.vo.order.AutoCompleteUnifiedOrderCreditDimOrderStep01Vo;
import cn.superdesk.uniorder.dto.vo.score.ScoreOrderReconciliationNotYetHeadVo;
import cn.superdesk.uniorder.service.invoice.customer.InvoiceApplyXGoodsService;
import cn.superdesk.uniorder.service.order.base.CommonOrderProcessService;
import cn.superdesk.uniorder.service.order.base.ScoreOrderService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: Java类作用描述
 * @Author: linjinyu
 * @CreateDate: 6/12/20 3:14 PM
 * @UpdateUser: linjinyu
 * @UpdateDate: 6/12/20 3:14 PM
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Slf4j
@Service
public class ScoreOrderServiceImpl implements ScoreOrderService {

    @Autowired
    private UnifiedOrderMapper                    unifiedOrderMapper;
    @Autowired
    private UnifiedOrderMapperEx                  unifiedOrderMapperEx;
    @Autowired
    private UnifiedOrderMapperExCustomerDimCredit unifiedOrderMapperExCustomerDimCredit;
    @Autowired
    private UnifiedOrderGoodsMapper               unifiedOrderGoodsMapper;
    @Autowired
    private UnifiedOrderGoodsMapperEx             unifiedOrderGoodsMapperEx;
    @Autowired
    private UnifiedOrderCreditMapper              unifiedOrderCreditMapper;

    @Autowired
    private CommonOrderProcessService commonOrderProcessService;

    /****************************************** 退单部分 ******************************************/
    @Autowired
    private UnifiedOrderReturnMapper        unifiedOrderReturnMapper;
    @Autowired
    private UnifiedOrderReturnMapperEx      unifiedOrderReturnMapperEx;
    @Autowired
    private UnifiedOrderReturnGoodsMapper   unifiedOrderReturnGoodsMapper;
    @Autowired
    private UnifiedOrderReturnGoodsMapperEx unifiedOrderReturnGoodsMapperEx;
    @Autowired
    private UnifiedOrderReturnCreditMapper  unifiedOrderReturnCreditMapper;
    /****************************************** 退单部分 ******************************************/


    /****************************************** 分润部分 ******************************************/
    @Autowired
    private UnifiedOrderProfitMapper         unifiedOrderProfitMapper;
    @Autowired
    private UnifiedOrderProfitMapperEx       unifiedOrderProfitMapperEx;
    @Autowired
    private UnifiedChannelProfitSyncMapper   unifiedChannelProfitSyncMapper;
    @Autowired
    private UnifiedChannelProfitSyncMapperEx unifiedChannelProfitSyncMapperEx;

    /****************************************** 分润部分 ******************************************/


    /****************************************  start ****************************************/

    @Autowired
    private InvoiceApplyXGoodsService invoiceApplyXGoodsService;


    @Deprecated
    @Override
    public int insertSelective(UnifiedOrder scoreOrder) {

        return 0;
    }

    @Deprecated
    @Override
    public int updateByPrimaryKeySelective(UnifiedOrder scoreOrder) {
        return 0;
    }

    @Override
    public void deleteObj(Long id) {

    }

    @Override
    public UnifiedOrder findById(Long id) {
        return null;
    }


    @Override
    public List<UnifiedOrder> findAll(Map<String, Object> queryMap) {
        return null;
    }

    @Override
    public PageInfo<UnifiedOrder> findByPaging(Map<String, Object> params, Integer pageNo, Integer pageSize) {
        return null;
    }

    public ScoreOrderReconciliationNotYetHeadVo getScoreOrderReconciliationNotYetHeadSum(AccountingOrderScoreCustomerNotYetDimCreditQueryCriteria queryCriteria, LoginSysUser loginSysUser) {
        return unifiedOrderMapperExCustomerDimCredit.getScoreOrderReconciliationNotYetHeadSum(queryCriteria);
    }

    @Override
    public R<List<InvoiceApplyDetailDimCreditItemVo>> getScoreOrderReconciliationNotYetByPageQuery(AccountingOrderScoreCustomerNotYetDimCreditQueryCriteria queryCriteria, LoginSysUser loginSysUser) {

        PageHelper.startPage(queryCriteria.getPageNumber(), queryCriteria.getPageSize());

        List<InvoiceApplyDetailDimCreditItemVo> scoreOrderReconciliationNotYetVoList = getScoreOrderReconciliationNotYet(queryCriteria, loginSysUser);

        PageInfo<InvoiceApplyDetailDimCreditItemVo> page = new PageInfo<InvoiceApplyDetailDimCreditItemVo>(scoreOrderReconciliationNotYetVoList);
        PageHelper.clearPage();

        return new R<List<InvoiceApplyDetailDimCreditItemVo>>(page.getPageNum(), page.getPageSize(), (int) page.getTotal(), scoreOrderReconciliationNotYetVoList);
    }


    /**
     * 场景1 作为未对账流水 订单流水管理
     *
     * @param queryCriteria
     * @param loginSysUser
     * @return
     */
    @Override
    public List<InvoiceApplyDetailDimCreditItemVo> getScoreOrderReconciliationNotYetScene1(
            AccountingOrderScoreCustomerNotYetDimCreditScene1QueryCriteria queryCriteria,
            LoginSysUser loginSysUser) {

        return getScoreOrderReconciliationNotYet(
                AccountingOrderScoreCustomerNotYetDimCreditQueryCriteria
                        .builder()
                        .startTime(queryCriteria.getStartTime())
                        .endTime(queryCriteria.getEndTime())
                        .orderSn(queryCriteria.getOrderSn())
                        .purchaseVirtId(queryCriteria.getPurchaseVirtId())
                        .purchaseVirtName(queryCriteria.getPurchaseVirtName())
                        .purchaseDepartmentName(queryCriteria.getPurchaseDepartmentName())
                        .purchaseUserId(queryCriteria.getPurchaseUserId())
                        .purchaseUserName(queryCriteria.getPurchaseUserName())
                        .purchasePhone(queryCriteria.getPurchasePhone())
                        .creditName(queryCriteria.getCreditName())
                        .payType(queryCriteria.getPayType())
                        .batchs(queryCriteria.getBatchs())
                        .accountingStateCustomer(queryCriteria.getAccountingStateCustomer())
                        .build(),
                loginSysUser
        );
    }

    /**
     * 场景2 作为创建对账单数据
     *
     * @param queryCriteria
     * @param loginSysUser
     * @return
     */
    @Override
    public List<InvoiceApplyDetailDimCreditItemVo> getScoreOrderReconciliationNotYetScene2(
            AccountingOrderScoreCustomerNotYetDimCreditScene2QueryCriteria queryCriteria,
            LoginSysUser loginSysUser) {

        // 证明场景2逻辑 getCreditSelected 不能为空 getAutoComplete 不能为空
        if (CollUtil.isEmpty(queryCriteria.getCreditSelected()) || ObjectUtil.isNull(queryCriteria.getAutoComplete())) {
            // 抛异常
            return null;
        }

        // TODO 有空再优化 mark by linjinyu at 20220225
        //	【后端已完成-20220222-对映文档-2. 积分结算-2.3 未对账流水-已整理-20220222】 https://www.tapd.cn/33003868/prong/stories/view/1133003868001003945
        //	①将当前所勾选的未对账流水数据及其关联的未对账流水数据一并自动带入到"创建对账单"页面:
        //	·勾选"正单/负单"未对账流水所关联当前未对账流水同订单同商品的"负单/正单"一并带入,同一条流水id去重;
        //	·勾选"同一订单流水组合支付其中一条"未对账流水所关联当前未对账流水"同订单同商品其他支付流水 "一并带入,同一条流水id去重;
        //	·不再过滤当前所勾选积分类型为`微信支付`的未对账流水;
        //	②注:所有关联流水带入时必须为"未对账"状态,已对账和存在数据变动的流水不关联带入,自动过滤掉;


        /****************************************** 场景2 start ******************************************/

        // 自动补全 最小单位为 订单商品
        switch (AccountingOrderDimCreateByEnum.get(queryCriteria.getAutoComplete())) {
            case 订单:

                // TODO 这个差了个过滤 `已对账`

                return getScoreOrderReconciliationNotYet(
                        AccountingOrderScoreCustomerNotYetDimCreditQueryCriteria
                                .builder()
                                .autoComplete(AccountingOrderDimCreateByEnum.订单.getKey())
                                // 过滤 客户对账状态
                                .accountingStateCustomer(queryCriteria.getAccountingStateCustomer())
                                .orderSnsSelected(autoCompleteUnifiedOrderCreditDimOrder(queryCriteria.getCreditSelected()))
                                .build(),
                        loginSysUser
                );
            case 商品:
                // 抛异常
                return null;
            case 流水:

                /**************************************** 修改前逻辑 start ****************************************/

//                return getScoreOrderReconciliationNotYet(
//                        AccountingOrderScoreCustomerNotYetDimCreditQueryCriteria
//                                .builder()
//                                .autoComplete(AccountingOrderDimCreateByEnum.流水.getKey())
//                                // 过滤 客户对账状态
//                                .accountingStateCustomer(queryCriteria.getAccountingStateCustomer())
//                                .idsCredit(
//                                        queryCriteria.getCreditSelected()
//                                                .stream()
//                                                .map(AccountingOrderScoreCustomerCreateSelectedCreditParam::getUnifiedOrderCreditId)
//                                                .collect(Collectors.toList())
//                                )
//                                .build(),
//                        loginSysUser
//                );

                /**************************************** 修改前逻辑 start ****************************************/


//【正负单关联问题-【结算中心-测试环境】积分结算-订单流水管理-负单查询未带出订单内所有流水】https://www.tapd.cn/33003868/bugtrace/bugs/view?bug_id=1133003868001004749
//【正负单关联问题-【结算中心-测试环境】积分结算-订单流水管理-查询-查询负单-未把正单和其他负单返回】https://www.tapd.cn/33003868/bugtrace/bugs/view?bug_id=1133003868001004540
//【正负单关联问题-【结算中心-测试环境】积分结算-未对账流水-负单查询未带出订单内所有流水】https://www.tapd.cn/33003868/bugtrace/bugs/view?bug_id=1133003868001004751
//【正负单关联问题-【结算中心-测试环境】积分结算-未对账流水-ME20220331095521666157-SR20220331101239783294使用负单创建对账单-未把其关联的负单创建】https://www.tapd.cn/33003868/bugtrace/bugs/view?bug_id=1133003868001004546

//                思路 基于订单商品为最小单位 目前做为只能提级

//                unified_order_credit.id -> order_sn + order_id + goods_id

//                SELECT `order_sn`,`order_id`,`goods_id` FROM `unified_order_credit` WHERE id in (358817) GROUP BY `order_sn`,`order_id`,`goods_id`

                return getScoreOrderReconciliationNotYet(
                        AccountingOrderScoreCustomerNotYetDimCreditQueryCriteria
                                .builder()
                                .autoComplete(AccountingOrderDimCreateByEnum.流水.getKey())
                                .batchs(queryCriteria.getBatchs())
                                // 过滤 客户对账状态
                                .accountingStateCustomer(queryCriteria.getAccountingStateCustomer())
                                .idsCredit(autoCompleteUnifiedOrderCreditDimOrderGoods(queryCriteria.getCreditSelected()))
                                .build(),
                        loginSysUser
                );

            case 不补:
                return getScoreOrderReconciliationNotYet(
                        AccountingOrderScoreCustomerNotYetDimCreditQueryCriteria
                                .builder()
//                                .autoComplete(AccountingOrderDimCreateByEnum.流水.getKey())
                                // 因为方法有两种状态 一是预览 二是确认 所以这里的控制权交出去，不能写死 mark by linjinyu at 20220420
                                .autoComplete(AccountingOrderDimCreateByEnum.不补.getKey())
                                .batchs(queryCriteria.getBatchs())
                                // 过滤 客户对账状态
                                .accountingStateCustomer(queryCriteria.getAccountingStateCustomer())
                                .idsCredit(autoCompleteUnifiedOrderCreditDimOrderGoods(queryCriteria.getCreditSelected()))
                                .build(),
                        loginSysUser
                );

            default:
                // 抛异常
                return null;
        }

        /****************************************** 场景2   end ******************************************/

    }

    /**
     * 场景3 作为对账单明细数据,开票申请678
     *
     * @param queryCriteria
     * @param loginSysUser
     * @return
     */
    @Override
    public List<InvoiceApplyDetailDimCreditItemVo> getScoreOrderReconciliationNotYetScene3(
            AccountingOrderScoreCustomerNotYetDimCreditScene3QueryCriteria queryCriteria,
            LoginSysUser loginSysUser) {

        return getScoreOrderReconciliationNotYet(
                AccountingOrderScoreCustomerNotYetDimCreditQueryCriteria
                        .builder()
                        .autoComplete(AccountingOrderDimCreateByEnum.流水.getKey())
                        .idsCredit(queryCriteria.getIdsCredit())
                        .build(),
                loginSysUser
        );
    }

    /**
     * @param queryCriteria
     * @param loginSysUser
     * @return
     */
    @Override
    public R<List<InvoiceApplyDetailDimCreditItemVo>> getScoreOrderReconciliationNotYetScene4(
            AccountingOrderScoreCustomerNotYetDimCreditScene4QueryCriteria queryCriteria,
            LoginSysUser loginSysUser) {

        List<Long> idsCredit = invoiceApplyXGoodsService.findCreditSetByInvoicApplyId(queryCriteria.getInvoiceApplyId());

        PageHelper.startPage(queryCriteria.getPageNumber(), queryCriteria.getPageSize());

        List<InvoiceApplyDetailDimCreditItemVo> resultList = getScoreOrderReconciliationNotYet(
                AccountingOrderScoreCustomerNotYetDimCreditQueryCriteria
                        .builder()
                        .autoComplete(AccountingOrderDimCreateByEnum.流水.getKey())
                        .idsCredit(idsCredit)

                        /**************************************** 搜索参数 start ****************************************/

                        .orderSn(queryCriteria.getOrderSn())
                        .orderSnEq(queryCriteria.getOrderSnEq())
                        .goodsName(queryCriteria.getGoodsName())//: "菊芝韵 茶叶 花草茶 庐山金菊 金丝皇菊大菊花茶30朵礼盒装"
                        .goodsId(queryCriteria.getGoodsId())//: 5128573
                        .unifiedOrderGoodsId(queryCriteria.getUnifiedOrderGoodsId())//: 1911428
                        .operationTaxCode(queryCriteria.getOperationTaxCode())//: "1010116010000000000"

                        /**************************************** 搜索参数   end ****************************************/

                        .build(),
                loginSysUser
        );

        PageInfo<InvoiceApplyDetailDimCreditItemVo> page = new PageInfo<InvoiceApplyDetailDimCreditItemVo>(resultList);
        PageHelper.clearPage();

        return new R<List<InvoiceApplyDetailDimCreditItemVo>>(page.getPageNum(), page.getPageSize(), (int) page.getTotal(), resultList);
    }

    /**
     * 积分结算2.1 后封闭 按场景开放 mark by linjinyu at 20220225
     *
     * @param queryCriteria
     * @param loginSysUser
     * @return
     */
    private List<InvoiceApplyDetailDimCreditItemVo> getScoreOrderReconciliationNotYet(
            AccountingOrderScoreCustomerNotYetDimCreditQueryCriteria queryCriteria,
            LoginSysUser loginSysUser) {


        // 场景1 作为未对账流水 订单流水管理

        // 场景2 作为创建对账单数据
        // 前置条件是 queryCriteria.getCreditSelected() 不能为空,在多只是防御一下

        // 场景3 作为对账单明细数据,开票申请

        log.info("getScoreOrderReconciliationNotYet -> queryCriteria\n{}", JSONUtil.toJsonStr(queryCriteria));


        List<InvoiceApplyDetailDimCreditItemVo> resultList = new ArrayList<>();

        /**************************************** 特殊处理一下 start ****************************************/

//        autoComplete

        /**************************************** 特殊处理一下   end ****************************************/


        resultList = unifiedOrderMapperExCustomerDimCredit.getScoreOrderReconciliationNotYet(queryCriteria);

        // 附加信息
        additionalInfoInvoiceApplyDetailDimCreditItemVo(resultList);

        /**
         * 数据脱敏
         * 1. 按登陆类型
         * 2. 按开关 SensitiveRequireSwitchEnum SensitiveRequireSwitchConstants.SWITCH_PARAM 开关目前有两种 TODO 有空再写个方法统一判定
         */
        if ((ObjectUtil.isNotNull(loginSysUser)
                && ObjectUtil.isNotNull(loginSysUser.getOutLogin())
                && loginSysUser.getOutLogin().compareTo(SysLoginTypeEnum.福利商城_侨城汇.getKey()) == 0)
                || queryCriteria.getSensitiveRequireSwitch().compareTo(SensitiveRequireSwitchEnum.On.getKey()) == 0) {
            DesensitizedUtils.desensitization(resultList);
        }


        return resultList;

    }

    /**
     * 自动补全 autoCompleteUnifiedOrderCreditDimOrderStep01
     * <p>
     * 最小完整性单位为 订单
     *
     * @param creditSelected 输入最小单位为 流水
     * @return
     */
    public List<String> autoCompleteUnifiedOrderCreditDimOrder(List<AccountingOrderScoreCustomerCreateSelectedCreditParam> creditSelected) {

        // TODO 优化
//        SELECT
//                order_sn,
//        GROUP_CONCAT(return_sn),
//                COUNT(return_sn) AS refund_order_size
//        FROM
//          `unified_order_return`
//        WHERE
//        order_sn IS NOT NULL
//        GROUP BY
//        order_sn
//                HAVING
//        refund_order_size > 1

//		unifiedOrderCreditId: 711413
//		unifiedOrderGoodsId: 1036119
//		unifiedOrderId: 312530

//		SELECT id as unified_order_id,order_sn,refund_order_sn,order_type FROM `unified_order` WHERE id in (312530)
//		SELECT id as unified_order_id,order_sn,refund_order_sn,oAutoCompleteUnifiedOrderCreditDimOrderStep01rder_type FROM `unified_order` WHERE `accounting_state_customer` = 2 AND refund_order_sn IS NOT NULL

        // 分 正负 向 plus-minus
        List<String> orderSns            = new ArrayList<>();
        List<String> orderSnsAllDistinct = new ArrayList<>();
        List<String> orderSnsPlus        = new ArrayList<>();
        List<String> orderSnsMinus       = new ArrayList<>();


        List<Long> processUnifiedOrderIds = creditSelected
                .stream()
                .map(AccountingOrderScoreCustomerCreateSelectedCreditParam::getUnifiedOrderId)
                .distinct()
                .collect(Collectors.toList());

        List<AutoCompleteUnifiedOrderCreditDimOrderStep01Vo> _middleResult = unifiedOrderMapperExCustomerDimCredit.autoCompleteUnifiedOrderCreditDimOrderStep01(
                AutoCompleteUnifiedOrderCreditDimOrderStep01QueryCriteria
                        .builder()
                        .unifiedOrderIds(processUnifiedOrderIds)
                        .build()
        );

//		&& o.getOrderType().compareTo(1) == 0
//		&& o.getOrderType().compareTo(2) == 0
        orderSnsPlus = _middleResult.stream().filter(o -> o.getOrderSn() != null).map(o -> o.getOrderSn()).distinct().collect(Collectors.toList());
        orderSnsMinus = _middleResult.stream().filter(o -> o.getRefundOrderSn() != null).map(o -> o.getRefundOrderSn()).distinct().collect(Collectors.toList());

        orderSns.addAll(orderSnsPlus);
        orderSns.addAll(orderSnsMinus);

        orderSnsAllDistinct = orderSns.stream().distinct().collect(Collectors.toList());

        log.info("autoCompleteUnifiedOrderCreditDimOrder \n{}", JSONUtil.toJsonStr(orderSnsAllDistinct));

        return orderSnsAllDistinct;

    }

    /**
     * 自动补全 autoCompleteUnifiedOrderCreditDimOrderGoodsStep01
     * <p>
     * 最小完整性单位为 订单商品
     *
     * @param creditSelected 输入最小单位为 流水
     * @return
     */
    public List<Long> autoCompleteUnifiedOrderCreditDimOrderGoods(List<AccountingOrderScoreCustomerCreateSelectedCreditParam> creditSelected) {

        List<Long> processUnifiedOrderCreditIds = creditSelected
                .stream()
                .map(AccountingOrderScoreCustomerCreateSelectedCreditParam::getUnifiedOrderCreditId)
                .collect(Collectors.toList());

        List<AutoCompleteUnifiedOrderCreditDimOrderGoodsStep01Vo> _middleResult = unifiedOrderMapperExCustomerDimCredit.autoCompleteUnifiedOrderCreditDimOrderGoodsStep01(
                AutoCompleteUnifiedOrderCreditDimOrderGoodsStep01QueryCriteria
                        .builder()
                        .unifiedOrderCreditIds(processUnifiedOrderCreditIds)
                        .build()
        );

        return unifiedOrderMapperExCustomerDimCredit.autoCompleteUnifiedOrderCreditDimOrderGoodsStep02(
                AutoCompleteUnifiedOrderCreditDimOrderGoodsStep02QueryCriteria
                        .builder()
                        .outOrderSns(
                                _middleResult.stream().map(AutoCompleteUnifiedOrderCreditDimOrderGoodsStep01Vo::getOrderSn)
                                        .collect(Collectors.toList())
                        )
                        .outGoodsIds(
                                _middleResult.stream().map(AutoCompleteUnifiedOrderCreditDimOrderGoodsStep01Vo::getGoodsId)
                                        .collect(Collectors.toList())
                        )
                        .build()
        );
    }

    /**
     * 附加信息
     *
     * @param resultList
     */
    private void additionalInfoInvoiceApplyDetailDimCreditItemVo(List<InvoiceApplyDetailDimCreditItemVo> resultList) {

        if (CollUtil.isEmpty(resultList)) {
            return;
        }

        // 修数据
        for (InvoiceApplyDetailDimCreditItemVo vo : resultList) {

            // 补 订单类型-订单来源-引用enum CommonServiceNoEnum
            if (ObjectUtil.isNotNull(vo.getServiceNo())) {
                vo.setServiceNoName(CommonServiceNoEnum.getByServiceNo(vo.getServiceNo()).getServiceName());
            } else {
                vo.setServiceNoName(CommonServiceNoEnum.UNKNOW.getServiceName());
            }

            // 对账单状态
            vo.setAccountingStateCustomerName(CommonAccountingStateEnum.getDesc(vo.getAccountingStateCustomer()));
            // 票类状态
            vo.setInvoiceApplyStatusName(UnifiedOrderCreditInvoiceApplyStatusEnum.getDesc(vo.getInvoiceApplyStatus()));
            vo.setInvoiceMakeStatusName(UnifiedOrderCreditInvoiceMakeStatusEnum.getDesc(vo.getInvoiceMakeStatus()));
            // 回款类状态
            vo.setBackStatusName(UnifiedOrderCreditBackAccountStatusEnum.getDesc(vo.getBackStatus()));
        }

    }


    /**
     * 要重构这个方法
     *
     * @param unifiedOrderReturn
     */
    private void processProfit(UnifiedOrderReturn unifiedOrderReturn) {

        // TODO mark by linjinyu 重构 分润 start =================================
        Map<String, Object> profitQuery = new HashMap<>();
        profitQuery.put("projectId", unifiedOrderReturn.getProjectId());
        List<UnifiedChannelProfitSync> channelProfitSyncs = unifiedChannelProfitSyncMapperEx.findAll(profitQuery);
        if (AnCollectionUtils.isNotEmpty(channelProfitSyncs)) {

            // 如果有分润的 更新分润表
            UnifiedChannelProfitSync channelProfitSync = channelProfitSyncs.get(0);

            UnifiedOrderProfit profit = new UnifiedOrderProfit();

            profit.setBusinessCode(channelProfitSync.getBusinessCode());
            profit.setChannelId(channelProfitSync.getChannelId());
            profit.setCreateTime(DateUtil.date());
            profit.setOrgId(channelProfitSync.getOrganizationId());

            profit.setProfitAmount(new BigDecimal(unifiedOrderReturn.getAmount().doubleValue() * channelProfitSync.getProportion().doubleValue() / 100).negate());
            profit.setProportion(channelProfitSync.getProportion());

            profit.setOrderSn(unifiedOrderReturn.getOrderSn());
            profit.setOrderSnReturn(unifiedOrderReturn.getReturnSn());

            UnifiedOrderProfit searchProfit = unifiedOrderProfitMapperEx.selectByReturnSn(unifiedOrderReturn.getReturnSn());

            if (searchProfit != null) {
                profit.setId(searchProfit.getId());
                unifiedOrderProfitMapper.updateByPrimaryKeySelective(profit);
            } else {
                unifiedOrderProfitMapper.insert(profit);
            }
        }
        // TODO mark by linjinyu 重构 分润  end  =================================
    }


}
