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

import cn.hutool.core.date.DateUtil;
import cn.superdesk.uniorder.common.enums.accounting.AccountingOrderTypeDimEnum;
import cn.superdesk.uniorder.common.enums.common.*;
import cn.superdesk.uniorder.common.exception.utils.ExceptionUtils;
import cn.superdesk.uniorder.common.json.AnJsonUtils;
import cn.superdesk.uniorder.common.numerical.AnCollectionUtils;
import cn.superdesk.uniorder.dao.entity.base.*;
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.operation.UnifiedOrderIssuesFlowingParam;
import cn.superdesk.uniorder.dto.receive.consumer.superdeskmall.unified.qyng.refund.UnifiedQyngRefundOrderGoodsReceiveParam;
import cn.superdesk.uniorder.dto.receive.consumer.superdeskmall.unified.qyng.refund.UnifiedQyngRefundOrderOrderReceiveParam;
import cn.superdesk.uniorder.dto.receive.consumer.superdeskmall.unified.qyng.refund.UnifiedQyngRefundOrderReceiveParam;
import cn.superdesk.uniorder.service.order.base.CommonMergeOrderCreditProcessService;
import cn.superdesk.uniorder.service.order.base.CommonMergeOrderGoodsProcessService;
import cn.superdesk.uniorder.service.order.base.CommonMergeRefundOrderProcessService;
import cn.superdesk.uniorder.service.order.base.CommonOrderProcessService;
import cn.superdesk.uniorder.service.order.receive.ReceiveQyngRefundOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 重构 20210628
 * @Author: linjinyu
 * @CreateDate: 2021/6/28 下午5:39
 * @UpdateUser: linjinyu
 * @UpdateDate: 2021/6/28 下午5:39
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Slf4j
@Service
public class ReceiveQyngRefundOrderServiceImpl implements ReceiveQyngRefundOrderService {

    @Autowired
    private UnifiedOrderMapper                   unifiedOrderMapper;
    @Autowired
    private UnifiedOrderMapperEx                 unifiedOrderMapperEx;
    @Autowired
    private UnifiedOrderMapperExSupplierDimOrder unifiedOrderMapperExSupplier;
    @Autowired
    private UnifiedOrderGoodsMapper              unifiedOrderGoodsMapper;
    @Autowired
    private UnifiedOrderGoodsMapperEx            unifiedOrderGoodsMapperEx;

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

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

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

    @Autowired
    private CommonOrderProcessService            commonOrderProcessService;
    @Autowired
    private CommonMergeRefundOrderProcessService commonMergeOrderProcessService;
    @Autowired
    private CommonMergeOrderGoodsProcessService  commonMergeOrderGoodsProcessService;
    @Autowired
    private CommonMergeOrderCreditProcessService commonMergeOrderCreditProcessService;

    /**
     * 退单 维权订单
     * 一般订单处理
     * <p>
     * 企业采购 福利内购 才有的 目前 20200423 mark by linjinyu
     *
     * @param receiveParam
     * @return
     */
    @Transactional
    public UnifiedOrderIssuesFlowingParam kafkaUnifiedQyngRefundOrderReceive(UnifiedQyngRefundOrderReceiveParam receiveParam) {

        UnifiedOrderIssuesFlowingParam callback = new UnifiedOrderIssuesFlowingParam();
        callback.setUid(receiveParam.getUid());
        callback.setProcessResult(CommonProcessResultEnum.正常.getKey());
        callback.setProcessReport("");


        log.info("\n########################## kaFkaUnifiedOrderReturn start ################################\n \norder : {}\ngoods : {}", AnJsonUtils.toJson(receiveParam.getOrder()), AnJsonUtils.toJson(receiveParam.getGoods()));


//		order : {"amount":"11680.20","project_id":"66","return_sn":"SR20200304163613122249","sn":"ME20200225151952681226","complet_state":1}
//		goods : {"goods_name":"摩托罗拉/Motorola VZ-D135 数字对讲机商用手台 小巧 1电1充 标配【销售单位:套】","total":"20","quantity":"20","orderid":"55971","price":584.01,"return_sn":"SR20200304163613122249","goods_id":"2482410","realprice":"11680.20","cost_price":"537.29"}

        try {

            // ########################################### 维权订单处理 start ###########################################

            // 判定 order 为空
            if (null == receiveParam.getOrder()) {
                // TODO 记录 Error
                callback.setProcessResult(CommonProcessResultEnum.异常_数据本身缺失.getKey());
                callback.setProcessReport("退单订单信息为空");
                return callback;
            }
            // 判定 goods 为空
            if (null == receiveParam.getGoods()) {
                // TODO 记录 Error
                callback.setProcessResult(CommonProcessResultEnum.异常_数据本身缺失.getKey());
                callback.setProcessReport("退单商品为空");
                return callback;
            }

            // 处理 退单 主体 转换 持久化 | 执行完后,这个退单是已经持久化了 是只 退单号来判定唯一的
            UnifiedOrderReturn unifiedOrderReturn = convertAndStoreUnifiedQyngRefundOrderReceiveParam2Entity(receiveParam);
            // 处理 退单 商品 转换 持久化
            UnifiedOrderReturnGoods unifiedOrderReturnGoods = convertAndStoreUnifiedQyngRefundOrderGoodsReceiveParam2Entity(receiveParam);

            /****************************************** TODO 20210120 处理退单退运费验证 start ******************************************/
            UnifiedOrderGoods refundOrderGoods = null;
//			if (null != unifiedOrderReturn.getTransportAmount() && unifiedOrderReturn.getTransportAmount().compareTo(BigDecimal.ZERO) > 0)
            /****************************************** TODO 20210120 处理退单退运费验证   end ******************************************/


            // 重新核算 退单 修正 传过来时  amount 为 0 的问题 TODO 好像与退运费没什么关系
            accountingUnifiedOrderReturnAmount(unifiedOrderReturn, unifiedOrderReturnGoods);// 卡住

            // 反过来再处理 UnifiedOrderGoods 没有持久化 只是转换
            List<UnifiedOrderGoods> hedgeUnifiedOrderGoodsList = processRefundOrderGoodsRetrunUnifiedOrderGoods(unifiedOrderReturn, unifiedOrderReturnGoods);

            // 处理退运费
            // 目前没有

            // 重新核算订单
//			accountingUnifiedOrderAmount(hedgeUnifiedOrder.getOrderSn());
            UnifiedOrder hedgeUnifiedOrder = processRefundOrderUnifiedOrder(unifiedOrderReturn);

            // 与现有数据合并 并 持久化
            commonMergeOrderGoodsProcessService.processUnifiedOrderGoodsBykafkaPushOrderReceive(hedgeUnifiedOrder, hedgeUnifiedOrderGoodsList, -1);

            log.info("listenRefund kaFkaUnifiedOrderReturn. end===>");

            // 分润处理 TODO 目前的没验证 先屏蔽
//			processProfit(unifiedOrderReturn);


//			// TODO 20200529 问题出在这里 TAPD_ID_1000991_PC端_企业购订单部分退货后,统一订单没有对冲的负数订单,导致对账出错.md
//			// 这个id 不为空
//			// add dz 2019-09-25 订单增加一条负数 不等于空的情况就说明之前已经生成过负数记录
//			if (null == unifiedOrderReturnGoods.getId()) {
//
//
////				添加一条 负的 对充 商品
//				UnifiedOrderGoods unifiedOrderGoods = new UnifiedOrderGoods();
//
//				unifiedOrderGoods.setGoodsType(UnifiedOrderGoodsTypeEnum.商品.getKey());
//				unifiedOrderGoods.setDirection(CommonDirectionEnum.负向.getKey());
//				unifiedOrderGoods.setAccountingStateCustomer(CommonAccountingStateEnum.未对账.getKey());
//				unifiedOrderGoods.setAccountingStateSupplier(CommonAccountingStateEnum.未对账.getKey());
//
//				BigDecimal unitPrice = new BigDecimal(unifiedOrderReturnGoods.getPrice().doubleValue());
//
//				// TODO bug 对错位了
//				unifiedOrderGoods.setOrderSn(unifiedOrderReturn.getOrderSn());
//
//				unifiedOrderGoods.setCostPrice(unifiedOrderReturnGoods.getCostPrice());
//
//				unifiedOrderGoods.setGoodsName(unifiedOrderReturnGoods.getGoodsName());
//				unifiedOrderGoods.setPrice(unitPrice);
//				// 对充一下负数的数量
//				unifiedOrderGoods.setQuantity(0-unifiedOrderReturnGoods.getQuantity());
//
//				unifiedOrderGoods.setCreateTime(DateUtil.date());
//				unifiedOrderGoods.setCreateUserId(1L);
//
//				unifiedOrderGoods.setUpdateTime(DateUtil.date());
//				unifiedOrderGoods.setUpdateUserId(1L);
//
//				unifiedOrderGoodsMapper.insert(unifiedOrderGoods);
//
//				UnifiedOrder unifiedOrder1 = new UnifiedOrder();
//
////==> Preparing: select id, sn, out_sn, order_type, service_no, project_id, project_name, purchase_virt_id, purchase_virt_name, purchase_user_id, purchase_user_name, purchase_phone, sale_id, sale_name, amount, cost_amount, transport_amount, complet_state, sale_account_state, account_state, payment_type, pay_state, order_state, order_state_name, settlement_type, appraise_state, source_channel, other_params, user_type, user_name, inv_state, create_time, create_user_id, update_time, update_user_id, rec_user_name, rec_user_id, rec_user_phone, rec_address, remarks, invoice_number, inv_sn from unified_order where sn = ?
////==> Parameters: ME20190802171645769831(String)
//
//				UnifiedOrder unifiedOrder = unifiedOrderMapperEx.selectByPrimaryOrderSn(unifiedOrderGoods.getOrderSn());
//
//				if (null == unifiedOrder) {
//					callback.setProcessReport("订单数据为空");
//					return callback;
//				}
//
//				// TODO Mark 这个 基于 商城的订单号 有可能会查不到
//				log.info("unifiedOrderMapper.selectByPrimarySn : " + JsonUtils.toJson(unifiedOrder));
//
//				unifiedOrder1.setId(unifiedOrder.getId());
//
//				// TODO bug https://www.tapd.cn/33003868/bugtrace/bugs/view/1133003868001000639
//				BigDecimal amount = new BigDecimal(unifiedOrder.getAmount().doubleValue() + (unifiedOrderGoods.getPrice().doubleValue() * unifiedOrderGoods.getQuantity()));
//				unifiedOrder1.setAmount(amount);
//
//				// TODO 20200427 add linjinyu
//				BigDecimal costAmount = new BigDecimal(unifiedOrder.getCostAmount().doubleValue() + (unifiedOrderGoods.getCostPrice().doubleValue() * unifiedOrderGoods.getQuantity()));
//				unifiedOrder1.setCostAmount(costAmount);
//
//				commonOrderProcessService.attachUpdate(unifiedOrder1);
//
//
//			}
            // end


        } catch (Exception e) {

            log.error("kaFkaUnifiedOrderReturn error===>\n{}", ExceptionUtils.getMessage(e));
            e.printStackTrace();
            // 手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

            callback.setProcessResult(CommonProcessResultEnum.异常_数据本身缺失.getKey());

        } finally {

            log.info("\n########################## kaFkaUnifiedOrderReturn end   ################################\n");

            return callback;
        }

    }

    private UnifiedOrderReturn convertAndStoreUnifiedQyngRefundOrderReceiveParam2Entity(
    		UnifiedQyngRefundOrderReceiveParam unifiedQyngRefundOrderReceiveParam) {

        // 初始化 退单 主体
        UnifiedOrderReturn refundOrderEntity = new UnifiedOrderReturn();

        UnifiedQyngRefundOrderOrderReceiveParam refundOrderReceiveParam = unifiedQyngRefundOrderReceiveParam.getOrder();

        // 找一下这个退单 在当前数据库 有没有 也就是说是不是第一次推过来
        List<UnifiedOrderReturn> listOldUnifiedOrderReturn = unifiedOrderReturnMapperEx.findByRefundOrderSn(refundOrderReceiveParam.getRefundOrderSn());

        log.info("kaFkaUnifiedOrderReturn listOldUnifiedOrderReturn.get(0)===>找到:" + refundOrderReceiveParam.getRefundOrderSn());


        // TODO 20200514 by linjinyu 家豪说:企业采购 福利采购 维权单(退货退款|退款|) 只会有一种商品
        if (null != listOldUnifiedOrderReturn && listOldUnifiedOrderReturn.size() == 1) {
            refundOrderEntity = listOldUnifiedOrderReturn.get(0);
        }

        /****************************************** 商城也要修改 start ******************************************/

        refundOrderEntity.setServiceName(CommonServiceNoEnum.企业采购.getServiceName());
        refundOrderEntity.setServiceNo(CommonServiceNoEnum.企业采购.getServiceNo());

        /****************************************** 商城也要修改 start ******************************************/

        refundOrderEntity.setOrderDim(AccountingOrderTypeDimEnum.一般订单.getKey());

        refundOrderEntity.setOrderSn(refundOrderReceiveParam.getOrderSn());
        refundOrderEntity.setReturnSn(refundOrderReceiveParam.getRefundOrderSn());

        refundOrderEntity.setProjectId(refundOrderReceiveParam.getProjectId());


        /**************************************** mark by linjinyu at 2022-07-25 10:34:44 - start ****************************************/

        refundOrderEntity.setExpress(refundOrderReceiveParam.getExpress());
        refundOrderEntity.setExpressCompany(refundOrderReceiveParam.getExpressCompany());
        refundOrderEntity.setExpressSn(refundOrderReceiveParam.getExpressSn());

        /**************************************** mark by linjinyu at 2022-07-25 10:34:44 -   end ****************************************/

        /****************************************** 以下信息没传 start ******************************************/

//		refundOrderEntity.setProjectName(refundOrderReceiveParam.getProjectName());

//		refundOrderEntity.setPurchaseVirtId(refundOrderReceiveParam.getPurchaseVirtId());
//		refundOrderEntity.setPurchaseVirtName(refundOrderReceiveParam.getPurchaseVirtName());
//
//		refundOrderEntity.setPurchaseDepartmentName(refundOrderReceiveParam.getPurchaseDepartmentName());
//
//		refundOrderEntity.setPurchaseUserId(refundOrderReceiveParam.getPurchaseUserId());
//		refundOrderEntity.setPurchaseUserName(refundOrderReceiveParam.getPurchaseUserName());
//		refundOrderEntity.setPurchasePhone(refundOrderReceiveParam.getPurchasePhone());

        /****************************************** 以下信息没传   end ******************************************/

        // order : {"amount":"","project_id":"615","return_sn":"SR20190802170324142482","sn":"ME20190802153337664456","complet_state":1}
        // amount 为 空串的情况是 退换货的情况
        // TODO 这个不是销售价 是退款时 手工填写的金额
        refundOrderEntity.setAmount(refundOrderReceiveParam.getAmount() == null ? BigDecimal.ZERO : refundOrderReceiveParam.getAmount());


        // change dz 1025 TODO 这个是为什么呀? 就是上边说的问题 优化点 直接 先去看这个退款金金额有没有 没有直接返回啦 做这么多事干什么
//		if (unifiedOrderReturn.getAmount().doubleValue() <= 0) {
//			callback.setProcessResult(CommonProcessResultEnum.异常.getKey());
//			callback.setProcessReport("退单金额小于等于0");
////				return callback;
//		}

        refundOrderEntity.setCompletState(refundOrderReceiveParam.getCompletState());

        refundOrderEntity.setUserType("kafka");
        refundOrderEntity.setUserName("kafka系统同步");

        // 保存数据 维权订单
        if (null != refundOrderEntity.getId()) {

            refundOrderEntity.setUpdateUserId(1L);
            refundOrderEntity.setUpdateTime(DateUtil.date());

            unifiedOrderReturnMapper.updateByPrimaryKeySelective(refundOrderEntity);

        } else {

            refundOrderEntity.setAccountingStateCustomer(CommonAccountingStateEnum.未对账.getKey());
            refundOrderEntity.setPayState(2);


            // TODO 未确认 linjinyu 订单状态 start
            refundOrderEntity.setOrderState(refundOrderReceiveParam.getCompletState());

            String orderStateName = "";

            if (refundOrderReceiveParam.getCompletState().equals(1)) {
                orderStateName = "完成";
            } else if (refundOrderReceiveParam.getCompletState().equals(2)) {
                orderStateName = "未完成";
            } else if (refundOrderReceiveParam.getCompletState().equals(3)) {
                orderStateName = "已取消";
            }

            refundOrderEntity.setOrderStateName(orderStateName);
            // TODO 未确认 linjinyu 订单状态 end

            refundOrderEntity.setCreateUserId(1L);
            refundOrderEntity.setCreateTime(DateUtil.date());

            unifiedOrderReturnMapper.insertSelective(refundOrderEntity);
        }

        return refundOrderEntity;

    }

    private UnifiedOrderReturnGoods convertAndStoreUnifiedQyngRefundOrderGoodsReceiveParam2Entity(UnifiedQyngRefundOrderReceiveParam receiveParam) {

        // 退单商品处理
        UnifiedOrderReturnGoods unifiedOrderReturnGoods = new UnifiedOrderReturnGoods();

        UnifiedQyngRefundOrderGoodsReceiveParam refundGoods = receiveParam.getGoods();


        // TODO 基于退维权 订单SN来去查 退货 货物
        List<UnifiedOrderReturnGoods> unifiedOrderReturnGoodsList = unifiedOrderReturnGoodsMapperEx.findByRefundOrderSn(refundGoods.getRefundOrderSn());

        if (null != unifiedOrderReturnGoodsList && unifiedOrderReturnGoodsList.size() == 1) {

            log.info("kaFkaUnifiedOrderReturn listUnifiedOrderReturnGoods.get(0)===>找到:" + refundGoods.getRefundOrderSn());

            unifiedOrderReturnGoods = unifiedOrderReturnGoodsList.get(0);

        }

        unifiedOrderReturnGoods.setReturnSn(refundGoods.getRefundOrderSn());
        unifiedOrderReturnGoods.setGoodsName(refundGoods.getGoodsName());
        unifiedOrderReturnGoods.setGoodsId(refundGoods.getGoodsId());
        unifiedOrderReturnGoods.setQuantity(refundGoods.getTotal());
        unifiedOrderReturnGoods.setCostPrice(refundGoods.getCostPrice());
        unifiedOrderReturnGoods.setPrice(refundGoods.getPrice());


        if (null != unifiedOrderReturnGoods.getId()) {
            unifiedOrderReturnGoods.setUpdateUserId(2L);
            unifiedOrderReturnGoods.setUpdateTime(DateUtil.date());
        } else {
            unifiedOrderReturnGoods.setCreateUserId(1L);
            unifiedOrderReturnGoods.setCreateTime(DateUtil.date());
        }

        // 保存数据 维权订单 货品
        if (null != unifiedOrderReturnGoods.getId()) {
            unifiedOrderReturnGoodsMapper.updateByPrimaryKeySelective(unifiedOrderReturnGoods);
        } else {
            unifiedOrderReturnGoodsMapper.insertSelective(unifiedOrderReturnGoods);
        }

//		// 保存数据 维权订单 货品
//		if (null != unifiedOrderReturnGoods.getId()) {
//			unifiedOrderReturnGoodsMapper.updateByPrimaryKeySelective(unifiedOrderReturnGoods);
//		} else {
//			unifiedOrderReturnGoodsMapper.insertSelective(unifiedOrderReturnGoods);
//		}

        return unifiedOrderReturnGoods;
    }

    private void accountingUnifiedOrderReturnAmount(
            UnifiedOrderReturn unifiedOrderReturn,
            UnifiedOrderReturnGoods unifiedOrderReturnGoods
    ) {
        log.info("accountingUnifiedOrderReturnAmount unifiedOrderReturn \n{}", AnJsonUtils.toPrettyJson(unifiedOrderReturn));
        log.info("accountingUnifiedOrderReturnAmount unifiedOrderReturnGoods \n{}", AnJsonUtils.toPrettyJson(unifiedOrderReturnGoods));

        if (null == unifiedOrderReturn.getAmount()
                || unifiedOrderReturn.getAmount().compareTo(BigDecimal.ZERO) == 0) {

            log.info("TODO 退单 金额 为 0 先记录 数据错误 ");


            BigDecimal checkUnifiedOrderReturnGoodsPriceQuantity = unifiedOrderReturnGoods.getPrice().multiply(new BigDecimal(unifiedOrderReturnGoods.getQuantity()));

            log.info("TODO 退单的 商品 与 流水 金额对等 更新");

            unifiedOrderReturn.setAmount(checkUnifiedOrderReturnGoodsPriceQuantity);

            unifiedOrderReturnMapper.updateByPrimaryKeySelective(unifiedOrderReturn);
        }
    }

//	private void accountingUnifiedOrderAmount(String orderSn) {
//
//		// TODO 重新核算一下订单 linjinyu start
//		UnifiedOrder            checkGomputationUnifiedOrder = unifiedOrderMapperEx.selectByPrimaryOrderSn(orderSn);
//		List<UnifiedOrderGoods> checkGomputationGoods        = unifiedOrderGoodsMapperEx.findByOrderSn(orderSn);
//
//		BigDecimal checkGomputationAmount     = BigDecimal.ZERO;
//		BigDecimal checkGomputationCostAmount = BigDecimal.ZERO;
//
//		checkGomputationAmount = checkGomputationGoods
//				.stream()
//				.map(item -> item.getPrice() == null ? BigDecimal.ZERO : item.getPrice().multiply(new BigDecimal(item.getQuantity())))
//				.reduce(BigDecimal.ZERO, BigDecimal::add);
//
//
//		checkGomputationCostAmount = checkGomputationGoods
//				.stream()
//				.map(item -> item.getCostPrice() == null ? BigDecimal.ZERO : item.getCostPrice().multiply(new BigDecimal(item.getQuantity())))
//				.reduce(BigDecimal.ZERO, BigDecimal::add);
//
////			if (null != checkGomputationUnifiedOrder && AnCollectionUtils.isNotEmpty(checkGomputationGoods)) {
////
////				checkGomputationGoods.forEach(goods -> {
////					checkGomputationAmount = new BigDecimal(checkGomputationAmount.doubleValue() + goods.getPrice().doubleValue() * goods.getQuantity());
////					checkGomputationCostAmount = new BigDecimal(checkGomputationCostAmount.doubleValue() + goods.getCostPrice().doubleValue() * goods.getQuantity());
////				});
////
////
////			}
//
//		checkGomputationUnifiedOrder.setAmount(checkGomputationAmount);
//		checkGomputationUnifiedOrder.setCostAmount(checkGomputationCostAmount);
//
//		commonOrderProcessService.attachUpdate(checkGomputationUnifiedOrder);
//
//		// TODO 重新核算一下订单 linjinyu end
//	}

    /**
     * 单主体情况 - 处理 对冲 商品
     *
     * @param unifiedOrderReturn
     * @param unifiedOrderReturnGoods
     * @return
     */
    private List<UnifiedOrderGoods> processRefundOrderGoodsRetrunUnifiedOrderGoods(UnifiedOrderReturn unifiedOrderReturn, UnifiedOrderReturnGoods unifiedOrderReturnGoods) {

        List<UnifiedOrderGoods> hedgeUnifiedOrderGoodsList = new ArrayList<>();

        log.info("processScoreOrderRefundUnifiedOrderGoods :: unifiedOrderReturn \n{}", AnJsonUtils.toJson(unifiedOrderReturn));
        log.info("processScoreOrderRefundUnifiedOrderGoods :: unifiedOrderReturnGoods \n{}", AnJsonUtils.toJson(unifiedOrderReturnGoods));

        // TODO 查一下这个对冲商品有没有 20201017 12:00 发现有个问题,如果同一个单 多个商品退单好像有问题 排查
//		UnifiedOrderGoodsExample example = new UnifiedOrderGoodsExample();
//		example.createCriteria()
//				.andOrderSnEqualTo(unifiedOrderReturn.getOrderSn())
//				.andGoodsIdEqualTo(unifiedOrderReturnGoods.getGoodsId())// 目前 数据库有可能是没记录的 // TODO 什么时候 修下这个问题, 再回头修改这里
////                .andPriceEqualTo(unifiedOrderReturnGoods.getPrice()) // TODO 按道理 这个金额是不会变的,存于商城快照
////                .andCostPriceEqualTo(unifiedOrderReturnGoods.getCostPrice()) // TODO 按道理 这个金额是不会变的,存于商城快照
////                .andGoodsNameEqualTo(unifiedOrderReturnGoods.getGoodsName()) // TODO 按道理 这个金额是不会变的,存于商城快照
//				.andQuantityLessThan(0)
//				.andDirectionEqualTo(-1);
//		List<UnifiedOrderGoods> existUnifiedOrderGoodsList = unifiedOrderGoodsMapper.selectByExample(example);

        // 算了 , 不做 更新的情况
//		if (AnCollectionUtils.isEmpty(existUnifiedOrderGoodsList)) {
        // 添加一条 负的 对充 商品

        UnifiedOrderGoods unifiedOrderGoods = new UnifiedOrderGoods();

        unifiedOrderGoods.setGoodsType(CommonOrderGoodsTypeEnum.商品.getKey());
        unifiedOrderGoods.setDirection(CommonDirectionEnum.负向.getKey());

        unifiedOrderGoods.setGoodsLockingCustomer(CommonAccountingLockingEnum.正常.getKey());
        unifiedOrderGoods.setGoodsLockingSupplier(CommonAccountingLockingEnum.正常.getKey());

        unifiedOrderGoods.setAccountingStateCustomer(CommonAccountingStateEnum.未对账.getKey());
        unifiedOrderGoods.setAccountingStateSupplier(CommonAccountingStateEnum.未对账.getKey());


        BigDecimal unitPrice = new BigDecimal(unifiedOrderReturnGoods.getPrice().doubleValue());

        unifiedOrderGoods.setOrderSn(unifiedOrderReturn.getOrderSn());
        unifiedOrderGoods.setGoodsName(unifiedOrderReturnGoods.getGoodsName());
        // 目前这个退单的商品没这个字段
//        unifiedOrderGoods.setOutSnapshotOrderGoodsId(unifiedOrderReturnGoods.getOutSnapshotOrderGoodsId());
        unifiedOrderGoods.setGoodsId(unifiedOrderReturnGoods.getGoodsId());

        // 对充一下负数的数量
        unifiedOrderGoods.setQuantity(0 - unifiedOrderReturnGoods.getQuantity());

        unifiedOrderGoods.setCostPrice(unifiedOrderReturnGoods.getCostPrice());
        unifiedOrderGoods.setPrice(unifiedOrderReturnGoods.getPrice());

        /****************************************** 退单退商品 添加 税率 mark by linjinyu at 20210323 start ******************************************/

        unifiedOrderGoods.setFiscalCode(unifiedOrderReturnGoods.getFiscalCode());
        unifiedOrderGoods.setTaxCode(unifiedOrderReturnGoods.getTaxCode());
        unifiedOrderGoods.setTaxRate(unifiedOrderReturnGoods.getTaxRate());

        // 商户税率
        unifiedOrderGoods.setMerchTaxId(unifiedOrderReturnGoods.getMerchTaxId());
        unifiedOrderGoods.setMerchTaxCode(unifiedOrderReturnGoods.getMerchTaxCode());
        unifiedOrderGoods.setMerchTaxRate(unifiedOrderReturnGoods.getMerchTaxRate());

        // 平台税率
        unifiedOrderGoods.setOperationTaxId(unifiedOrderReturnGoods.getOperationTaxId());
        unifiedOrderGoods.setOperationTaxCode(unifiedOrderReturnGoods.getOperationTaxCode());
        unifiedOrderGoods.setOperationTaxRate(unifiedOrderReturnGoods.getOperationTaxRate());

        /****************************************** 退单退商品 添加 税率 mark by linjinyu at 20210323   end ******************************************/

//		unifiedOrderGoods.setGoodsParams();

        unifiedOrderGoods.setCreateTime(DateUtil.date());
        unifiedOrderGoods.setCreateUserId(1L);

        unifiedOrderGoods.setUpdateTime(DateUtil.date());
        unifiedOrderGoods.setUpdateUserId(1L);

//			unifiedOrderGoodsMapper.insert(unifiedOrderGoods);

        hedgeUnifiedOrderGoodsList.add(unifiedOrderGoods);

//		}
        return hedgeUnifiedOrderGoodsList;
    }

    /**
     * 单主体情况 -此为订单与退单共用时的情况 mark by linjinyu at 20210628
     * <p>
     * 传入退单 -> 重新核算订单
     * 再重构吧 最终只要传入 orderSn 就好了
     *
     * @param unifiedOrderReturn
     */
    private UnifiedOrder processRefundOrderUnifiedOrder(UnifiedOrderReturn unifiedOrderReturn) {

        log.info("processRefundOrderUnifiedOrder :: unifiedOrderReturn \n{}", AnJsonUtils.toJson(unifiedOrderReturn));

        UnifiedOrder checkGomputationUnifiedOrder = unifiedOrderMapperEx.findByOrderSn(unifiedOrderReturn.getOrderSn());

        if (null == checkGomputationUnifiedOrder) {
            // TODO 记录错误
            return null;
        }

        UnifiedOrderGoodsExample unifiedOrderGoodsExample = new UnifiedOrderGoodsExample();
        unifiedOrderGoodsExample.createCriteria()
                .andOrderSnEqualTo(unifiedOrderReturn.getOrderSn())
                // 排除退货(只计算 正向:1;负向:-1)
                .andDirectionEqualTo(CommonDirectionEnum.正向.getKey())
                // 排除运费(运费 GoodsId为0)
                .andGoodsIdNotEqualTo(CommonOrderGoodsIdEnum.运费.getKey());

//		unifiedOrderGoodsMapperEx.findByOrderSn(unifiedOrderReturn.getOrderSn());

        List<UnifiedOrderGoods> checkGomputationUnifiedOrderGoods = unifiedOrderGoodsMapper.selectByExample(unifiedOrderGoodsExample);
        if (AnCollectionUtils.isEmpty(checkGomputationUnifiedOrderGoods)) {
            // TODO 记录错误
            return null;
        }

        BigDecimal checkGomputationAmount     = BigDecimal.ZERO;
        BigDecimal checkGomputationCostAmount = BigDecimal.ZERO;

        checkGomputationAmount = checkGomputationUnifiedOrderGoods
                .stream()
                .map(item -> item.getPrice() == null ? BigDecimal.ZERO : item.getPrice().multiply(new BigDecimal(item.getQuantity())))
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        checkGomputationCostAmount = checkGomputationUnifiedOrderGoods
                .stream()
                .map(item -> item.getCostPrice() == null ? BigDecimal.ZERO : item.getCostPrice().multiply(new BigDecimal(item.getQuantity())))
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        checkGomputationUnifiedOrder.setAmount(checkGomputationAmount);
        checkGomputationUnifiedOrder.setCostAmount(checkGomputationCostAmount);

        commonOrderProcessService.attachUpdate(checkGomputationUnifiedOrder);

        return checkGomputationUnifiedOrder;

    }

    private void processProfit(UnifiedOrderReturn unifiedOrderReturn) {
        // TODO mark by linjinyu 待重构 分润 start =================================
        // 1209 -- 计算分润
        Map<String, Object> profitQuery = new HashMap<>();

        profitQuery.put("projectId", unifiedOrderReturn.getProjectId());

        List<UnifiedChannelProfitSync> channelProfitSyncs = unifiedChannelProfitSyncMapperEx.findAll(profitQuery);

        if (channelProfitSyncs != null && channelProfitSyncs.size() > 0) {

            // 插入分润表
            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  =================================
    }

}
