package com.zm.order.tool.server.service.impl;

import com.alibaba.fastjson.JSON;
import com.aliyun.openservices.shade.org.apache.commons.lang3.StringUtils;
import com.github.dozermapper.core.Mapper;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import com.zm.order.tool.server.component.ShardingKeyGenerator;
import com.zm.order.tool.server.constants.*;
import com.zm.order.tool.server.cy.WmKoubeiOrdersDao;
import com.zm.order.tool.server.cy.WmOrderAttachGoodsDao;
import com.zm.order.tool.server.cy.WmOrderGiveGoodsDao;
import com.zm.order.tool.server.dao.*;
import com.zm.order.tool.server.design.ZmStorePagesDao;
import com.zm.order.tool.server.dto.OrderAddrDTO;
import com.zm.order.tool.server.dto.OrderSyncAmountEsDTO;
import com.zm.order.tool.server.helper.TemporaryHelp;
import com.zm.order.tool.server.hint.HintOrderPayDetailsDao;
import com.zm.order.tool.server.manager.*;
import com.zm.order.tool.server.message.BatchSyncEsMessage;
import com.zm.order.tool.server.model.*;
import com.zm.order.tool.server.query.*;
import com.zm.order.tool.server.request.OrderDataReviseRequest;
import com.zm.order.tool.server.request.OrderSyncEsRequest;
import com.zm.order.tool.server.request.RefundDataReviseRequest;
import com.zm.order.tool.server.service.ExceptionConstants;
import com.zm.order.tool.server.service.TemporaryService;
import com.zm.order.tool.server.tempdb.MergeOrderDao;
import com.zm.order.tool.server.utils.CommonUtils;
import com.zm.order.tool.server.utils.ConvertUtils;
import com.zm.order.tool.server.utils.DateUtils;
import com.zm.util.dto.Result;
import org.apache.lucene.util.NamedThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;

/**
 * 零时任务处理
 *
 * @Author 陈标
 * @Date 2020/3/25 16:03
 */
@Service
@SuppressWarnings("all")
public class TemporaryServiceImpl implements TemporaryService, InitializingBean {

    private static final Logger logger = LoggerFactory.getLogger(TemporaryServiceImpl.class);

    private ExecutorService executorService;

    private BlockingQueue workQueue;
    @Value("${new.sharding.db.size}")
    private int dbSize;

    @Value("${new.sharding.tb.size}")
    private int tbSize;

    @Autowired
    private RedisManager redisManager;
    @Autowired
    private CommonManager commonManager;
    @Autowired
    private MergeOrderDao mergeOrderDao;
    @Autowired
    private WmOrderDiscountDao wmOrderDiscountDao;
    @Autowired
    private OrderDiscountDao orderDiscountDao;
    @Autowired
    private OrderItemDao orderItemDao;

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private OrderIndexDao orderIndexDao;
    @Autowired
    private RefundDao refundDao;
    @Autowired
    private TemporaryHelp help;
    @Autowired
    private OrderOperationDao operationDao;
    @Autowired
    private UpdateUserIdDao updateUserIdDao;
    @Autowired
    private InnerApiManager innerApiManager;
    @Autowired
    private RefundItemDao refundItemDao;
    @Autowired
    private SearchManager searchManager;
    @Autowired
    private OrderPayDetailsDao orderPayDetailsDao;
    @Autowired
    private Mapper mapper;
    @Autowired
    private OrderAddrDao orderAddrDao;
    @Autowired
    private TemporaryHelp helper;
    @Autowired
    private SourceNoIndexDao sourceNoIndexDao;

    @Autowired
    private EventManager eventManager;

    @Autowired
    private ShardingKeyGenerator shardingKeyGenerator;

    @Autowired
    private OrderUserRelationDao relationDao;
    @Autowired
    private OrderPayDetailsDao payDetailsDao;
    @Autowired
    private OrderRefundDetailsDao refundDetailsDao;
    @Autowired
    private WmOrderAttachGoodsDao orderAttachGoodsDao;
    @Autowired
    private WmOrderGiveGoodsDao orderGiveGoodsDao;
    @Autowired
    private OrderItemBatchingDao itemBatchingDao;
    @Autowired
    private WmKoubeiOrdersDao wmKoubeiOrdersDao;
    @Autowired
    private AsyncMessageManager messageManager;
    @Autowired
    private TestOrderIndexDao testOrderIndexDao;

    @Autowired
    private HintOrderPayDetailsDao hintOrderPayDetailsDao;

    @Autowired
    private ZmStorePagesDao zmStorePagesDao;

    @Autowired
    private OrderUserRelationDao ourDao;

    /**
     * 多线程配置
     */
    @Override
    public void afterPropertiesSet() {
        int coreSize = Runtime.getRuntime().availableProcessors();
        workQueue = new ArrayBlockingQueue(64);
        executorService = new ThreadPoolExecutor(4, 4, 1, TimeUnit.MINUTES,
                workQueue, new NamedThreadFactory("order-data-sync"),
                new ThreadPoolExecutor.AbortPolicy());
    }

    /**
     * 一共处理的数量
     */
    private Integer total = 0;


    /**
     * 对表数据操作
     *
     * @param orderQuery
     * @param dbIndex
     * @param tbIndex
     */
    private void handleTable(OrderQuery orderQuery, int dbIndex, int tbIndex) {
        if (Objects.isNull(orderQuery.getLastId())) {
            orderQuery.setLastId(0L);
        }
        total = 0;
        while (true) {
            List<Order> orders = commonManager.scanOrder(orderQuery, dbIndex, tbIndex);
            if (CollectionUtils.isEmpty(orders)) {
                logger.info("query orderSize:0");
                break;
            }
            logger.info("query orderSize:{}", orders.size());
            // 遍历订单
            for (Order order : orders) {
                if (StringUtils.isEmpty(order.getSourceNo())) {
                    continue;
                }
                while (workQueue.remainingCapacity() < 10000) {
                    try {
                        logger.info("workQueue size{}", workQueue.size());
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {

                            // 真正处理的逻辑业务

                        } catch (Throwable throwable) {
                            logger.error(" xxxxx is failed  orderId{},cause by:{}", order.getId(),
                                    Throwables.getStackTraceAsString(throwable));
                        }
                    }
                });
            }
            orderQuery.setLastId(orders.get(orders.size() - 1).getId());
            total += orders.size();
            logger.info("处理了{}, 数据", orders.size());
            logger.info("库{}, 表{},处理了{},数据", dbIndex, tbIndex, total);
            if (orders.size() < 500) {
                break;
            }
        }
    }
    
    private static final Integer PAGE_SIZE = 200;

    private static final Long START_AT = 1597075200000L;

    private static final Long END_AT = 1597766400000L;

    @Override
    public Result compensate() {
        Result result = new Result();
        OrderQuery orderQuery = new OrderQuery();
        orderQuery.setOrderAtStart(new Date(START_AT));
        orderQuery.setOrderAtEnd(new Date(END_AT));
        orderQuery.setStatus(2);
        orderQuery.setPerformanceTypeList(Lists.newArrayList(1,2));

        try {
            for (int i = 0; i < dbSize; i++) {
                for (int j = 0; j < tbSize; j++) {
                    List<Order> orderList = commonManager.scanOrder(orderQuery, i, j);
                    if (CollectionUtils.isEmpty(orderList)) {
                        break;
                    }
                    orderList.forEach(order -> {
                        excute(order);
                    });
                    if (orderList.size() < PAGE_SIZE) {
                        break;
                    }
                }
            }
        } catch (Exception e) {
            logger.error("[compensate]failed!,cause by:{}", e);
        }
        return result;
    }
    
    private void excute(Order order) {
        if (Objects.nonNull(order)) {
            if (Objects.equals(2, order.getBizType())) {
                Map<String, Object> extraMap = order.getExtraMap();
                if (!CollectionUtils.isEmpty(extraMap)) {
                    Object autoCompleteAt = extraMap.get("autoCompleteAt");
                    if (Objects.nonNull(autoCompleteAt) && !Objects.equals(0, autoCompleteAt)) {
                        Long autoComplete = Long.valueOf(autoCompleteAt.toString());
                        if (autoComplete <= System.currentTimeMillis()) {
                            // 直接推送队列信息到零售
                            Result result = innerApiManager.noticeOrderComplete(order);
                            if (result.isStatus()) {
                                logger.info("send topic message success!orderNo:{}", order.getOrderNo());
                            }else{
                                logger.error("send topic message failed!orderNo:{}", order.getOrderNo());
                            }
                        } else {
                            // 发送消息到事件中心
                            Result result = eventManager.sendDelayCompleteOrderEvent(order, new Date(autoComplete));
                            if (result.isStatus()) {
                                logger.info("send event message success!orderNo:{}", order.getOrderNo());
                            }else {
                                logger.error("send event message failed!orderNo:{}", order.getOrderNo());
                            }
                        }
                    }
                }
            }
        }
    }


    @Override
    public Result syncAmountIndex(OrderSyncAmountEsDTO syncAmountEs) {
        Result result = new Result<>();
        try {
            if (!StringUtils.isEmpty(syncAmountEs.getOrderNo()) && Objects.nonNull(syncAmountEs.getUserId())) {
                Order order = orderDao.selectByOrderNo(syncAmountEs.getOrderNo(), syncAmountEs.getUserId());
                searchManager.indexAmountOrder(order);
            } else {
                OrderQuery orderQuery = new OrderQuery();
                orderQuery.setSize(PAGE_SIZE);
                orderQuery.setOrderAtStart(DateUtils.getStartDate(syncAmountEs.getDate()));
                orderQuery.setOrderAtEnd(DateUtils.getEndDate(syncAmountEs.getDate()));
                for (int i = 0; i < dbSize; i++) {
                    for (int j = 0; j < tbSize; j++) {
                        quene(syncAmountEs, orderQuery, i, j);
                    }
                }
            }
            result.setStatus(true);
        } catch (Exception e) {
            logger.error("[syncAmountIndex]failed!cause by:{}", e);
            result.setException(ExceptionConstants.SYSTEM_ERROR);
        }
        return result;
    }

    private void quene(OrderSyncAmountEsDTO syncAmountEs, OrderQuery orderQuery, int i, int j) {
        try {
            while (workQueue.remainingCapacity() < 10000) {
                logger.info("workQueue size{}", workQueue.size());
                Thread.sleep(5000);
            }
            executorService.submit(() -> {
                executeSync(syncAmountEs, orderQuery, i, j);
            });
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
    private void executeSync(OrderSyncAmountEsDTO syncAmountEs, OrderQuery orderQuery, int i, int j) {
        int count = 0;
        Long lastId = 0L;
        for (;;) {
            orderQuery.setLastId(lastId);
            List<Order> orderList = commonManager.scanOrder(orderQuery, i, j);
            if (CollectionUtils.isEmpty(orderList)) {
                break;
            }
            count += orderList.size();
            searchManager.indexAmountOrderList(orderList, DateUtils.formatDate(syncAmountEs.getDate()));
            String log = "orderpro_" + (i + 1) + ",orders_" + j + ",sync order total：" + count;
            logger.info("message:{}", log);
            if (orderList.size() < PAGE_SIZE) {
                break;
            }
            lastId = orderList.get(orderList.size() - 1).getId();
        }
    }

    @Override
    public Result syncIndex(OrderSyncEsRequest request) {
        Result result = new Result<>();
        int total = 0;
        try {
            OrderQuery orderQuery = buildOrderQuery(request);
            for (int i = 0; i < dbSize; i++) {
                for (int j = 0; j < tbSize; j++) {
                    Long lastId = null;
                    for (;;) {
                        Result<String> redisData = redisManager.get("order_data_sync_es_key");
                        if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                            result.setStatus(true);
                            result.setData(lastId);
                            return result;
                        }
                        orderQuery.setLastId(lastId);
                        List<Order> orderList = commonManager.scanOrder(orderQuery, i, j);
                        if (CollectionUtils.isEmpty(orderList)) {
                            break;
                        }
                        addQueneAndExcute(orderList);
                        total += orderList.size();
                        logger.info("[order_sync_es_index] total:{}", total);
                        if (orderList.size() < PAGE_SIZE) {
                            break;
                        }
                        lastId = orderList.get(orderList.size() - 1).getId();
                    }
                }
            }
            result.setStatus(true);
        } catch (Exception e) {
            logger.error("[syncIndex]failed!cause by:{}", e);
            result.setException(ExceptionConstants.SYSTEM_ERROR);
        }
        return result;
    }

    private void addQueneAndExcute(List<Order> orderList) {
        while (workQueue.remainingCapacity() < 10) {
            logger.info("workQueue size{}", workQueue.size());
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executorService.submit(() -> {
            try {
                searchManager.indexOrder(orderList);
            } catch (Exception e) {
                logger.error("[order_sync_es]failed!cause by:{},", e);
            }
        });
    }

    /**
     * 订单全量同步
     * @return:
     * @Date: 2020/10/10 10:16 AM
     */
    private OrderQuery buildOrderQuery(OrderSyncEsRequest request) {
        Long startAt = 1606226400000L;
        Long endAt = 1606838399000L;
        OrderQuery orderQuery = new OrderQuery();
        orderQuery.setSize(PAGE_SIZE);
        orderQuery.setUpdatedAtStart(new Date(startAt));
        orderQuery.setUpdatedAtEnd(new Date(endAt));
        orderQuery.setOrderNo(request.getOrderNo());
        return orderQuery;
    }

    /**
     * 同步用户端删除的订单
     * minID = 424237643681789610
     * maxID = 538669672799694850
     * @return:
     * @Date: 2020/10/10 10:16 AM
     */
    private OrderQuery buildOrderQuery1(OrderSyncEsRequest request) {
        OrderQuery orderQuery = new OrderQuery();
        orderQuery.setSize(PAGE_SIZE);
        orderQuery.setOrderNo(request.getOrderNo());
        orderQuery.setMaxId(538669672799694850L);
        return orderQuery;
    }

    @Override
    public Result sendEvent() {
        Result result = new Result<>();
        int total = 0;
        try {
            OrderQuery orderQuery = buildQueryParam();
            for (int i = 0; i < dbSize; i++) {
                for (int j = 0; j < tbSize; j++) {
                    Long lastId = 0L;
                    for (;;) {
                        orderQuery.setLastId(lastId);
                        List<Order> orderList = commonManager.scanOrder(orderQuery, i, j);
                        if (CollectionUtils.isEmpty(orderList)) {
                            break;
                        }
                        execute(orderList);
                        total += orderList.size();
                        logger.info("send order event success!total:{}", total);
                        if (orderList.size() < PAGE_SIZE) {
                            break;
                        }
                        lastId = orderList.get(orderList.size() - 1).getId();
                    }
                }
            }
            result.setStatus(true);
        } catch (Exception e) {
            logger.error("[sendEvent]failed!cause by:{}", e);
            result.setException(ExceptionConstants.SYSTEM_ERROR);
        }
        return result;
    }

    /**
     * 重新推送巴莉甜甜的订单评论事件 查询三天内支付成功，并且未评论的订单
     * @return:
     * @Date: 2020/10/10 10:16 AM
     */
    private OrderQuery buildQueryParam() {
        Date startAt = DateUtils.before(DateUtils.getStartDate(new Date()), Calendar.DAY_OF_YEAR, 3);
        Date endAt = DateUtils.getEndDate(new Date());
        OrderQuery orderQuery = new OrderQuery();
        orderQuery.setSize(PAGE_SIZE);
        orderQuery.setOrderAtStart(startAt);
        orderQuery.setOrderAtEnd(endAt);
        orderQuery.setSellerId(29171L);
        orderQuery.setCommentStatus(0);
        orderQuery.setPayStatus(1);
        return orderQuery;
    }
    
    private void execute(List<Order> orderList) {
        orderList.forEach(order -> {
            executorService.submit(() -> {
                try {
                    sendOrderEvent(order);
                } catch (Exception e) {
                    logger.error("[execute]failed！orderNo:{},cause by:{}", order.getOrderNo(), e);
                }
            });
        });
    }

    private void sendOrderEvent(Order order) {
        Map<String, Object> extraMap = order.getExtraMap();
        if (!CollectionUtils.isEmpty(extraMap)) {
            if (Objects.nonNull(extraMap.get("auto_comment_at"))) {
                Long autoCommentAt = Long.valueOf(extraMap.get("auto_comment_at").toString());
                if (autoCommentAt != 0) {
                    Result result = eventManager.sendCommentOrderEvent(order, new Date(autoCommentAt));
                    if (!result.isStatus()) {
                        logger.error("send event message failed!orderNo:{}", order.getOrderNo());
                    }
                }
            }
        }
    }

    @Override
    public Result refundDataRevise(RefundDataReviseRequest request) {
        Result result = new Result<>();
        int count = 0;
        Long id = 424237643681759233L;
        try {
            RefundQuery refundQuery = new RefundQuery();
            refundQuery.setSize(200);
            refundQuery.setRefundNo(request.getRefundNo());
            for (;;) {
                refundQuery.setLastId(id);
                List<Refund> refundList = refundDao.selectList(refundQuery);
                if (CollectionUtils.isEmpty(refundList)) {
                    break;
                }
                refundList.forEach(refund -> {
                    refundDataRevise(refund);
                });
                count += refundList.size();
                logger.info("refund data revise count:{}", count);
                if (refundList.size() < 200) {
                    break;
                }
                id = refundList.get(refundList.size() - 1).getId();
            }
            result.setStatus(true);
        } catch (Exception e) {
            logger.error("[refundData]failed!cause by:{}", e);
            result.setException(ExceptionConstants.SYSTEM_ERROR);
        }
        return result;
    }

    private void refundDataRevise(Refund refund) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        try {
            if (!Objects.equals(2, refund.getBizType())) {
                return ;
            }
            if (Objects.equals(2, refund.getStatus()) || Objects.equals(4, refund.getStatus())) {
                Map<String, Object> extraMap = refund.getExtraMap();
                if (!CollectionUtils.isEmpty(extraMap) && !org.springframework.util.StringUtils.isEmpty(extraMap.get("deal_at"))) {
                    String dealAt = extraMap.get("deal_at").toString();
                    if (!Objects.equals("0", dealAt) &&
                        !Objects.equals("0000-00-00 00:00:00", dealAt) &&
                        !Objects.equals("0000-00-00 00:00:00.000000", dealAt)) {
                        dealAt = dealAt.replace(".000000", "");
                        refund.setDealAt(simpleDateFormat.parse(dealAt));
                        refundDao.updateDealAt(refund);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("refund execute failed!refundNo:{},cause by:{}", refund.getRefundNo(), e);
        }
    }

    /**
     * 数据迁移后，需要执行该脚本进行数据处理
     * 1：订单商品与优惠信息填充
     * 2：添加订单号和用户ID索引信息
     * 3：同步ES
     * @param request
     * @return:
     * @Date: 2020/11/19 10:05 AM
     */
    @Override
    public Result orderDataRevise(OrderDataReviseRequest request) {
        Result result = new Result<>();
        int count = 0;
        try {
            OrderQuery orderQuery = new OrderQuery();
            // 生产环境换为203009
            orderQuery.setSellerId(11100L);
            orderQuery.setSize(1000);
            orderQuery.setMaxId(455237644781759233L);
            orderQuery.setOrderNo(request.getOrderNo());

            for (int i = 0; i < dbSize; i++) {
                for (int j = 0; j < tbSize; j++) {
                    Long lastId = 455237644681759233L;
                    for (;;) {
                        orderQuery.setLastId(lastId);
                        List<Order> orderList = commonManager.scanOrder(orderQuery, i, j);
                        if (CollectionUtils.isEmpty(orderList)) {
                            break;
                        }
                        orderList.forEach(order -> orderExecute(order));
                        count += orderList.size();
                        logger.info("[order_data_revise] total:{}条", count);
                        if (orderList.size() < 1000) {
                            break;
                        }
                        lastId = orderList.get(orderList.size() - 1).getId();
                        logger.info("[execute_lastId]:{}", lastId);

                        Result<String> redisData = redisManager.get("order_data_revise_key");
                        if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                            result.setStatus(true);
                            result.setData(lastId);
                            return result;
                        }
                    }
                }
            }
            result.setStatus(true);
        } catch (Exception e) {
            logger.error("[orderDataRevise]failed!cause by:{}", e);
            result.setException(ExceptionConstants.SYSTEM_ERROR);
        }
        return result;
    }

    private void orderExecute(Order order) {
        while (workQueue.remainingCapacity() < 10000) {
            logger.info("workQueue size{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executorService.submit(() -> {
            try {
                this.dataRevise(order);
            } catch (Exception e) {
                logger.error("[execute_order_revise]failed！cause by:{}", e);
            }
        });
    }

    private void dataRevise(Order order) throws Exception {
        List<OrderItem> orderItemList = orderItemDao.selectByOrderNo(order.getOrderNo(), order.getUserId());
        if (!CollectionUtils.isEmpty(orderItemList)) {
            if (orderItemList.size() > 10) {
                order.setItemInfo("TL");
            } else {
                List<InnerOrderItem> innerOrderItemList = Lists.newArrayListWithCapacity(orderItemList.size());
                orderItemList.forEach(orderItem -> {
                    InnerOrderItem innerOrderItem = mapper.map(orderItem, InnerOrderItem.class);
                    innerOrderItemList.add(innerOrderItem);
                });
                order.setItemInfo(JSON.toJSONString(innerOrderItemList));
            }
        }
        // 支付明细
        // insertPayDetails(order);
        orderDao.updateItemAndDiscount(order);

        OrderIndex orderNoIndex = mapper.map(order, OrderIndex.class);
        orderNoIndex.setOrderId(order.getId());
        orderNoIndex.setId(shardingKeyGenerator.generateSnowflakeNumKey());
        orderIndexDao.insert(orderNoIndex);

        // 记得变更ES索引
        searchManager.indexOrder(order, null);
    }

    /**
     * 批量更新
     * @param orderList
     * @param i
     * @param j
     * @return:
     * @Date: 2021/1/25 4:40 下午
     */
    private void dataReviseList(List<Order> orderList, int i, int j) {
        List<Order> updateOrderList = new ArrayList<>(orderList.size());
        List<OrderIndex> orderIndexList = new ArrayList<>(orderList.size());
        orderList.forEach(order -> {
            List<OrderItem> orderItemList = orderItemDao.selectByOrderNo(order.getOrderNo(), order.getUserId());
            if (!CollectionUtils.isEmpty(orderItemList)) {
                if (orderItemList.size() > 10) {
                    order.setItemInfo("TL");
                } else {
                    List<InnerOrderItem> innerOrderItemList = Lists.newArrayListWithCapacity(orderItemList.size());
                    orderItemList.forEach(orderItem -> {
                        InnerOrderItem innerOrderItem = mapper.map(orderItem, InnerOrderItem.class);
                        innerOrderItemList.add(innerOrderItem);
                    });
                    order.setItemInfo(JSON.toJSONString(innerOrderItemList));
                }
                updateOrderList.add(order);
            }
            OrderIndex orderNoIndex = mapper.map(order, OrderIndex.class);
            orderNoIndex.setOrderId(order.getId());
            orderNoIndex.setId(shardingKeyGenerator.generateSnowflakeNumKey());
            orderIndexList.add(orderNoIndex);
        });
        // 支付明细
//        insertPayDetails(order);
        // 批量更新
        commonManager.batchUpdateOrderItemAndDiscount(updateOrderList, i, j);
        // 订单索引
        orderIndexDao.insertList(orderIndexList);
        // ES
        searchManager.indexOrder(updateOrderList);
    }

    @Override
    public Result orderAdjustDataRevise(OrderDataReviseRequest request) {
        Result result = new Result<>();
        int count = 0;
        try {
            logger.info("[service_before]");
            OrderQuery orderQuery = new OrderQuery();
            orderQuery.setSize(200);
            orderQuery.setSellerId(49112L);
//            orderQuery.setStoreId(request.getStoreId());
            orderQuery.setOrderAtStart(request.getOrderAtStart());
            orderQuery.setOrderAtEnd(request.getOrderAtEnd());
            orderQuery.setOrderNo(request.getOrderNo());

            for (int i = 0; i < dbSize; i++) {
                for (int j = 0; j < tbSize; j++) {
                    Long lastId = null;
                    for (;;) {
                        orderQuery.setLastId(lastId);
                        List<Order> orderList = commonManager.scanOrder(orderQuery, i, j);
                        if (CollectionUtils.isEmpty(orderList)) {
                            break;
                        }
                        for (Order order : orderList) {
                            Map<String, Object> extraMap = order.getExtraMap();
                            if (!CollectionUtils.isEmpty(extraMap) && Objects.equals(1, extraMap.get("sync_erp_error"))) {
                                extraMap.put("sync_erp_error", 0);
                                order.setExtraMap(extraMap);
                                orderDao.updateFeatures(order);
                                count ++;
                                logger.info("update sync_erp_error order:{}条", count);
                            }
                            searchManager.indexOrder(order,null);
                        }
                        if (orderList.size() < 200) {
                            break;
                        }
                        lastId = orderList.get(orderList.size() - 1).getId();
                    }
                }
            }
            result.setStatus(true);
        } catch (Exception e) {
            logger.error("[orderAdjustDataRevise]failed!cause by:{}", e);
            result.setException(ExceptionConstants.SYSTEM_ERROR);
        }
        return result;
    }

    @Override
    public Result erpErrorData(OrderDataReviseRequest request) {
        Result result = new Result<>();
        int count = 0;
        try {
            logger.info("[service_before]");
            for (String orderNo : ListConst5.list) {
                OrderIndex orderIndex = orderIndexDao.selectOne(orderNo);
                if (orderIndex != null) {
                    Order order = orderDao.selectByOrderNo(orderIndex.getOrderNo(), orderIndex.getUserId());
                    if (order != null) {
                        Map<String, Object> extraMap = order.getExtraMap();
                        if (!CollectionUtils.isEmpty(extraMap) && Objects.equals(1, extraMap.get("sync_erp_error"))) {
                            extraMap.put("sync_erp_error", 0);
                            order.setExtraMap(extraMap);
                            orderDao.updateFeatures(order);
                            count++;
                            searchManager.indexOrder(order, null);
                            logger.info("update sync_erp_error order:{}条", count);
                        }
                    }
                }
            }
            result.setStatus(true);
        } catch (Exception e) {
            logger.error("[orderAdjustDataRevise]failed!cause by:{}", e);
            result.setException(ExceptionConstants.SYSTEM_ERROR);
        }
        return result;
    }
    
    private int updateDiscount(int count, List<Order> orderList) {
        List<Order> updateOrderList = new ArrayList<>(orderList.size());
        orderList.forEach(order -> {
            OrderDiscountQuery orderDiscountQuery = new OrderDiscountQuery();
            orderDiscountQuery.setOrderNo(order.getOrderNo());
            orderDiscountQuery.setUserId(order.getUserId());
            orderDiscountQuery.setDiscountType(6);
            List<OrderDiscount> discountList = orderDiscountDao.selectList(orderDiscountQuery);
            if (!CollectionUtils.isEmpty(discountList)) {
                updateOrderList.add(order);
            }
        });
        if (!CollectionUtils.isEmpty(updateOrderList)) {
            updateOrderList.forEach(update -> {
                update.setDiscountAmount(update.getDiscountAmount() - update.getFreightAmount());
                orderDao.updateDiscountAmount(update);
            });
            count += updateOrderList.size();
            logger.info("[order_discount_data_revise] total:{}条", count);
        }
        return count;
    }

    /**
     * 删除ES重复的数据
     * 多人点餐场景
     * 线上目前不存在这种情况
     * @return:
     * @Date: 2020/11/19 10:04 AM
     */
    @Override
    public Result deleteEsOrder() {
        Result result = new Result<>();
        OrderQuery orderQuery = getOrderQuery();
        int count = 0;
        try {
            for (int i = 26; i < dbSize; i++) {
                for (int j = 0; j < tbSize; j++) {
                    if (i == 26 && j < 18) {
                        continue;
                    }
                    Long lastId = null;
                    for (;;) {
                        orderQuery.setLastId(lastId);
                        List<Order> orderList = commonManager.scanOrder(orderQuery, i, j);
                        if (CollectionUtils.isEmpty(orderList)) {
                            break;
                        }
                        for (Order order : orderList) {
                            if (!CollectionUtils.isEmpty(order.getExtraMap())) {
                                Object masterId = order.getExtraMap().get("masterId");
                                if (masterId != null && !Objects.equals(Long.valueOf(masterId.toString()), order.getId())) {
                                    continue;
                                }
                            }
                            OrderUserRelationQuery query = new OrderUserRelationQuery();
                            query.setOrderNo(order.getOrderNo());
                            query.setPageNo(1);
                            query.setPageSize(100);
                            List<OrderUserRelation> orderUserRelations = relationDao.selectList(query);
                            if (!CollectionUtils.isEmpty(orderUserRelations)) {
                                for (OrderUserRelation relation : orderUserRelations) {
                                    if (Objects.equals(1, relation.getIsRoot())) {
                                        Order subOrder =
                                            orderDao.selectByOrderNo(relation.getOrderNo(), relation.getUserId());
                                        searchManager.deleteOrder(subOrder.getId(), subOrder.getSellerId());
                                        count++;
                                        logger.info("delete_sub_order count:{}，i:{}, j:{}", count, i, j);
                                    }
                                }
                            }
                        }
                        lastId = orderList.get(orderList.size() - 1).getId();
                        if (orderList.size() < 200) {
                            break;
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("[deleteEsOrder]failed!cause by:{}", e);
            result.setException(ExceptionConstants.SYSTEM_ERROR);
        }
        return result;
    }

    private OrderQuery getOrderQuery() {
        OrderQuery query = new OrderQuery();
        query.setSize(200);
        query.setSortFlag(1);
        query.setOrderSubType(2);
        query.setUpdatedAtEnd(new Date(1673539200000L));
        query.setUpdatedAtStart(new Date(1661270400000L));
        return query;
    }

    /**
     * 生产环境按照时间迁移
     * @return:
     * @Date: 2020/10/10 10:16 AM
     */
    private OrderQuery buildOrderQuery() {
        Long startAt = 1598889601000L;
        Long endAt = 1604937600000L;
        OrderQuery orderQuery = new OrderQuery();
        orderQuery.setSize(1000);
        orderQuery.setOrderAtStart(new Date(startAt));
        orderQuery.setOrderAtEnd(new Date(endAt));
        orderQuery.setMaxId(536120629837971457L);
        return orderQuery;
    }

    private OrderQuery buildOrderQuery1() {
        Long startAt = 1598889601000L;
        Long endAt = 1604937600000L;
        OrderQuery orderQuery = new OrderQuery();
        orderQuery.setSize(1000);
        orderQuery.setOrderAtStart(new Date(startAt));
        orderQuery.setOrderAtEnd(new Date(endAt));
        orderQuery.setMaxId(536120629837971457L);
        return orderQuery;
    }

    
    @Override
    public Result orderItemGoodsId() {
        Result result = new Result<>();
        int count = 0;
        try {
            List<String> list = CollectionConstants.list;
            if (!CollectionUtils.isEmpty(list)) {
                for (String str : list) {
                    String[] split = str.split("#");
                    String orderNo = split[0];
                    Long goodsId = Long.valueOf(split[1]);
                    String itemName = split[2];
                    OrderIndex orderIndex = orderIndexDao.selectOne(orderNo);
                    if (orderIndex != null) {
                        setItemInfo(goodsId, itemName, orderIndex);
                        setOrderItem(goodsId, itemName, orderIndex);
                        count++;
                    }
                }
                logger.info("update order item count:{}", count);
            }
            result.setStatus(true);
        } catch (Exception e) {
            logger.error("[orderItemGoodsId]failed!cause by:{}", e);
            result.setException(ExceptionConstants.SYSTEM_ERROR);
        }
        return result;
    }

    private void setItemInfo(Long goods, String itemName, OrderIndex orderIndex) {
        Order order = orderDao.selectByOrderNo(orderIndex.getOrderNo(), orderIndex.getUserId());
        String itemInfo = order.getItemInfo();
        if (!StringUtils.isEmpty(itemInfo)) {
            List<OrderItem> orderItemList = JSON.parseArray(itemInfo, OrderItem.class);
            orderItemList.forEach(orderItem -> {
                if (Objects.equals(orderItem.getItemName(), itemName) && orderItem.getGoodsId() == 0) {
                    orderItem.setUserId(orderIndex.getUserId());
                    orderItem.setGoodsId(goods);
                }
            });
            order.setItemInfo(JSON.toJSONString(orderItemList));
        }
        orderDao.update(order);
    }

    private void setOrderItem(Long goods, String itemName, OrderIndex orderIndex) {
        List<OrderItem> itemList = orderItemDao.selectByOrderNo(orderIndex.getOrderNo(), orderIndex.getUserId());
        if (!CollectionUtils.isEmpty(itemList)) {
            itemList.forEach(orderItem -> {
                if (Objects.equals(orderItem.getItemName(), itemName) && orderItem.getGoodsId() == 0) {
                    orderItem.setUserId(orderIndex.getUserId());
                    orderItem.setGoodsId(goods);
                    orderItemDao.update(orderItem);
                }
            });
        }
    }

    @Override
    public Result deleteOrder(OrderDataReviseRequest request) {
        Result result = new Result<>();
        int count = 0;
        OrderQuery orderQuery = buildRoutingQuery(request);
        try {
            for (int i = 0; i < dbSize; i++) {
                for (int j = 0; j < tbSize; j++) {
                    Long lastId = null;
                    for (;;) {
                        orderQuery.setLastId(lastId);
                        List<Long> idList = commonManager.scanOrderId(orderQuery, i, j);
                        if (CollectionUtils.isEmpty(idList)) {
                            break;
                        }
                        List<Order> orderList = commonManager.listOrderById(idList, i, j);
                        if(request.getExec() == 1){
                            checkOrderAndAddQuene3(orderList, i, j);
                        }
                        count += orderList.size();
                        logger.info("query_order:{}条, lastId:{}", count, lastId);
                        Thread.sleep(20);
                        if (orderList.size() < 200) {
                            break;
                        }
                        lastId = orderList.get(orderList.size() - 1).getId();
                        Result<String> redisData = redisManager.get("delete_order_key_02");
                        if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                            result.setStatus(true);
                            result.setData(lastId);
                            return result;
                        }
                    }
                }
            }
            result.setStatus(true);
        } catch (Exception e) {
            logger.error("[orderRouting]failed!cause by:{}", e);
            result.setException(ExceptionConstants.SYSTEM_ERROR);
        }
        return result;
    }



    @Override
    public Result deleteRefund(OrderDataReviseRequest request) {
        Result result = new Result<>();
        return result;
    }
    /**
     * 先将需要处理的数据打标
     * @param orderList
     * @return:
     * @Date: 2020/12/14 11:35 AM
     */
    private void checkOrderAndAddQuene1(List<Order> orderList) {
        while (workQueue.remainingCapacity() < 50) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executorService.submit(() -> {
            try {
                List<Long> idList = orderList.stream().map(Order::getId).collect(Collectors.toList());
                commonManager.batchDeleteOrder(idList, 0, 0);
            } catch (Exception e) {
                logger.error("[quene_order_routing]failed！cause by:{}", e);
            }
        });
    }

    /**
     * 记得更换sql中的 is_deleted = 100
     * 1.1 重新路由，插入一条新的值
     * 1.2 更新原数据
     * 2 变更订单索引表
     * 3 同步ES
     * @param orderList
     * @return:
     * @Date: 2020/12/11 4:53 PM
     */
    private void checkOrderAndAddQuene2(List<Order> orderList) {
        while (workQueue.remainingCapacity() < 20) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executorService.submit(() -> {
            try {
                List<Order> updateOrderList = new ArrayList<>(orderList.size());
                orderList.forEach(order -> {
                    if (order.getUserId() == 0 && order.getStoreId() != 0 && order.getIsDeleted() == 100) {
                        Long newUserId = 0 - order.getStoreId();
                        order.setUserId(newUserId);
                        if (reRouting(newUserId)) {
                            order.setSyncFlag(0);
                            orderDao.insert(order);
                        } else {
                            orderDao.updateUserId(order.getId(), 0L, order.getUserId());
                        }
                        orderIndexDao.update(buildOrderIndex(order));
                        updateOrderList.add(order);
                    }
                });
                if (!CollectionUtils.isEmpty(updateOrderList)) {
                    searchManager.indexOrder(updateOrderList);
                }
            } catch (Exception e) {
                logger.error("[quene_order_routing]failed！cause by:{}", e);
            }
        });
    }

    /**
     * （物理）删除表中的无效数据
     * @param orderList
     * @return:
     * @Date: 2020/12/14 11:35 AM
     */
    public void checkOrderAndAddQuene3(List<Order> orderList, int i, int j) {
        while (workQueue.remainingCapacity() < 20) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executorService.submit(() -> {
            try {
                // 删除订单
                List<Long> idList = orderList.stream().map(Order::getId).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(idList)) {
                    commonManager.deleteOrder(idList, i, j);
                }
                List<String> orderNoList = orderList.stream().map(Order::getOrderNo).collect(Collectors.toList());
                // 删除商品
                if (!CollectionUtils.isEmpty(orderNoList)) {
                    commonManager.deleteItem(orderNoList, i, j);
                }
                // 删除退款单
                if (!CollectionUtils.isEmpty(orderNoList)) {
                    refundDao.deleteByOrderNos(orderNoList);
                }
            } catch (Exception e) {
                logger.error("[quene_order_routing]failed！cause by:{}", e);
            }
        });
    }

    /**
     * 重新打标商品与优惠数据
     * @param orderList
     * @return:
     * @Date: 2020/12/14 11:35 AM
     */
    private void checkOrderAndAddQuene4(List<Order> orderList) {
        while (workQueue.remainingCapacity() < 20) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executorService.submit(() -> {
            try {
                // 商品信息打标
                List<String> orderNoList = orderList.stream().map(Order::getOrderNo).collect(Collectors.toList());
                commonManager.updateItemDeleted(orderNoList, 0, 0);
                // 优惠信息打标
                List<String> discountOrderNoList = new ArrayList<>(orderNoList.size());
                orderList.forEach(order -> {
                    if (!StringUtils.isEmpty(order.getDiscountInfo())) {
                        discountOrderNoList.add(order.getOrderNo());
                    }
                });
                if (!CollectionUtils.isEmpty(discountOrderNoList)) {
                    commonManager.updateDiscountDeleted(discountOrderNoList,0, 0);
                }
            } catch (Exception e) {
                logger.error("[quene_order_routing]failed！cause by:{}", e);
            }
        });
    }

    /**
     * 重新打标商品与优惠数据
     * @param order
     * @return:
     * @Date: 2020/12/14 11:35 AM
     */
    private void checkOrderAndAddQuene5(Order order) {
        while (workQueue.remainingCapacity() < 10000) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executorService.submit(() -> {
            try {
                Long userId = 0 - order.getStoreId();
                ArrayList<String> orderNo = Lists.newArrayList(order.getOrderNo());
                // 重定向商品
                List<OrderItem> itemList = commonManager.scanOrderItem(orderNo, 0, 0);
                if (!CollectionUtils.isEmpty(itemList)) {
                    itemList.forEach(item -> {
                        item.setUserId(userId);
                    });
                }
                orderItemDao.inserts(itemList);
                // 重定向优惠
                if (!StringUtils.isEmpty(order.getDiscountInfo())) {
                    List<OrderDiscount> discountList = commonManager.scanOrderDiscount(orderNo, 0, 0);
                    if (!CollectionUtils.isEmpty(discountList)) {
                        discountList.forEach(discount -> {
                            discount.setUserId(userId);
                        });
                        orderDiscountDao.inserts(discountList);
                    }
                }
            } catch (Exception e) {
                logger.error("[quene_order_routing]failed！cause by:{}", e);
            }
        });
    }

    /**
     * 重新打标商品与优惠数据
     * @param orderList
     * @return:
     * @Date: 2020/12/14 11:35 AM
     */
    private void checkOrderAndAddQuene6(List<Order> orderList, int i,int j) {
        while (workQueue.remainingCapacity() < 50) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executorService.submit(() -> {
            try {
                if (!CollectionUtils.isEmpty(orderList)) {
                    List<Long> idList = orderList.stream().map(Order::getId).collect(Collectors.toList());
                    commonManager.batchDeleteOrder(idList, i, j);
                    orderList.forEach(order -> {
                        order.setIsDeleted(0);
                    });
                    searchManager.indexOrder(orderList);
                }
            } catch (Exception e) {
                logger.error("[quene_order_routing]failed！cause by:{}", e);
            }
        });
    }

    /**
     * 更新1库0表中商品与优惠中的user_id
     * @param order
     * @return:
     * @Date: 2020/12/14 11:35 AM
     */
    private void checkOrderAndAddQuene7(Order order) {
        while (workQueue.remainingCapacity() < 50) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executorService.submit(() -> {
            try {
                commonManager.updateItemUserId(order.getOrderNo(), order.getUserId(), 0, 0);
                if (!StringUtils.isEmpty(order.getDiscountInfo())) {
                    commonManager.updateDiscountUserId(order.getOrderNo(), order.getUserId(), 0, 0);
                }
                searchManager.indexOrder(order, null);
            } catch (Exception e) {
                logger.error("[quene_order_routing]failed！cause by:{}", e);
            }
        });
    }
    
    private OrderIndex buildOrderIndex(Order order) {
        OrderIndex orderIndex = new OrderIndex();
        orderIndex.setOrderNo(order.getOrderNo());
        orderIndex.setUserId(order.getUserId());
        return orderIndex;
    }

    private OrderQuery buildRoutingQuery(OrderDataReviseRequest request) {
        OrderQuery orderQuery = new OrderQuery();
        orderQuery.setSellerId(207720L);
        orderQuery.setSize(200);
        orderQuery.setOrderAtStart(new Date(1736265600000L));
        return orderQuery;
    }

    /**
     * 订单信息isDeleted字段修改
     * @return:
     * @Date: 2020/12/10 2:29 PM
     */
    private OrderQuery buildRoutingQuery1(OrderDataReviseRequest request) {
        OrderQuery orderQuery = new OrderQuery();
        orderQuery.setSpecialUserId(1L);
        orderQuery.setMaxId(465533789477552129L);
        orderQuery.setExcludeStoreId(1);
        orderQuery.setSize(500);
        orderQuery.setOrderAtStart(new Date(1590940800000L));
        orderQuery.setOrderAtEnd(new Date(1590940800000L));
        return orderQuery;
    }

    private boolean reRouting(Long userId) {
        if (userId < 0) {
            userId = 0 - userId;
        }
        Long modDb = userId % dbSize;
        Long modTb = userId / dbSize % tbSize;
        if (modDb == 0 && modTb == 0) {
            return false;
        }
        return true;
    }

    @Override
    public Result orderPayType(OrderDataReviseRequest request) {
        Result result = new Result<>();
        int count = 0;
        OrderQuery orderQuery = buildOrderPayTypeQuery(request);
        try {
            for (int i = 0; i < dbSize; i++) {
                for (int j = 0; j < tbSize; j++) {
                    Long lastId = null;
                    for (;;) {
                        orderQuery.setLastId(lastId);
                        List<Long> orderIdList = commonManager.scanOrderId(orderQuery, i, j);
                        if (CollectionUtils.isEmpty(orderIdList)) {
                            break;
                        }
                        List<Order> orderList = commonManager.listOrderById(orderIdList, i, j);
                        List<Order> newOrderList = new ArrayList<>(orderList.size());
                        for (Order order : orderList) {
                            if (Objects.equals(1, order.getPayStatus())) {
                                newOrderList.add(order);
                            }
                        }
//                        orderPayTypeQuene(newOrderList, i, j);
                        count += orderIdList.size();
                        logger.info("orderPayType:{}条", count);
                        if (orderIdList.size() < 200) {
                            break;
                        }
                        lastId = orderList.get(orderList.size() - 1).getId();
                        logger.info("lastId:{}", lastId);
                        Result<String> redisData = redisManager.get("order_pay_type");
                        if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                            result.setStatus(true);
                            result.setData(lastId);
                            return result;
                        }
                    }
                }
            }
            result.setStatus(true);
        } catch (Exception e) {
            logger.error("[orderPayType]failed!cause by:{}", e);
            result.setException(ExceptionConstants.SYSTEM_ERROR);
        }
        return result;
    }

    @Override
    public Result orderRefundType(OrderDataReviseRequest request) {
        Result result = new Result<>();
        int count = 0;
        // 生产环境换ID
        Long lastId = 454237644693900981L;
        RefundQuery refundQuery = buildOrderRefundTypeQuery(request);
        try {
            for (;;) {
                refundQuery.setLastId(lastId);
                List<Refund> refundList = refundDao.selectList(refundQuery);
                if (CollectionUtils.isEmpty(refundList)) {
                    break;
                }
                orderRefundTypeQuene(refundList);
                count += refundList.size();
                logger.info("orderRefundType:{}条", count);
                if (refundList.size() < 200) {
                    break;
                }
                lastId = refundList.get(refundList.size() - 1).getId();
                logger.info("lastId:{}", lastId);
                Result<String> redisData = redisManager.get("order_refund_type");
                if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                    result.setStatus(true);
                    result.setData(lastId);
                    return result;
                }
            }
            result.setStatus(true);
        } catch (Exception e) {
            logger.error("[orderRefundType]failed!cause by:{}", e);
            result.setException(ExceptionConstants.SYSTEM_ERROR);
        }
        return result;
    }

    private void orderRefundTypeQuene(List<Refund> refundList) {
        while (workQueue.remainingCapacity() < 50) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executorService.submit(() -> {
            try {
                List<OrderRefundDetails> refundDetailsList = new ArrayList<>(refundList.size());
                for (Refund refund : refundList) {
                    // 免支付
                    List<InnerOrderRefundDetail> detailsList = new ArrayList<>();
                    if (refund.getRefundAmount() == 0 && refund.getWalletAmount() == 0) {
                        OrderRefundDetails refundDetails = buildRefundDetailParam(refund, refund.getRefundAmount(), 0, 1);
                        refundDetailsList.add(refundDetails);
                        detailsList.add(mapper.map(refundDetails, InnerOrderRefundDetail.class));
                    }
                    if (refund.getRefundAmount() != 0) {
                        OrderRefundDetails refundDetails = buildRefundDetailParam(refund, refund.getRefundAmount(),0, 0);
                        refundDetailsList.add(refundDetails);
                        detailsList.add(mapper.map(refundDetails, InnerOrderRefundDetail.class));
                    }
                    if (refund.getWalletAmount() != 0) {
                        OrderRefundDetails refundDetails = buildRefundDetailParam(refund, refund.getWalletAmount(), 1, 0);
                        refundDetailsList.add(refundDetails);
                        detailsList.add(mapper.map(refundDetails, InnerOrderRefundDetail.class));
                    }
                    refund.setRefundDetailInfo(JSON.toJSONString(detailsList));
                    refundDao.updateRefundDetail(refund);
                }
                refundDetailsDao.insertList(refundDetailsList);
            } catch (Exception e) {
                logger.error("[orderRefundTypeQuene]failed！cause by:{}", e);
            }
        });
    }

    private OrderRefundDetails buildRefundDetailParam(Refund refund, Integer amount, Integer payType, int noPay) {
        OrderRefundDetails refundDetails = new OrderRefundDetails();
        refundDetails.setId(shardingKeyGenerator.generateSnowflakeNumKey());
        refundDetails.setOrderNo(refund.getOrderNo());
        refundDetails.setUserId(refund.getUserId());
        refundDetails.setRefundNo(refund.getRefundNo());
        refundDetails.setSellerId(refund.getSellerId());
        refundDetails.setStoreId(refund.getStoreId());
        refundDetails.setRefundAmount(amount);
        if (noPay == 1) {
            refundDetails.setPayType(0);
            return refundDetails;
        }
        if (payType == 0) {
            Order order = orderDao.selectByOrderNo(refund.getOrderNo(), refund.getUserId());
            if (order != null) {
                if (order != null) {
                    payType = order.getPayType();
                    if (payType == 0) {
                        if (alipaySourceList.contains(order.getSource())) {
                            payType = 3;
                        } else {
                            payType = 2;
                        }
                    }
                    if (alipayList.contains(payType)) {
                        payType = 3;
                    }
                    if (wechatList.contains(payType)) {
                        payType = 2;
                    }
                    if (payType == 6514) {
                        payType = 15;
                    }
                }
            } else {
                payType = 2;
            }
        }
        refundDetails.setPayType(payType);
        return refundDetails;
    }

    private static List<Integer> alipayList = new ArrayList<>();

    private static List<Integer> wechatList = new ArrayList<>();

    private static List<Integer> alipaySourceList = new ArrayList<>();

    static {
        wechatList.add(6508);
        wechatList.add(6512);
        wechatList.add(7508);
        wechatList.add(8508);
        wechatList.add(9508);
        wechatList.add(8608);
        wechatList.add(8708);
        wechatList.add(8108);

        alipayList.add(6509);
        alipayList.add(6513);
        alipayList.add(7509);
        alipayList.add(8509);
        alipayList.add(9509);
        alipayList.add(8609);
        alipayList.add(8709);
        alipayList.add(8109);

        alipaySourceList.add(2);
        alipaySourceList.add(3);
        alipaySourceList.add(6);
        alipaySourceList.add(7);
    }

    private void orderPayTypeQuene(List<Order> orderList, int i, int j) {
        while (workQueue.remainingCapacity() < 20) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executorService.submit(() -> {
            try {
                if (CollectionUtils.isEmpty(orderList)) {
                    return;
                }
                List<OrderPayDetails> payDetailsList = new ArrayList<>();
                orderList.forEach(order -> {
//                    setPayDetails(order, payDetailsList);
                });
                Map<String, List<OrderPayDetails>> payTypeMap =
                    payDetailsList.stream().collect(Collectors.groupingBy(OrderPayDetails::getOrderNo));
                for (Order order : orderList) {
                    if (!CollectionUtils.isEmpty(payTypeMap.get(order.getOrderNo()))) {
                        List<OrderPayDetails> orderPayDetails = payTypeMap.get(order.getOrderNo());
                        order.setPayDetailInfo(JSON.toJSONString(orderPayDetails));
                    }
                }
                commonManager.batchUpdatePayDetailInfo(orderList, i, j);
                payDetailsDao.insertList(payDetailsList);
//                List<OrderIndex> indexList = new ArrayList<>();
//                for (Order order : orderList) {
//                    OrderIndex orderIndex = new OrderIndex();
//                    orderIndex.setId(shardingKeyGenerator.generateSnowflakeNumKey());
//                    orderIndex.setOrderId(order.getId());
//                    orderIndex.setOrderNo(order.getOrderNo());
//                    orderIndex.setUserId(order.getUserId());
//                    orderIndex.setBizType(5);
//                    indexList.add(orderIndex);
//                }
//                orderIndexDao.insertList(indexList);
            } catch (Exception e) {
                logger.error("[orderPayTypeQueue]failed！cause by:{}", e);
            }
        });
    }

    private void setPayDetails(Order order, List<OrderPayDetails> payDetailsList) {
        Integer payType = order.getPayType();
        String payInfo = order.getPayInfo();
        if (!StringUtils.isEmpty(payInfo)) {
            Map<String, Object> payInfoMap = JSON.parseObject(payInfo);
            Integer useWallet = Objects.nonNull(payInfoMap.get("use_wallet")) ?
                    Integer.valueOf(payInfoMap.get("use_wallet").toString()) : null;
            String amountStr = Objects.nonNull(payInfoMap.get("amount")) ? payInfoMap.get("amount").toString() : "0";
            Integer amount = 0;
            if (amountStr.contains(".")) {
                amount = new BigDecimal(amountStr).multiply(new BigDecimal(100)).intValue();
            }else {
                amount = Integer.valueOf(amountStr);
            }

            Integer walletAmount = 0;
            String walletAmountStr = Objects.nonNull(payInfoMap.get("wallet_amount")) ?
                    payInfoMap.get("wallet_amount").toString() : "0";
            if (walletAmountStr.contains(".")) {
                walletAmount = new BigDecimal(walletAmountStr).multiply(new BigDecimal(100)).intValue();
            }else {
                walletAmount = Integer.valueOf(walletAmountStr);
            }

            // from_system = 1  --> payType = 7 在线支付
            if (Objects.equals(1, order.getFromSystem())) {
                order.setPayType(7);
                OrderPayDetails payDetails = buildPayDetails(7, order, amount);
                payDetailsList.add(payDetails);
                return;
            }
            // 余额 + 三方
            if (walletAmount > 0) {
                // 如果amount = 0 那么就是一种支付方式：余额支付（4），如果大于0，那么就是混合支付 payType = 9 混合支付
                if (amount == 0) {
                    order.setPayType(4);
                    OrderPayDetails payDetails = buildPayDetails(4, order, walletAmount);
                    payDetailsList.add(payDetails);
                    return;
                }
                // 混合支付
                if (amount > 0) {
                    order.setPayType(9);
                    OrderPayDetails payDetails1 = buildPayDetails(4, order, walletAmount);
                    Integer newPayType = mapThirdPay(payType);
                    OrderPayDetails payDetails2 = buildPayDetails(newPayType, order, amount);
                    payDetailsList.add(payDetails1);
                    payDetailsList.add(payDetails2);
                    return;
                }
            }
            // 现金 + 三方支付
            if (Objects.equals(19, order.getSource())) {
                Object cashAmountObj = payInfoMap.get("cash_amount");
                Object thirdAmountObj = payInfoMap.get("third_amount");
                if (Objects.nonNull(cashAmountObj) && Objects.nonNull(thirdAmountObj)) {
                    Integer cashAmount = Integer.valueOf(cashAmountObj.toString());
                    Integer thirdAmount = Integer.valueOf(thirdAmountObj.toString());
                    if (cashAmount > 0 && thirdAmount > 0) {
                        // 混合支付场景 现金 + 三方支付 payType = 99
                        order.setPayType(99);
                        OrderPayDetails cashPay = buildPayDetails(12, order, cashAmount);
                        OrderPayDetails thirdPay = buildPayDetails(mapThirdPay(payType), order, thirdAmount);
                        payDetailsList.add(cashPay);
                        payDetailsList.add(thirdPay);
                        return;
                    }
                }
            }
            // 三方支付
            if (amount > 0) {
                Integer newPayType = mapThirdPay(payType);
                order.setPayType(newPayType);
                OrderPayDetails payDetails = buildPayDetails(newPayType, order, amount);
                payDetailsList.add(payDetails);
                return;
            }
            // 免支付 payType = 16 新餐饮
            if (Objects.equals(0, order.getActualAmount())) {
                order.setPayType(16);
                OrderPayDetails payDetails = buildPayDetails(16, order, 0);
                payDetailsList.add(payDetails);
                return;
            }
            // 未匹配到的支付类型
            OrderPayDetails payDetails = buildPayDetails(mapThirdPay(order.getPayType()), order, amount);
            payDetailsList.add(payDetails);
        }
    }

    private Integer mapThirdPay(Integer payType) {
        if (alipayList.contains(payType)) {
            payType = 2;
            return payType;
        }
        if (wechatList.contains(payType)) {
            payType = 1;
            return payType;
        }
        // 云闪付
        if (Objects.equals(6514, payType)) {
            payType = 15;
            return payType;
        }
        if (Objects.equals(4, payType)) {
            payType = 12;
            return payType;
        }
        if (Objects.equals(10, payType)) {
            payType = 13;
            return payType;
        }
        if (Objects.equals(13, payType)) {
            payType = 10;
            return payType;
        }
        if (Objects.equals(12, payType)) {
            payType = 16;
            return payType;
        }
        return payType;
    }

    private OrderPayDetails buildPayDetails(Integer payType, Order order, Integer amount) {
        OrderPayDetails payDetails = new OrderPayDetails();
        payDetails.setId(shardingKeyGenerator.generateSnowflakeNumKey());
        payDetails.setOrderNo(order.getOrderNo());
        payDetails.setUserId(order.getUserId());
        payDetails.setSellerId(order.getSellerId());
        payDetails.setStoreId(order.getStoreId());
        payDetails.setStoreId(order.getStoreId());
        payDetails.setAmount(amount);
        payDetails.setPayType(payType);
        payDetails.setPayNo(!StringUtils.isEmpty(order.getPayNo()) ? order.getPayNo() : "");
        payDetails.setThirdPayNo(!StringUtils.isEmpty(order.getThirdPayNo()) ? order.getThirdPayNo() : "");
        payDetails.setOrderAt(order.getOrderAt());
        payDetails.setPayAt(Objects.nonNull(order.getPayAt()) ? order.getPayAt() : order.getOrderAt());
        payDetails.setOrderType(order.getOrderType());
        payDetails.setSource(Objects.nonNull(order.getSource()) ? order.getSource() : 0);
        return payDetails;
    }

    /**
     * 变更时间
     * @param request
     * @return:
     * @Date: 2021/1/18 10:33 上午
     */
    private OrderQuery buildOrderPayTypeQuery(OrderDataReviseRequest request) {
        Long startAt = 1610899201000L;
        Long endAt = 1611590400000L;
        OrderQuery orderQuery = new OrderQuery();
        orderQuery.setSize(200);
//        orderQuery.setPayStatus(1);
        orderQuery.setSellerId(205960L);
//        orderQuery.setOrderAtStart(new Date(startAt));
//        orderQuery.setOrderAtEnd(new Date(endAt));
        orderQuery.setOrderNo(request.getOrderNo());
        return orderQuery;
    }

    /**
     * 变更时间
     * 乡村基数据迁移后，执行一遍脚本
     * @param request
     * @return:
     * @Date: 2021/1/18 10:33 上午
     */
    private RefundQuery buildOrderRefundTypeQuery(OrderDataReviseRequest request) {
        Long startAt = 1598889600000L;
//        Long endAt = 1590940800000L;
        RefundQuery refundQuery = new RefundQuery();
        refundQuery.setSize(200);
        refundQuery.setBizType(1);
        refundQuery.setOrderAtStart(new Date(startAt));
//        refundQuery.setOrderAtEnd(new Date(endAt));
        refundQuery.setOrderNo(request.getOrderNo());
        return refundQuery;
        // 乡村基参数 设置lastID
//        refundQuery.setMaxId(455237644781759233L);
//        refundQuery.setSellerId(50161L);
    }

    @Override
    public Result updateRefundPayType(OrderDataReviseRequest request) {
        Result result = new Result<>();
        int count = 0;
        Long lastId = 483632265868349440L;
        RefundQuery refundQuery = buildOrderRefundTypeQuery1(request);
        try {
            for (;;) {
                refundQuery.setLastId(lastId);
                List<Refund> refundList = refundDao.selectList(refundQuery);
                if (CollectionUtils.isEmpty(refundList)) {
                    break;
                }
                refundList.forEach(refund -> {
                    updatePayTypeQueue(refund);
                });
                count += refundList.size();
                logger.info("updateRefundPayType:{}条", count);
                if (refundList.size() < 200) {
                    break;
                }
            }
            result.setStatus(true);
        } catch (Exception e) {
            logger.error("[updateRefundPayType]failed!cause by:{}", e);
            result.setException(ExceptionConstants.SYSTEM_ERROR);
        }
        return result;
    }

    private void updatePayTypeQueue(Refund refund) {
        while (workQueue.remainingCapacity() < 10000) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executorService.submit(() -> {
            try {
                Order order = orderDao.selectByOrderNo(refund.getOrderNo(), refund.getUserId());
                if (order != null) {
                    refund.setPayType(order.getPayType());
                    refundDao.updatePayType(refund);
                }
            } catch (Exception e) {
                logger.error("[updatePayTypeQueue]failed！cause by:{}", e);
            }
        });
    }

    private RefundQuery buildOrderRefundTypeQuery1(OrderDataReviseRequest request) {
        Long startAt = 1609430400000L;
        Long endAt = 1612620000000L;
        RefundQuery refundQuery = new RefundQuery();
        refundQuery.setSize(200);
        refundQuery.setBizType(1);
        refundQuery.setUpdatedAtStart(new Date(startAt));
        refundQuery.setUpdatedAtEnd(new Date(endAt));
        refundQuery.setOrderNo(request.getOrderNo());
        return refundQuery;
    }

    @Override
    public Result updateRefundDealAt(OrderDataReviseRequest request) {
        Result result = new Result<>();
        int count = 0;
        Long lastId = 424237643681776521L;
        RefundQuery refundQuery = buildOrderRefundDealAt(request);
        try {
            for (;;) {
                refundQuery.setLastId(lastId);
                List<Refund> refundList = refundDao.selectList(refundQuery);
                if (CollectionUtils.isEmpty(refundList)) {
                    break;
                }
                updateDealAtQueue1(refundList);
                count += refundList.size();
                logger.info("updateRefundDealAt:{}条", count);
                if (refundList.size() < 200) {
                    break;
                }
                lastId = refundList.get(refundList.size() - 1).getId();
            }
        } catch (Exception e) {
            logger.error("[updateRefundDealAt]failed!cause by:{}", e);
            result.setException(ExceptionConstants.SYSTEM_ERROR);
        }
        return result;
    }

    private void updateDealAtQueue(List<Refund> refundList) {
        while (workQueue.remainingCapacity() < 20) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executorService.submit(() -> {
            try {
                List<Refund> updateRefundList = new ArrayList<>(refundList.size());
                refundList.forEach(refund -> {
                    if (!org.springframework.util.StringUtils.isEmpty(refund.getFeatures())) {
                        Map map = JSON.parseObject(refund.getFeatures(), Map.class);
                        if (Objects.nonNull(map.get("deal_at"))) {
                            Long dealAt = Long.valueOf(map.get("deal_at").toString());
                            Date dealTime;
                            if (dealAt == 0) {
                                dealTime = refund.getUpdatedAt();
                            } else {
                                dealTime = new Date(dealAt);
                            }
                            refund.setDealAt(dealTime);
                        } else {
                            refund.setDealAt(refund.getUpdatedAt());
                        }
                        updateRefundList.add(refund);
                    }
                });
                if (!CollectionUtils.isEmpty(updateRefundList)) {
                    refundDao.batchUpdateDealAt(updateRefundList);
                }
            } catch (Exception e) {
                logger.error("[updateDealAtQueue]failed！cause by:{}", e);
            }
        });
    }

    private void updateDealAtQueue1(List<Refund> refundList) {
        while (workQueue.remainingCapacity() < 20) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executorService.submit(() -> {
            try {
                List<Refund> updateList = new ArrayList<>();
                refundList.forEach(refund -> {
                    Order order = orderDao.selectByOrderNo(refund.getOrderNo(), refund.getUserId());
                    if (order.getFromSystem() == 1) {
                        refund.setFromSystem(order.getFromSystem());
                        updateList.add(refund);
                    }
                });
                if (!CollectionUtils.isEmpty(updateList)) {
                    refundDao.batchUpdateFromSystem(updateList);
                }
            } catch (Exception e) {
                logger.error("[updateDealAtQueue]failed！cause by:{}", e);
            }
        });
    }

    private RefundQuery buildOrderRefundDealAt(OrderDataReviseRequest request) {
        // 2020-01-01 00:00:00
        Long startAt = 1577808000000L;
        // 2021-02-25 22:00:00
        Long endAt = 1614952800000L;
        RefundQuery refundQuery = new RefundQuery();
        refundQuery.setSize(200);
        refundQuery.setBizType(1);
        refundQuery.setUpdatedAtStart(new Date(startAt));
        refundQuery.setUpdatedAtEnd(new Date(endAt));
        // 去除
//        refundQuery.setExcDealAt(1);
        refundQuery.setOrderNo(request.getOrderNo());
        return refundQuery;
    }

    @Override
    public Result updatePayInfo(OrderDataReviseRequest request) {
        Result result = new Result<>();
        int count = 0;
        OrderQuery orderQuery = buildUpdatePayInfo(request);
        try {
            for (int i = 0; i < dbSize; i++) {
                for (int j = 0; j < tbSize; j++) {
                    for (;;) {
                        List<Order> orderList = commonManager.scanOrder(orderQuery, i, j);
                        if (CollectionUtils.isEmpty(orderList)) {
                            break;
                        }
                        orderList.forEach(order -> {
                            if (!StringUtils.isEmpty(order.getPayInfo())) {
                                Map map = JSON.parseObject(order.getPayInfo(), Map.class);
                                if (Objects.nonNull(map.get("cash_amount"))) {
                                    Object cashAmountObj = map.get("cash_amount");
                                    if (Long.valueOf(cashAmountObj.toString()) > 0) {
                                        map.remove("cash_amount");
                                        order.setPayInfo(JSON.toJSONString(map));
                                        orderDao.updatePayInfo(order);
                                    }
                                }
                            }
                        });
                        count += orderList.size();
                        logger.info("updatePayInfo:{}条", count);
                        if (orderList.size() < 200) {
                            break;
                        }
                    }
                }
            }
            result.setStatus(true);
        } catch (Exception e) {
            logger.error("[updateRefundDealAt]failed!cause by:{}", e);
            result.setException(ExceptionConstants.SYSTEM_ERROR);
        }
        return result;
    }

    private OrderQuery buildUpdatePayInfo(OrderDataReviseRequest request) {
        Long startAt = 1614268800000L;
        Long endAt = 1614355140000L;
        OrderQuery orderQuery = new OrderQuery();
        orderQuery.setSize(200);
        orderQuery.setBizType(1);
//        orderQuery.setSellerId(33750L);
        orderQuery.setPayTypeList(Lists.newArrayList(5, 6, 8, 22, 21, 23));
        orderQuery.setOrderAtStart(new Date(startAt));
        orderQuery.setOrderAtEnd(new Date(endAt));
//        orderQuery.setIdList(ListConst.list);
        orderQuery.setOrderNo(request.getOrderNo());
        return orderQuery;
    }

    @Override
    public Result updateOrderStatus(OrderDataReviseRequest request) {
        Result result = new Result<>();
        int count = 0;
        long lastId = 524197582516277248L;
        OrderQuery orderQuery = buildUpdateItemInfo(request);
        try {
            for (int i = 0; i < dbSize; i++) {
                for (int j = 0; j < tbSize; j++) {
                    for (;;) {
                        orderQuery.setLastId(lastId);
                        List<Order> orderList = commonManager.scanOrder(orderQuery, i, j);
                        if (CollectionUtils.isEmpty(orderList)) {
                            break;
                        }
                        updateOrderStatusQueue(orderList, i, j);
                        count += orderList.size();
                        logger.info("updateOrderStatus:{}条", count);
                        if (orderList.size() < 200) {
                            break;
                        }
                        lastId = orderList.get(orderList.size() - 1).getId();
                        Result<String> redisData = redisManager.get("update_item_info_switch");
                        if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                            result.setStatus(true);
                            result.setData(lastId);
                            return result;
                        }
                    }
                }
            }
            result.setStatus(true);
        } catch (Exception e) {
            logger.error("[updateItemInfo]failed!cause by:{}", e);
            result.setException(ExceptionConstants.SYSTEM_ERROR);
        }
        return result;
    }
    private void updateOrderStatusQueue(List<Order> orderList, int i, int j) {
        while (workQueue.remainingCapacity() < 20) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executorService.submit(() -> {
            try {
//                commonManager.batchUpdateOrderItemInfo(orderList, i ,j);
                for (Order order : orderList) {
                    Order update = new Order();
                    update.setId(order.getId());
                    update.setUserId(order.getUserId());
                    update.setStatus(5);
                    update.setCompletedAt(new Date());
//                    orderDao.update(update);
                }
            } catch (Exception e) {
                logger.error("[updateOrderStatusQueue]failed！cause by:{}", e);
            }
        });
    }

    private OrderQuery buildUpdateItemInfo(OrderDataReviseRequest request) {
        Long startAt = 1601481600000L;
        Long endAt = 1621439999000L;
        OrderQuery orderQuery = new OrderQuery();
        orderQuery.setSellerId(40927L);
        orderQuery.setOrderAtStart(new Date(startAt));
        orderQuery.setOrderAtEnd(new Date(endAt));
        orderQuery.setStatusList(Lists.newArrayList(2,10,12));
        orderQuery.setPayStatus(1);
        orderQuery.setSize(200);
        orderQuery.setOrderNo(request.getOrderNo());
        orderQuery.setMaxId(601853088139055106L);
        return orderQuery;
    }

    @Override
    public Result updateItemPrice(OrderDataReviseRequest request) {
        for (String val : ListConst.list) {
            OrderIndex index = orderIndexDao.selectOne(val);
            if(index != null){
                Order order = orderDao.selectByOrderNo(index.getOrderNo(), index.getUserId());
                List<OrderItem> itemList = orderItemDao.selectByOrderNo(index.getOrderNo(), index.getUserId());
                itemList.forEach(item -> {
                    String s = MapConst.map.get(item.getItemSign());
                    if(s != null){
                        item.setItemName(s);
                        orderItemDao.updateItemPrice(item);
                    }
                });
                order.setItemInfo(JSON.toJSONString(ConvertUtils.convertList(itemList, InnerOrderItem.class)));
                orderDao.updateItemInfo(order);
            }
        }
        logger.info("Update item name end.");
        return Result.successNullData();
    }

    private static List<String> list1 = new ArrayList<>();

    @Override
    public Result updateSellerId(OrderDataReviseRequest request) {
        Result result = new Result();
        int count = 0;
        OrderDiscountQuery query = new OrderDiscountQuery();
        query.setSize(200);
        try {
            for (int i = 0; i < dbSize; i++) {
                for (int j = 0; j < tbSize; j++) {
                    Long lastId = 424237643681759233L;
                    for (;;) {
                        query.setLastId(lastId);
                        List<OrderDiscount> orderDiscountList = commonManager.scanOrderDiscount1(query, i, j);
                        if (CollectionUtils.isEmpty(orderDiscountList)) {
                            break;
                        }
                        updateSellerIdQueue(orderDiscountList, i, j);
                        count += orderDiscountList.size();
                        logger.info("updateSellerId:{}条", count);
                        if (orderDiscountList.size() < 200) {
                            break;
                        }
                        lastId = orderDiscountList.get(orderDiscountList.size() - 1).getId();
                        logger.info("lastId:{}", lastId);
                        Result<String> redisData = redisManager.get("update_seller_id_switch");
                        if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                            result.setStatus(true);
                            result.setData(lastId);
                            return result;
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("[updateSellerId]failed!cause by:{}", e);
            result.setException(ExceptionConstants.SYSTEM_ERROR);
        }
        return result;
    }

    private void updateSellerIdQueue(List<OrderDiscount> orderDiscountList, int i, int j) {
        while (workQueue.remainingCapacity() < 20) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executorService.submit(() -> {
            try {
                List<String> orderNoList =
                    orderDiscountList.stream().map(OrderDiscount::getOrderNo).collect(Collectors.toList());
                List<Order> orderList = commonManager.scanOrderByOrderNo(orderNoList, i, j);
                Map<String, List<Order>> orderMap =
                    orderList.stream().collect(Collectors.groupingBy(Order::getOrderNo));
                orderDiscountList.forEach(discount -> {
                    List<Order> orders = orderMap.get(discount.getOrderNo());
                    if (!CollectionUtils.isEmpty(orders)) {
                        discount.setSellerId(orders.get(0).getSellerId());
                    }
                });
                commonManager.updateDiscountSellerId(orderDiscountList, i, j);
            } catch (Exception e) {
                logger.error("[updateSellerIdQueue]failed！cause by:{}", e);
            }
        });
    }

    @Override
    public Result updateRefundItemSellerId(OrderDataReviseRequest request) {
        int count = 0;
        Long lastId = 424237644681751024L;
        RefundItemQuery query = new RefundItemQuery();
        query.setSize(200);
        for (;;) {
            query.setLastId(lastId);
            List<RefundItem> refundItemList = refundItemDao.selectList(query);
            if (CollectionUtils.isEmpty(refundItemList)) {
                break;
            }
            updateRefundItemSellerIdQueue(refundItemList);
            count += refundItemList.size();
            logger.info("updateRefundItemSellerId:{}条", count);
            if (refundItemList.size() < 200) {
                break;
            }
            lastId = refundItemList.get(refundItemList.size() - 1).getId();
        }
        return Result.successNullData();
    }

    private void updateRefundItemSellerIdQueue(List<RefundItem> refundItemList) {
        while (workQueue.remainingCapacity() < 20) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executorService.submit(() -> {
            try {
                List<String> refundNoList = refundItemList.stream().map(RefundItem::getRefundNo).collect(Collectors.toList());
                RefundQuery query = new RefundQuery();
                query.setRefundNoList(refundNoList);
                List<Refund> refundList = refundDao.selectList(query);
                Map<String, List<Refund>> refundMap = refundList.stream().collect(Collectors.groupingBy(Refund::getRefundNo));
                refundItemList.forEach(refundItem -> {
                    if (!CollectionUtils.isEmpty(refundMap.get(refundItem.getRefundNo()))) {
                        List<Refund> refunds = refundMap.get(refundItem.getRefundNo());
                        refundItem.setSellerId(refunds.get(0).getSellerId());
                    }
                });
                refundItemDao.updateSellerId(refundItemList);
            } catch (Exception e) {
                logger.error("[updateRefundItemSellerIdQueue]failed！cause by:{}", e);
            }
        });
    }


    @Override
    public Result updateOrderStatus() {
        try {
            for (String orderNo : ListConst2.list) {
                OrderIndex orderIndex = orderIndexDao.selectOne(orderNo);
                if (orderIndex != null) {
                    Order order = orderDao.selectByOrderNo(orderNo, orderIndex.getUserId());
                    if (order != null) {
                        Order update = new Order();
                        update.setId(order.getId());
                        update.setUserId(order.getUserId());
                        update.setPayStatus(1);
                        update.setStatus(20);

                        orderDao.orderDataUpdate(update);
                        order.setStatus(update.getStatus());
                        searchManager.indexOrder(order);
                    }
                }
            }
        } catch (Exception e) {

            logger.error("[updateOrderStatus]failed！cause by:{}", e);
            return Result.failureData(ExceptionConstants.SYSTEM_ERROR);
        }
        return Result.successNullData();
    }

    @Override
    public Result updatePaymentInfo(OrderDataReviseRequest request) {
        Long userId = 522929460953993771L;
        for (String orderNo : paymentList) {
            Order order = orderDao.selectByOrderNo(orderNo, userId);
            if (order != null && !CollectionUtils.isEmpty(order.getExtraMap())) {
                Map<String, Object> extraMap = order.getExtraMap();
                if (Objects.nonNull(extraMap.get("payment_info"))) {
                    Object paymentInfo = extraMap.get("payment_info");
                    if (!Objects.equals(paymentInfo, "[]")) {
                        List list = JSON.parseArray(paymentInfo.toString());
                        List<Map<String, Object>> listMap = new ArrayList<>();
                        for (Object obj : list) {
                            Map<String, Object> map = new HashMap<>(2);
                            String[] split = obj.toString().split(",");
                            for (int i = 0; i < split.length; i++) {
                                String[] split1 = split[i].split("=");
                                map.put(split1[0].replace("{", "").trim(),
                                        split1[1].replace("}", "").trim());
                            }
                            listMap.add(map);
                        }
                        extraMap.put("payment_info", JSON.toJSONString(listMap));
                        order.setExtraMap(extraMap);
                        orderDao.updateFeatures(order);
                    }
                }
            }
        }
        return Result.successNullData();
    }

    @Override
    public Result routingIndex(OrderDataReviseRequest request) {
        int count = 0;
        for (;;) {
            List<OrderIndex> indexList = testOrderIndexDao.selectList(602651038075363327L);
            if (CollectionUtils.isEmpty(indexList)) {
                break;
            }
            indexList.forEach(index -> index.setId(shardingKeyGenerator.generateSnowflakeNumKey()));
            orderIndexDao.insertList(indexList);
            count += indexList.size();
            logger.info("routingIndex count:{}", count);
            if (indexList.size() < 200) {
                break;
            }
        }
        return Result.successNullData();
    }

    @Override
    public Result insertPay() {
        int count = 0;
        OrderQuery orderQuery = buildOrderQuery2();
        try {
            for (int i = 0; i < dbSize; i++) {
                for (int j = 0; j < tbSize; j++) {
                    Long lastId = 424237643681776133L;
                    for (;;) {
                        orderQuery.setLastId(lastId);
                        List<Order> orderList = commonManager.scanOrder(orderQuery, i, j);
                        if (CollectionUtils.isEmpty(orderList)) {
                            break;
                        }
                        for (Order order : orderList) {
                            if (StringUtils.isEmpty(order.getPayDetailInfo())) {
                                orderPayTypeQuene(Lists.newArrayList(order), i, j);
                            }
                        }
                        count += orderList.size();
                        logger.info("insertPay:{}条", count);
                        if (orderList.size() < 50) {
                            break;
                        }
                        lastId = orderList.get(orderList.size() - 1).getId();
                    }
                }
            }
        } catch (Exception e) {
            logger.error("[insertPay]failed!cause by:{}", e);
            return Result.failureData(ExceptionConstants.SYSTEM_ERROR);
        }
        return Result.successNullData();
    }

    @Override
    public Result deletePay() {
        int count = 0;
        OrderQuery orderQuery = new OrderQuery();
        orderQuery.setSize(100);
//        orderQuery.setOrderNo("D5FA9EE48D25D38445");
        orderQuery.setSellerId(50161L);
        try {
            for (int i = 0; i < dbSize; i++) {
                for (int j = 0; j < tbSize; j++) {
                    Long lastId = null;
                    for (;;) {
                        orderQuery.setLastId(lastId);
                        List<OrderPayDetails> payDetailsList = commonManager.scanOrderPayDetails(orderQuery, i, j);
                        if (CollectionUtils.isEmpty(payDetailsList)) {
                            break;
                        }
                        executeDeletePay(payDetailsList);
                        count += payDetailsList.size();
                        logger.info("deletePay:{}条", count);
                        if (payDetailsList.size() < 100) {
                            break;
                        }
                        lastId = payDetailsList.get(payDetailsList.size() - 1).getId();
                    }
                }
            }
        } catch (Exception e) {
            logger.error("[deletePay]failed!cause by:{}", e);
            return Result.failureData(ExceptionConstants.SYSTEM_ERROR);
        }
        return Result.successNullData();
    }

    @Override
    public void deletePayA() {
        int count = 0;
        for (String orderNo : ListConst.list) {
            OrderIndex orderIndex = orderIndexDao.selectOne(orderNo);
            if (orderIndex != null) {
                Order order = orderDao.selectByOrderNo(orderIndex.getOrderNo(), orderIndex.getUserId());
                if (order != null) {
                    List<OrderPayDetails> payDetails =
                        orderPayDetailsDao.selectByOrderNo(order.getOrderNo(), order.getUserId());
                    if (!CollectionUtils.isEmpty(payDetails) && payDetails.size() >= 2) {
                        for (OrderPayDetails payDetail : payDetails) {
                            if (payDetail.getCreatedAt().getTime() > new Date(1719244800000L).getTime()) {
                                orderPayDetailsDao.delete(payDetail.getId(), payDetail.getUserId());
                            }
                        }
                        List<OrderPayDetails> payDetailsList = orderPayDetailsDao.selectByOrderNo(order.getOrderNo(), order.getUserId());
                        if (!CollectionUtils.isEmpty(payDetailsList)) {
                            order.setPayDetailInfo(JSON
                                .toJSONString(ConvertUtils.convertList(payDetailsList, InnerOrderPayDetails.class)));
                            orderDao.updatePayDetailInfo(order);
                            count++;
                            logger.info("deletePayA, count:{}", count);
                        }
                    }
                }
            }
        }
    }

    private void executeDeletePay(List<OrderPayDetails> payDetailsList) {
        while (workQueue.remainingCapacity() < 20) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executorService.submit(() -> {
            try {
                for (OrderPayDetails orderPayDetails : payDetailsList) {
                    orderPayDetailsDao.delete(orderPayDetails.getId(), orderPayDetails.getUserId());
                }
            } catch (Exception e) {
                logger.error("[executeDeletePay]failed！cause by:{}", e);
            }
        });
    }

    private OrderQuery buildOrderQuery2() {
        OrderQuery orderQuery = new OrderQuery();
        orderQuery.setSellerId(206146L);
        orderQuery.setPayStatus(1);
        orderQuery.setSize(50);
        return orderQuery;
    }

    private static List<Long> sellerIdList = new ArrayList<>();

    static {
        sellerIdList.add(202190L);
    }

    // todo
    @Override
    public Result cateringTransfer(OrderDataReviseRequest request) {
        int count = 0;
        Date current = new Date();
        Date queryStartAt = DateUtils.before(current, Calendar.DAY_OF_YEAR, 365);
        for (Long sellerId : sellerIdList) {
            OrderQuery orderQuery = new OrderQuery();
//            orderQuery.setSellerId(sellerId);
//            orderQuery.setOrderAtStart(queryStartAt);
//            orderQuery.setOrderAtEnd(current);
//            orderQuery.setBizType(1);
            orderQuery.setIsDeleted(0);
            orderQuery.setOrderNoList(Lists.newArrayList(
                    "301035704288152226",
                    "401035561928819279",
                    "301035420666150759"
            ));
            orderQuery.setSize(200);
            try {
                for (int i = 0; i < dbSize; i++) {
                    for (int j = 0; j < tbSize; j++) {
                        Long lastId = null;
                        for (;;) {
                            orderQuery.setLastId(lastId);
                            long startAt = System.currentTimeMillis();
                            List<Long> orderIdList = commonManager.scanOrderId(orderQuery, i, j);
                            if (CollectionUtils.isEmpty(orderIdList)) {
                                break;
                            }
                            List<Order> orderList = commonManager.listOrderById(orderIdList, i, j);
                            long endAt = System.currentTimeMillis() - startAt;
                            if (endAt >= 500) {
                                logger.info("query_time:{}ms", endAt);
                            }
                            executeTransfer(orderList, i, j);
                            count += orderIdList.size();
                            logger.info("cateringTransfer:{}条", count);
                            if (orderIdList.size() < 200) {
                                break;
                            }
                            lastId = orderIdList.get(orderIdList.size() - 1);
                            logger.info("cateringTransfer_lastId:{},i:{},j:{}", lastId, i, j);
                            Result<String> redisData = redisManager.get("catering_transfer");
                            if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                                return Result.successNullData();
                            }
                        }
                    }
                }
            } catch (Exception e) {
                logger.error("[cateringTransfer]failed!cause by:{}", e);
                return Result.failureData(ExceptionConstants.SYSTEM_ERROR);
            }
        }
        return Result.successNullData();
    }

    private void executeTransfer(List<Order> orderList, int i, int j) {
        while (workQueue.remainingCapacity() < 20) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executorService.submit(() -> {
            try {
                List<BatchSyncEsMessage> messageList = new ArrayList<>(300);

                long deletePayAt = System.currentTimeMillis();
                List<String> orderNoList = orderList.stream().map(Order::getOrderNo).collect(Collectors.toList());
                OrderPayDetailsQuery query = new OrderPayDetailsQuery();
                query.setOrderNoList(orderNoList);
                List<OrderPayDetails> payIdList = commonManager.scanPayDetailsId(query, i, j);
                if (!CollectionUtils.isEmpty(payIdList)) {
                    List<Long> idList = payIdList.stream().map(OrderPayDetails::getId).collect(Collectors.toList());
                    commonManager.deletePayDetailsById(idList, i, j);
                }
                logger.info("delete_pay_at_time:{}ms", System.currentTimeMillis() - deletePayAt);

                long startAt = System.currentTimeMillis();
                // 批量查询订单下的所有商品
                List<OrderItem> itemList = queryOrderItemList(orderList);
//                Map<String, List<OrderAddrDTO>> addrMap = queryOrderAddressList(orderList);
                // 商品ID列表
                List<Long> itemIdList = itemList.stream().map(OrderItem::getId).collect(Collectors.toList());
                List<WmOrderAttachGoods> attachGoodsList = new ArrayList<>();
                List<WmOrderGiveGoods> orderGiveGoodsList = new ArrayList<>();
                if (!CollectionUtils.isEmpty(itemIdList)) {
                    // 商品加料
                    attachGoodsList = orderAttachGoodsDao.selectList(itemIdList);
                    // 套餐商品
                    orderGiveGoodsList = orderGiveGoodsDao.selectList(itemIdList);
                }
                // 按照订单号分组
                Map<String, List<OrderItem>> itemMap = itemList.stream().collect(Collectors.groupingBy(OrderItem::getOrderNo));
                // 新增商品加料列表
                List<OrderItemBatching> itemBatchingList = new ArrayList<>();
                // 新增套餐子商品列表
                List<OrderItem> setMealList = new ArrayList<>();
                // 更新商品itemType列表
                List<OrderItem> setMealUpdateItemList = new ArrayList<>();
                // 新增支付明细列表
                List<OrderPayDetails> payDetailsList = new ArrayList<>();
                logger.info("startAt_indexOrder_time:{}ms", System.currentTimeMillis() - startAt);

                long startAt1 = System.currentTimeMillis();
                for (Order order : orderList) {
                    messageList.add(buildMessage(order));
                    List<OrderPayDetails> orderPayList = new ArrayList<>();
                    buildOrderParam(order, itemMap, orderPayList);
                    if (!CollectionUtils.isEmpty(orderPayList)) {
                        payDetailsList.addAll(orderPayList);
                        order.setPayDetailInfo(JSON.toJSONString(orderPayList));
                    }
//                    buildOrderAddress(order, addrMap);
                    buildItemBatchingParam(order, itemMap, itemBatchingList, attachGoodsList);
                    buildSetMealItem(order, setMealList, setMealUpdateItemList, itemMap, orderGiveGoodsList);
                    String itemInfo = order.getItemInfo();
                    if (!Objects.equals("TL", itemInfo)) {
                        List<InnerOrderItem> innerOrderItemList = JSON.parseArray(itemInfo, InnerOrderItem.class);
                        if (!CollectionUtils.isEmpty(innerOrderItemList) && innerOrderItemList.size() > 10) {
                            order.setItemInfo("TL");
                        }
                    }
                }
                logger.info("startAt1_indexOrder_time:{}ms", System.currentTimeMillis() - startAt1);

                // 执行变更
                long startAt2 = System.currentTimeMillis();
                commonManager.batchUpdateOrderInfo(orderList, i, j);
                logger.info("startAt2_indexOrder_time:{}ms", System.currentTimeMillis() - startAt2);

                long startAt3 = System.currentTimeMillis();
                List<OrderItem> newItemList = null;
                if (!CollectionUtils.isEmpty(setMealUpdateItemList)) {
                    newItemList = reBuildItemList(itemList, setMealUpdateItemList);
                } else {
                    newItemList = itemList;
                }
                if (!CollectionUtils.isEmpty(newItemList)) {
                    List<List<OrderItem>> partition = Lists.partition(newItemList, 100);
                    for (List<OrderItem> orderItemList : partition) {
                        commonManager.batchUpdateItemType(orderItemList, i, j);
                    }
                }
                if (!CollectionUtils.isEmpty(setMealList)) {
                    List<List<OrderItem>> partition = Lists.partition(setMealList, 100);
                    for (List<OrderItem> orderItems : partition) {
                        orderItemDao.inserts(orderItems);
                    }
                }
                if (!CollectionUtils.isEmpty(itemBatchingList)) {
                    itemBatchingDao.insertList(itemBatchingList);
                }
                if (!CollectionUtils.isEmpty(payDetailsList)) {
                    payDetailsDao.insertList(payDetailsList);
                }
                logger.info("startAt3_indexOrder_time:{}ms", System.currentTimeMillis() - startAt3);

                long startAt4 = System.currentTimeMillis();
                List<BatchSyncEsMessage> pushList = new ArrayList<>(500);
                buildPushMessage(messageList, pushList);
                List<List<BatchSyncEsMessage>> partition = Lists.partition(pushList, 20);
                for (List<BatchSyncEsMessage> batchSyncEsMessages : partition) {
                    messageManager.sendBatchSyncMessage(batchSyncEsMessages);
                }
                logger.info("startAt4_indexOrder_time:{}ms", System.currentTimeMillis() - startAt4);
            } catch (Exception e) {
                logger.error("[executeTransfer]failed！cause by:{}", e);
            }
        });
    }
    
    private void buildPushMessage(List<BatchSyncEsMessage> messageList, List<BatchSyncEsMessage> pushList) {
        if (!CollectionUtils.isEmpty(messageList)) {
            for (BatchSyncEsMessage message : messageList) {
                if (Objects.equals(1, message.getOrderSubType())) {
                    OrderUserRelation relation = ourDao.selectByOrderNo(message.getOrderNo(), message.getUserId());
                    if (relation == null) {
                        pushList.add(message);
                        continue;
                    }
                    if (Objects.equals(0, relation.getIsRoot())) {
                        pushList.add(message);
                        continue;
                    }
                } else {
                    pushList.add(message);
                }
            }
        }
    }

    private BatchSyncEsMessage buildMessage(Order order) {
        BatchSyncEsMessage message = new BatchSyncEsMessage();
        message.setUserId(order.getUserId());
        message.setId(order.getId());
        message.setOrderNo(order.getOrderNo());
        message.setOrderSubType(order.getOrderSubType());
        return message;
    }

    private List<OrderItem> reBuildItemList(List<OrderItem> itemList, List<OrderItem> setMealUpdateItemList) {
        Map<Long, List<OrderItem>> listMap = itemList.stream().collect(Collectors.groupingBy(OrderItem::getId));
        for (OrderItem orderItem : itemList) {
            listMap.put(orderItem.getId(), Lists.newArrayList(orderItem));
        }
        List<ArrayList<OrderItem>> arrayLists = listMap.values().stream().
                map(v -> (new ArrayList<OrderItem>(v))).collect(Collectors.toList());
        List<OrderItem> newItemList = new ArrayList<>();
        for (ArrayList<OrderItem> arrayList : arrayLists) {
            newItemList.addAll(arrayList);
        }
        return newItemList;
    }

    private List<OrderItem> queryOrderItemList(List<Order> orderList) {
        List<Long> userIdList = orderList.stream().map(Order::getUserId).collect(Collectors.toList());
        List<String> orderNoList = orderList.stream().map(Order::getOrderNo).collect(Collectors.toList());
        OrderItemQuery orderItemQuery = new OrderItemQuery();
        orderItemQuery.setUserIdList(userIdList);
        orderItemQuery.setOrderNoList(orderNoList);
        return orderItemDao.selectList(orderItemQuery);
    }

    private Map<String, List<OrderAddrDTO>> queryOrderAddressList(List<Order> orderList) {
        List<Long> userIdList = orderList.stream().map(Order::getUserId).collect(Collectors.toList());
        List<String> orderNoList = orderList.stream().map(Order::getOrderNo).collect(Collectors.toList());
        OrderAddressQuery query = new OrderAddressQuery();
        query.setUserIdList(userIdList);
        query.setOrderNoList(orderNoList);
        List<OrderAddrDTO> addrDTOList = ConvertUtils.convertList(orderAddrDao.selectList(query), OrderAddrDTO.class);
        if (CollectionUtils.isEmpty(addrDTOList)) {
            return Collections.EMPTY_MAP;
        }
        return addrDTOList.stream().collect(Collectors.groupingBy(OrderAddrDTO::getOrderNo));
    }

    private void buildSetMealItem(Order order, List<OrderItem> setMealList, List<OrderItem> updateItemList,
                                  Map<String, List<OrderItem>> itemMap, List<WmOrderGiveGoods> orderGiveGoodsList) {
        if (CollectionUtils.isEmpty(orderGiveGoodsList)) {
            return;
        }
        Map<Long, List<WmOrderGiveGoods>> goodsMap = orderGiveGoodsList.stream().collect(
                Collectors.groupingBy(WmOrderGiveGoods::getOrderGoodsId));

        List<OrderItem> itemList = itemMap.get(order.getOrderNo());
        if (CollectionUtils.isEmpty(itemList)) {
            return;
        }
        for (OrderItem orderItem : itemList) {
            Map<String, Object> extraMap = orderItem.getExtraMap();
            if (!CollectionUtils.isEmpty(extraMap)) {
                Object goodsType = extraMap.get("goods_type");
                if (Objects.equals(2, goodsType)) {
                    List<WmOrderGiveGoods> goodsList = goodsMap.get(orderItem.getId());
                    if (CollectionUtils.isEmpty(goodsList)) {
                        break;
                    }
                    List<InnerOrderItem> innerOrderItemList = new ArrayList<>();
                    for (WmOrderGiveGoods giveGoods : goodsList) {
                        OrderItem setMealItem = buildSetMealItem(giveGoods, orderItem);
                        setMealList.add(setMealItem);
                        innerOrderItemList.add(mapper.map(setMealItem, InnerOrderItem.class));
                    }
                    String itemInfo = order.getItemInfo();
                    if (!Objects.equals("TL", itemInfo)) {
                        if (StringUtils.isEmpty(itemInfo)) {
                            order.setItemInfo("TL");
                        } else {
                            List<InnerOrderItem> innerOrderItemList1 = JSON.parseArray(itemInfo, InnerOrderItem.class);
                            for (InnerOrderItem innerOrderItem : innerOrderItemList1) {
                                if (Objects.equals(innerOrderItem.getId(), orderItem.getId())) {
                                    innerOrderItem.setItemType(1);
                                }
                            }
                            innerOrderItemList1.addAll(innerOrderItemList);
                            order.setItemInfo(JSON.toJSONString(innerOrderItemList1));
                        }
                    }
                    // 普通商品itemType = 0 套餐商品itemType = 1 套餐子商品itemType = 2
                    orderItem.setItemType(1);
                    updateItemList.add(orderItem);
                }
            }
        }
    }
    
    private OrderItem buildSetMealItem(WmOrderGiveGoods giveGoods, OrderItem orderItem) {
        OrderItem setMealItem = new OrderItem();
        setMealItem.setId(shardingKeyGenerator.generateSnowflakeNumKey());
        setMealItem.setBizType(7);
        setMealItem.setOrderNo(orderItem.getOrderNo());
        setMealItem.setUserId(orderItem.getUserId());
        setMealItem.setSellerId(orderItem.getSellerId());
        setMealItem.setOwnerId(orderItem.getId());
        setMealItem.setItemType(2);
        setMealItem.setItemId(Objects.nonNull(giveGoods.getEntityId()) ? giveGoods.getEntityId() : "");
        setMealItem.setItemName(Objects.nonNull(giveGoods.getName()) ? giveGoods.getName() : "");
        setMealItem.setNum(new BigDecimal(Objects.nonNull(giveGoods.getNum()) ? giveGoods.getNum() : 0));
        setMealItem.setItemSpec(Objects.nonNull(giveGoods.getSpec()) ? giveGoods.getSpec() : "");
        setMealItem.setItemPrice(giveGoods.getPrice().intValue() * 100);
        setMealItem.setItemSign(Objects.nonNull(giveGoods.getTradeMark()) ? giveGoods.getTradeMark() : "");
        setMealItem.setItemBarcode(Objects.nonNull(giveGoods.getBarcode()) ? giveGoods.getBarcode() : "");
        setMealItem.setItemImage(Objects.nonNull(giveGoods.getImage()) ? giveGoods.getImage() : "");
        setMealItem.setPackAmount(giveGoods.getPackAmount().intValue() * 100);
        setMealItem.setProductNo(Objects.nonNull(giveGoods.getProductNo()) ? giveGoods.getProductNo() : "");
        setMealItem.setFeatures(JSON.toJSONString(giveGoods));
        setMealItem.setIsGift(0);
        setMealItem.setOrderAt(orderItem.getOrderAt());
        setMealItem.setIsTimeDiscount(0);
        setMealItem.setActivityId(0L);
        setMealItem.setfCode("");
        setMealItem.setDiscountAmount(0);
        setMealItem.setMemberPrice(0);
        setMealItem.setItemUnit("");
        setMealItem.setMarketPrice(0);
        setMealItem.setCostPrice(giveGoods.getOriginalPrice().intValue() * 100);
        setMealItem.setStatus(0);
        setMealItem.setGoodsId(0L);
        return setMealItem;
    }

    private void buildOrderAddress(Order order, Map<String, List<OrderAddrDTO>> addrMap) {
        if (!CollectionUtils.isEmpty(addrMap)) {
            List<OrderAddrDTO> list = addrMap.get(order.getOrderNo());
            if (!CollectionUtils.isEmpty(list)) {
                order.setAddrInfo(JSON.toJSONString(list.get(0)));
            }
        }
    }

    private void buildOrderParam(Order order, Map<String, List<OrderItem>> itemMap, List<OrderPayDetails> payDetailsList) {
        order.setSellerId(49112L);
        convertExtraMap(order);
        convertPayAmount(order);
        convertPayInfo(order);
        convertStatus(order);
        if (Objects.equals(1, order.getPayStatus())) {
            convertPayType(order, payDetailsList);
        }
        convertPerformanceType(order);
        convertOrderType(order);
        convertPerformancePlatform(order);
        convertPerformanceInfo(order);
    }

    private void buildItemBatchingParam(Order order, Map<String, List<OrderItem>> itemMap,
                                        List<OrderItemBatching> itemBatchingList, List<WmOrderAttachGoods> attachGoodsList) {
        if (!CollectionUtils.isEmpty(attachGoodsList)) {
            Map<Long, List<WmOrderAttachGoods>> map = attachGoodsList.stream().collect(
                    Collectors.groupingBy(WmOrderAttachGoods::getOrderGoodsId));
            List<InnerOrderItem> orderItemList = new ArrayList<>();
            
            List<OrderItem> itemList = itemMap.get(order.getOrderNo());
            if (!CollectionUtils.isEmpty(itemList)) {
                for (OrderItem orderItem : itemList) {
                    List<WmOrderAttachGoods> goodsList = map.get(orderItem.getId());
                    if (CollectionUtils.isEmpty(goodsList)) {
                        orderItemList.add(mapper.map(orderItem, InnerOrderItem.class));
                        continue;
                    }
                    List<InnerOrderItemBatching> batchingList = new ArrayList<>();
                    for (WmOrderAttachGoods batching : goodsList) {
                        OrderItemBatching itemBatching = parseItemBatching(batching, order);
                        batchingList.add(mapper.map(itemBatching, InnerOrderItemBatching.class));
                        itemBatchingList.add(itemBatching);
                    }
                    if (batchingList.size() > 10) {
                        orderItem.setBatchingInfo("TL");
                    } else {
                        orderItem.setBatchingInfo(JSON.toJSONString(batchingList));
                    }
                    orderItemList.add(mapper.map(orderItem, InnerOrderItem.class));
                }
                if (!CollectionUtils.isEmpty(orderItemList)) {
                    order.setItemInfo(JSON.toJSONString(orderItemList));
                }
            }
        }
    }
    
    private OrderItemBatching parseItemBatching(WmOrderAttachGoods batching, Order order) {
        OrderItemBatching itemBatching = new OrderItemBatching();
        itemBatching.setId(shardingKeyGenerator.generateSnowflakeNumKey());
        itemBatching.setUserId(order.getUserId());
        itemBatching.setOrderNo(order.getOrderNo());
        itemBatching.setSellerId(order.getSellerId());
        itemBatching.setStoreId(order.getStoreId());
        itemBatching.setBatchingId(Objects.nonNull(batching.getMaterialId()) ? batching.getMaterialId().toString() : "");
        itemBatching.setBatchingName(Objects.nonNull(batching.getName()) ? batching.getName() : "");
        itemBatching.setNum(Objects.nonNull(batching.getQty()) ? batching.getQty() : 0);
        itemBatching.setCode(Objects.nonNull(batching.getCode()) ? batching.getCode() : "");
        itemBatching.setPrice(batching.getPrice().multiply(new BigDecimal(100)));
        itemBatching.setOrderItemId(batching.getOrderGoodsId());
        return itemBatching;
    }

    private void convertPayInfo(Order order) {
        List<String> payNameList = new ArrayList<>();
        Object paymentInfo = order.getExtraMap().get("payment_info");
        if (paymentInfo != null) {
            if (paymentInfo instanceof List) {
                List<Map> list = JSON.parseArray(paymentInfo.toString(), Map.class);
                for (Map map : list) {
                    Object name = map.get("name");
                    Object amount = map.get("amount");
                    if (amount != null && !StringUtils.isEmpty(name.toString())) {
                        Double d = Double.valueOf(amount.toString());
                        if (d > 0) {
                            payNameList.add(name + "：￥" + amount);
                        }
                    }
                }
            }
            if (paymentInfo instanceof Map) {
                Map map = JSON.parseObject(paymentInfo.toString(), Map.class);
                map.forEach((key, value) -> {
                    Map valueObj = JSON.parseObject(value.toString(), Map.class);
                    Object name = valueObj.get("name");
                    Object amount = valueObj.get("amount");
                    if (amount != null && !StringUtils.isEmpty(name.toString())) {
                        Double d = Double.valueOf(amount.toString());
                        if (d > 0) {
                            payNameList.add(name + "：￥" + amount);
                        }
                    }
                });
            }
        }

        if (StringUtils.isEmpty(order.getPayInfo())) {
            Map<String, Object> payInfoMap = new HashMap<>(3);
            payInfoMap.put("walletAmount", 0);
            payInfoMap.put("amount", 0);
            payInfoMap.put("userWallet", 0);
            payInfoMap.put("payDetailsList", payNameList);
            order.setPayInfo(JSON.toJSONString(payInfoMap));
            return;
        }
        String payInfo = order.getPayInfo();
        Map<String, Object> payInfoMap = JSON.parseObject(payInfo, Map.class);
        payInfoMap.put("payDetailsList", payNameList);
        Object walletAmountObj = payInfoMap.get("wallet_amount");
        Object useWalletObj = payInfoMap.get("use_wallet");
        Object cashAmountObj = payInfoMap.get("cash_amount");
        Double w = 0.00;
        if (Objects.nonNull(walletAmountObj)) {
            String walletAmount = walletAmountObj.toString();
            if (walletAmount.contains(".")) {
                w = Double.valueOf(walletAmountObj.toString());
            } else {
                w = Double.valueOf(walletAmountObj.toString()) / 100;
            }
        }
        payInfoMap.put("walletAmount", w);
        payInfoMap.put("useWallet", Objects.nonNull(useWalletObj) ? Integer.valueOf(useWalletObj.toString()) : 0);
        payInfoMap.put("cashAmount", Objects.nonNull(cashAmountObj) ? Double.valueOf(cashAmountObj.toString()) / 100 : 0);
        order.setPayInfo(JSON.toJSONString(payInfoMap));

        if (Objects.nonNull(walletAmountObj)) {
            Integer walletAmount;
            String walletAmountStr = payInfoMap.get("wallet_amount").toString();
            if (walletAmountStr.contains(".")) {
                walletAmount = new BigDecimal(walletAmountStr).multiply(new BigDecimal(100)).intValue();
            } else {
                walletAmount = Integer.valueOf(walletAmountStr);
            }
            if (walletAmount > 0) {
                List<String> list = new ArrayList<>(1);
                Map<String, Object> map = new HashMap<>(3);
                map.put("bizId", order.getOrderNo());
                if (Objects.nonNull(payInfoMap.get("change_gift_amount"))
                    && Objects.nonNull(payInfoMap.get("change_recharge_amount"))) {
                    map.put("giftAmount", Double.valueOf(payInfoMap.get("change_gift_amount").toString()) / 100);
                    map.put("rechargeAmount", Double.valueOf(payInfoMap.get("change_recharge_amount").toString()) / 100);
                } else {
                    map.put("giftAmount", 0);
                    map.put("rechargeAmount", Double.valueOf(walletAmount) / 100);
                }
                list.add(JSON.toJSONString(map));
                payInfoMap.put("walletPayDetail", list);
                order.setPayInfo(JSON.toJSONString(payInfoMap));
            }
        }
    }

    private void convertStatus(Order order) {
        if (Objects.equals(1, order.getStatus())) {
            order.setStatus(10);
            return;
        }
        if (Objects.equals(2, order.getStatus())) {
            order.setStatus(20);
            return;
        }
        if (Objects.equals(3, order.getStatus())) {
            order.setStatus(60);
            return;
        }
        if (Objects.equals(5, order.getStatus())) {
            order.setStatus(50);
            return;
        }
        if (Objects.equals(6, order.getStatus()) && Objects.equals(0, order.getPayStatus())) {
            order.setStatus(60);
            return;
        }
        if (Objects.equals(6, order.getStatus()) && Objects.equals(1, order.getPayStatus())) {
            order.setStatus(70);
            return;
        }
        if (Objects.equals(6, order.getStatus()) && Objects.equals(2, order.getPayStatus())) {
            order.setStatus(60);
            return;
        }
        if (Objects.equals(10, order.getStatus())) {
            order.setStatus(30);
            return;
        }
        if (Objects.equals(11, order.getStatus())) {
            order.setStatus(70);
            return;
        }
        if (Objects.equals(12, order.getStatus())) {
            order.setStatus(40);
            return;
        }
        if (Objects.equals(13, order.getStatus())) {
            order.setStatus(30);
            return;
        }
    }

    private void convertPayType(Order order, List<OrderPayDetails> payDetailsList) {
        setPayDetails(order, payDetailsList);
        for (OrderPayDetails payDetails : payDetailsList) {
            if (Objects.equals(payDetails.getPayType(), 12)) {
                Integer changeAmount = order.getChangeAmount();
                if (Objects.nonNull(changeAmount) && !Objects.equals(0, changeAmount)) {
                    if (payDetails.getAmount() >= changeAmount) {
                        payDetails.setAmount(payDetails.getAmount() - changeAmount);
                    }
                }
            }
        }
    }

    private void convertPayAmount(Order order) {
        // 三方支付
        if (!alipayList.contains(order.getPayType()) && !wechatList.contains(order.getPayType())) {
            order.setPayAmount(0);
            return;
        }
        String payInfo = order.getPayInfo();
        if (StringUtils.isEmpty(payInfo)) {
            return;
        }
        Map payInfoMap = JSON.parseObject(payInfo, Map.class);
        Object amountObj = payInfoMap.get("amount");
        Object cashAmountObj = payInfoMap.get("cash_amount");
        Object thirdAmountObj = payInfoMap.get("third_amount");
        // 组合支付 三方 + 现金
        if (Objects.equals(19, order.getSource())) {
            if (Objects.nonNull(cashAmountObj) && Objects.nonNull(thirdAmountObj)) {
                Integer cashAmount = Integer.valueOf(cashAmountObj.toString());
                Integer thirdAmount = Integer.valueOf(thirdAmountObj.toString());
                if (cashAmount > 0 && thirdAmount > 0) {
                    order.setPayAmount(thirdAmount);
                    return;
                }
            }
        }
        // 三方支付 / 三方 + 余额
        if (Objects.nonNull(amountObj)) {
            order.setPayAmount(Integer.valueOf(amountObj.toString()));
            return;
        }
    }

    private void convertPerformanceType(Order order) {
        if (Objects.equals(1, order.getPerformanceType())) {
            order.setPerformanceType(2);
            return;
        }
        if (Objects.equals(2, order.getPerformanceType())) {
            order.setPerformanceType(4);
            return;
        }
        if (Objects.equals(3, order.getPerformanceType())) {
            order.setPerformanceType(6);
            return;
        }
        if (Objects.equals(4, order.getPerformanceType())) {
            order.setPerformanceType(3);
            return;
        }
        if (Objects.equals(5, order.getPerformanceType())) {
            order.setPerformanceType(7);
            return;
        }
        if (Objects.equals(6, order.getPerformanceType())) {
            order.setPerformanceType(8);
            return;
        }
        if (Objects.equals(7, order.getPerformanceType())) {
            order.setPerformanceType(1);
            return;
        }
    }

    private void convertPerformancePlatform(Order order) {
        if (!Objects.equals(1, order.getPerformanceStatus())) {
            return;
        }
        if (!Objects.equals(3, order.getOrderType())) {
            return;
        }
        if (Objects.equals("0", order.getPerformancePlatform())) {
            order.setPerformancePlatform("商家自配");
            return;
        }
        if (Objects.equals("1", order.getPerformancePlatform())) {
            order.setPerformancePlatform("蜂鸟");
            return;
        }
        if (Objects.equals("2", order.getPerformancePlatform())) {
            order.setPerformancePlatform("达达");
            return;
        }
        if (Objects.equals("3", order.getPerformancePlatform())) {
            order.setPerformancePlatform("UU跑腿");
            return;
        }
        if (Objects.equals("4", order.getPerformancePlatform())) {
            order.setPerformancePlatform("顺丰");
            return;
        }
        if (Objects.equals("5", order.getPerformancePlatform())) {
            order.setPerformancePlatform("点我达");
            return;
        }
        if (Objects.equals("6", order.getPerformancePlatform())) {
            order.setPerformancePlatform("餐道");
            return;
        }
        if (Objects.equals("7", order.getPerformancePlatform())) {
            order.setPerformancePlatform("美团");
            return;
        }
    }

    private void convertOrderType(Order order) {
        if (Objects.equals(6, order.getOrderType())) {
            WmKoubeiOrders koubeiOrders = wmKoubeiOrdersDao.selectOne(order.getOrderNo());
            if (koubeiOrders != null) {
                order.setOrderType(Objects.equals(koubeiOrders.getIsToGo(), 1) ? 2 : 1);
                Map<String, Object> extraMap = order.getExtraMap();
                extraMap.put("wmKoubeiOrders", JSON.toJSONString(koubeiOrders));
                order.setExtraMap(extraMap);
            } else {
                order.setOrderType(1);
            }
        }
    }

    private void convertPerformanceInfo(Order order) {
        String performanceInfo = order.getPerformanceInfo();
        if (!StringUtils.isEmpty(performanceInfo)) {
            Map<String, Object> map = JSON.parseObject(performanceInfo, Map.class);
            if (map.containsKey("sent_at")) {
                map.put("sentAt", map.get("sent_at"));
                order.setPerformanceInfo(JSON.toJSONString(map));
            }
        }
    }

    private void convertExtraMap(Order order) {
        Map<String, Object> extraMap = order.getExtraMap();
        if (CollectionUtils.isEmpty(extraMap)) {
            extraMap = new HashMap<>(10);
        }
        extraMap.put("isHistoryOrder", 1);
        extraMap.put("historyOrderType", order.getOrderType());
        extraMap.put("historyPayType", order.getPayType());
        extraMap.put("historyStatus", order.getStatus());
        extraMap.put("historyPlatform", order.getPerformancePlatform());
        extraMap.put("historyPerformanceType", order.getPerformanceType());
        extraMap.put("historyPayAmount", order.getPayAmount());
        extraMap.put("historyBizType", 1);
        if (extraMap.containsKey("sync_erp_error")) {
            extraMap.put("syncError", extraMap.get("sync_erp_error"));
        }
        if (extraMap.containsKey("erp_sync_error_reason")) {
            extraMap.put("syncErrorReason", extraMap.get("erp_sync_error_reason"));
        }
        if (extraMap.containsKey("flavor_card_minus")) {
            extraMap.put("flavorCardMinus", extraMap.get("flavor_card_minus"));
        }
        if (extraMap.containsKey("invoice_status")) {
            extraMap.put("invoiceStatus", extraMap.get("invoice_status"));
        }
        order.setExtraMap(extraMap);
    }

    private OrderQuery buildOrderQuery(OrderDataReviseRequest request) {
        OrderQuery orderQuery = new OrderQuery();
//        orderQuery.setBizType(1);
//        orderQuery.setSellerId(203683L);
//        orderQuery.setOrderNo("5033888363354677665");
//        orderQuery.setOrderAtStart(new Date(1622476800000L));
//        orderQuery.setOrderAtEnd(new Date(1627402032000L));
//        orderQuery.setOrderNoList(Lists.newArrayList("D60F68DF53F8B66770", "D60F68DDE98B2B6954"));
        orderQuery.setSize(500);
        return orderQuery;
    }

    @Override
    public Result cateringRefundTransfer(OrderDataReviseRequest request) {
        int count = 0;
        for (Long sellerId : sellerIdList) {
            RefundQuery query = new RefundQuery();
            query.setSellerId(sellerId);
//            query.setRefundNo("R65029FE12B8B19005");
            query.setSize(200);
            try {
                Long lastId = null;
                for (;;) {
                    query.setLastId(lastId);
                    List<Refund> refundList = refundDao.selectList(query);
                    if (CollectionUtils.isEmpty(refundList)) {
                        break;
                    }
                    executeRefundTransfer(refundList);
                    count += refundList.size();
                    logger.info("cateringRefundTransfer:{}条", count);
                    if (refundList.size() < 200) {
                        break;
                    }
                    lastId = refundList.get(refundList.size() - 1).getId();
                    logger.info("cateringRefundTransfer_lastId:{}", lastId);
                    Result<String> redisData = redisManager.get("catering_refund_transfer");
                    if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                        return Result.successNullData();
                    }
                }
            } catch (Exception e) {
                logger.error("[cateringRefundTransfer]failed!cause by:{}", e);
                return Result.failureData(ExceptionConstants.SYSTEM_ERROR);
            }
        }
        return Result.successNullData();
    }

    private void executeRefundTransfer(List<Refund> refundList) {
        while (workQueue.remainingCapacity() < 20) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executorService.submit(() -> {
            try {
                List<OrderRefundDetails> payDetailList = new ArrayList<>();
                List<String> refundNoList = refundList.stream().map(Refund::getRefundNo).collect(Collectors.toList());
                RefundItemQuery query = new RefundItemQuery();
                query.setRefundNoList(refundNoList);
                List<RefundItem> refundItemList = refundItemDao.selectList(query);
                for (Refund refund : refundList) {
                    refund.setSellerId(217347L);
                    parseRefundParam(refund, payDetailList);
                }
                refundDao.updateExtraMap(refundList);
                if (!CollectionUtils.isEmpty(refundItemList)) {
                    List<RefundItem> refundItems = rebuildItemType(refundItemList);
                    refundItemDao.updateBizType(refundItems);
                }
                if (!CollectionUtils.isEmpty(payDetailList)) {
                    refundDetailsDao.insertList(payDetailList);
                }
            } catch (Exception e) {
                logger.error("[executeRefundTransfer]failed！cause by:{}", e);
            }
        });
    }

    private List<RefundItem> rebuildItemType(List<RefundItem> refundItemList) {
        List<RefundItem> newList = new ArrayList<>(refundItemList.size());
        for (RefundItem refundItem : refundItemList) {
            Map<String, Object> extraMap = refundItem.getExtraMap();
            if (CollectionUtils.isEmpty(extraMap)) {
                extraMap = new HashMap<>(3);
            }
            if (Objects.equals(2, refundItem.getItemType())) {
                extraMap.put("historyItemType", refundItem.getItemType());
                refundItem.setItemType(0);
            }
            extraMap.put("isHistoryRefundItem", 1);
            refundItem.setFeatures(JSON.toJSONString(extraMap));
            newList.add(refundItem);
        }
        return newList;
    }

    private void parseRefundParam(Refund refund, List<OrderRefundDetails> payDetailList) {
        Order order = null;
        if (Objects.equals(0L, refund.getUserId())) {
            OrderIndex orderIndex = orderIndexDao.selectOne(refund.getOrderNo());
            if (orderIndex != null) {
                order = orderDao.selectByOrderNo(orderIndex.getOrderNo(), orderIndex.getUserId());
            }
        } else {
            order = orderDao.selectByOrderNo(refund.getOrderNo(), refund.getUserId());
        }
        if (order != null) {
            refund.setUserId(order.getUserId());
            refund.setOrderType(order.getOrderType());
            refund.setPayType(order.getPayType());
        }

        Map<String, Object> extraMap = refund.getExtraMap();
        if (CollectionUtils.isEmpty(extraMap)) {
            extraMap = new HashMap<>(5);
        }
        extraMap.put("historyStatus", refund.getStatus());
        extraMap.put("isHistoryRefund", 1);
        extraMap.put("buyerRemarks", extraMap.get("note"));
        extraMap.put("actualDonationAmount", 0);
        extraMap.put("historyBizType", 1);
        if (Objects.isNull(refund.getWalletAmount())) {
            extraMap.put("actualPrincipalAmount", 0);
        } else {
            extraMap.put("actualPrincipalAmount", refund.getWalletAmount() / 100);
        }
        refund.setExtraMap(extraMap);
        convertRefundStatus(refund);
        List<OrderRefundDetails> refundDetailsList = rebuild0(refund);
        if (!CollectionUtils.isEmpty(refundDetailsList)) {
            payDetailList.addAll(refundDetailsList);
            refund.setRefundDetailInfo(JSON.toJSONString(ConvertUtils.convertList(refundDetailsList, InnerOrderRefundDetail.class)));
        }
    }

    /**
     * 1.0的数据结构
     * @param refund
     * @return
     * Date: 2021/9/27 4:38 下午
     */
    private List<OrderRefundDetails> rebuild0(Refund refund) {
        List<OrderRefundDetails> payDetailList = new ArrayList<>();
        try {
            Order order = orderDao.selectByOrderNo(refund.getOrderNo(), refund.getUserId());
            if (order == null) {
                return payDetailList;
            }
            String payInfo = order.getPayInfo();
            // 混合
            if (StringUtils.isNotBlank(payInfo)) {
                Map<String, Object> payInfoMap = JSON.parseObject(payInfo);
                Double cashAmount = Objects.nonNull(payInfoMap.get("cash_amount")) ? Double.valueOf(payInfoMap.get("cash_amount").toString()) : 0.0;
                Double thirdAmount = Objects.nonNull(payInfoMap.get("third_amount")) ? Double.valueOf(payInfoMap.get("third_amount").toString()) : 0.0;
                if (Objects.equals(19, order.getSource()) && cashAmount > 0 && thirdAmount > 0) {
                    Map<String, Object> extraMap = refund.getExtraMap();
                    Integer paymentId = Objects.nonNull(extraMap.get("payment_id")) ? Integer.valueOf(extraMap.get("payment_id").toString()) : 0;
                    // 三方
                    Integer refundThirdAmount = Objects.nonNull(extraMap.get("refund_third_amount")) ?
                            Integer.valueOf(extraMap.get("refund_third_amount").toString()) : 0;
                    if (wechatList.contains(paymentId)) {
                        OrderRefundDetails refundDetails = rebuildParam(1, refund, refundThirdAmount);
                        payDetailList.add(refundDetails);
                    }
                    if (alipayList.contains(paymentId)) {
                        OrderRefundDetails refundDetails = rebuildParam(2, refund, refundThirdAmount);
                        payDetailList.add(refundDetails);
                    }
                    // 现金
                    Integer refundCashAmount = Objects.nonNull(extraMap.get("refund_cash_amount")) ?
                            Integer.valueOf(extraMap.get("refund_cash_amount").toString()) : 0;
                    OrderRefundDetails refundDetails = rebuildParam(12, refund, refundCashAmount);
                    payDetailList.add(refundDetails);
                    return payDetailList;
                }
            }

            // 三方
            if (refund.getAmount() > 0) {
                boolean flag = false;
                Map<String, Object> extraMap = refund.getExtraMap();
                Integer paymentId = Objects.nonNull(extraMap.get("payment_id")) ?
                        Integer.valueOf(extraMap.get("payment_id").toString()) : 0;
                if (alipayList.contains(paymentId)) {
                    OrderRefundDetails refundDetails = rebuildParam(2, refund, refund.getAmount());
                    payDetailList.add(refundDetails);
                    flag = true;
                }
                if (wechatList.contains(paymentId)) {
                    OrderRefundDetails refundDetails = rebuildParam(1, refund, refund.getAmount());
                    payDetailList.add(refundDetails);
                    flag = true;
                }
                if (!flag) {
                    OrderRefundDetails refundDetails = rebuildParam(order.getPayType(), refund, refund.getAmount());
                    payDetailList.add(refundDetails);
                }
            }
            // 余额
            if (refund.getWalletAmount() > 0) {
                OrderRefundDetails refundDetails = rebuildParam(4, refund, refund.getWalletAmount());
                payDetailList.add(refundDetails);
            }
        } catch (Exception e) {
            logger.error("rebuild0 failed! cause by:{}", e);
        }
        return payDetailList;
    }

    private OrderRefundDetails rebuildParam(int payType, Refund refund, Integer amount) {
        OrderRefundDetails pay = new OrderRefundDetails();
        pay.setId(shardingKeyGenerator.generateSnowflakeNumKey());
        pay.setOrderNo(refund.getOrderNo());
        pay.setRefundNo(refund.getRefundNo());
        pay.setUserId(refund.getUserId());
        pay.setSellerId(refund.getSellerId());
        pay.setStoreId(refund.getStoreId());
        pay.setPayType(payType);
        pay.setRefundAmount(amount);
        pay.setBizType(5);
        return pay;
    }

    private void convertRefundStatus(Refund refund) {
        if (Objects.equals(151, refund.getStatus())) {
            refund.setStatus(10);
            return;
        }
        if (Objects.equals(100, refund.getStatus())) {
            refund.setStatus(30);
            return;
        }
        if (Objects.equals(101, refund.getStatus())) {
            refund.setStatus(40);
            return;
        }
        if (Objects.equals(103, refund.getStatus())) {
            refund.setStatus(40);
            return;
        }
        if (Objects.equals(102, refund.getStatus())) {
            refund.setStatus(50);
            return;
        }
        if (Objects.equals(150, refund.getStatus())) {
            refund.setStatus(0);
            return;
        }
        if (Objects.equals(203, refund.getStatus())) {
            refund.setStatus(10);
            return;
        }
        if (Objects.equals(0, refund.getStatus())) {
            refund.setStatus(10);
            return;
        }
    }

    @Override
    public Result cateringTransferRollback(OrderDataReviseRequest request) {
        int count = 0;
        Long lastId = 0L;
        OrderQuery orderQuery = buildOrderQuery11(request);
        try {
            for (int i = 0; i < dbSize; i++) {
                for (int j = 0; j < tbSize; j++) {
                    for (;;) {
                        orderQuery.setLastId(lastId);
                        List<Order> orderList = commonManager.scanOrder(orderQuery, i, j);
                        if (CollectionUtils.isEmpty(orderList)) {
                            break;
                        }
                        executeTransferRollback(orderList, i, j);
                        count += orderList.size();
                        logger.info("cateringTransferRollback:{}条", count);
                        if (orderList.size() < 200) {
                            break;
                        }
                        lastId = orderList.get(orderList.size() - 1).getId();
                        logger.info("cateringTransferRollback_lastId:{}", lastId);
                        Result<String> redisData = redisManager.get("catering_Transfer_Rollback");
                        if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                            return Result.successNullData();
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("[cateringTransferRollback]failed!cause by:{}", e);
            return Result.failureData(ExceptionConstants.SYSTEM_ERROR);
        }
        return Result.successNullData();
    }

    private void executeTransferRollback(List<Order> orderList, int i, int j) {
        while (workQueue.remainingCapacity() < 20) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executorService.submit(() -> {
            try {
                // 批量查询订单下的所有商品
                List<OrderItem> itemList = queryOrderItemList(orderList);

                for (Order order : orderList) {
                    buildOrderParamRollback(order);
                }
                // 回滚
                commonManager.batchUpdateOrderRollBack(orderList, i, j);
                commonManager.updateBizTypeRollBack(itemList, i, j);
                searchManager.indexOrder(orderList);
            } catch (Exception e) {
                logger.error("[executeTransfer]failed！cause by:{}", e);
            }
        });
    }

    private void buildOrderParamRollback(Order order) {
        Map<String, Object> extraMap = order.getExtraMap();
        if (!CollectionUtils.isEmpty(extraMap)) {
            if (Objects.nonNull(extraMap.get("historyOrderType"))) {
                order.setOrderType(Integer.valueOf(extraMap.get("historyOrderType").toString()));
            }
            if (Objects.nonNull(extraMap.get("historyPayType"))) {
                order.setPayType(Integer.valueOf(extraMap.get("historyPayType").toString()));
            }
            if (Objects.nonNull(extraMap.get("historyStatus"))) {
                order.setStatus(Integer.valueOf(extraMap.get("historyStatus").toString()));
            }
            if (Objects.nonNull(extraMap.get("historyPlatform"))) {
                order.setPerformancePlatform(extraMap.get("historyPlatform").toString());
            }
            if (Objects.nonNull(extraMap.get("historyPerformanceType"))) {
                order.setPerformanceType(Integer.valueOf(extraMap.get("historyPerformanceType").toString()));
            }
        }
    }


    private OrderQuery buildOrderQuery11(OrderDataReviseRequest request) {
        OrderQuery orderQuery = new OrderQuery();
//        orderQuery.setBizType(1);
        orderQuery.setSellerId(203192L);
//        orderQuery.setOrderNo("D60004B4B51F107390");
        orderQuery.setSize(200);
        return orderQuery;
    }

    private static List<String> paymentList = new ArrayList<>();

    static {
        paymentList.add("D602F2AD3C6E2F6246");
    }

    @Override
    public Result insertBatching() {
        int count = 0;
        OrderQuery orderQuery = buildOrderQuery111();
        try {
            for (int i = 0; i < dbSize; i++) {
                for (int j = 0; j < tbSize; j++) {
                    Long lastId = null;
                    for (;;) {
                        orderQuery.setLastId(lastId);
                        List<Long> orderIdList = commonManager.scanOrderId(orderQuery, i, j);
                        if (CollectionUtils.isEmpty(orderIdList)) {break;

                        }
                        List<Order> orderList = commonManager.listOrderById(orderIdList, i, j);
                        executeTransferBatching(orderList, i, j);
                        count += orderIdList.size();
                        logger.info("insertBatching:{}条", count);
                        if (orderIdList.size() < 200) {
                            break;
                        }
                        lastId = orderList.get(orderIdList.size() - 1).getId();
                    }
                }
            }
        } catch (Exception e) {
            logger.error("TemporaryController[insertBatching]failed,cause by: {}", e);
            return Result.failureData(ExceptionConstants.SYSTEM_ERROR);
        }
        return Result.successNullData();
    }

    @Override
    public Result updatePayType() {
        int count = 0;
        OrderQuery orderQuery = new OrderQuery();
//        orderQuery.setOrderNo("D60F6C9C26EA684079");
        orderQuery.setSellerId(39339L);
        orderQuery.setSize(500);
        try {
            for (int i = 0; i < dbSize; i++) {
                for (int j = 0; j < tbSize; j++) {
                    Long lastId = null;
                    for (;;) {
                        orderQuery.setLastId(lastId);
                        long startAt = System.currentTimeMillis();
                        List<Long> orderIdList = commonManager.scanOrderId(orderQuery, i, j);
                        if (CollectionUtils.isEmpty(orderIdList)) {
                            break;
                        }
                        List<Order> orderList = commonManager.listOrderById(orderIdList, i, j);
                        logger.info("query_time:{}ms", System.currentTimeMillis() - startAt);
                        executeTransfer1(orderList, i, j);
                        count += orderIdList.size();
                        logger.info("cateringTransfer:{}条", count);
                        if (orderIdList.size() < 500) {
                            break;
                        }
                        lastId = orderList.get(orderIdList.size() - 1).getId();
                        logger.info("cateringTransfer_lastId:{},i:{},j:{}", lastId, i, j);
                        Result<String> redisData = redisManager.get("catering_transfer");
                        if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                            return Result.successNullData();
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("[cateringTransfer]failed!cause by:{}", e);
            return Result.failureData(ExceptionConstants.SYSTEM_ERROR);
        }
        return Result.successNullData();
    }

    private void executeTransfer1(List<Order> orderList, int i, int j) {
        while (workQueue.remainingCapacity() < 20) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executorService.submit(() -> {
            try {
                List<BatchSyncEsMessage> messageList = new ArrayList<>(500);

                List<String> orderNoList = orderList.stream().map(Order::getOrderNo).collect(Collectors.toList());
                OrderQuery query = new OrderQuery();
                query.setOrderNoList(orderNoList);
//                List<OrderPayDetails> payIdList = commonManager.scanPayDetailsId(query, i, j);
//                if (!CollectionUtils.isEmpty(payIdList)) {
//                    List<Long> idList = payIdList.stream().map(OrderPayDetails::getId).collect(Collectors.toList());
//                    commonManager.deletePayDetailsById(idList, i, j);
//                }
                System.out.println("1111");

                // 新增支付明细列表
                List<OrderPayDetails> payDetailsList = new ArrayList<>();

                for (Order order : orderList) {
                    if (Objects.equals(0, order.getPayStatus())) {
                        continue;
                    }
                    messageList.add(buildMessage(order));

                    List<OrderPayDetails> orderPayList = new ArrayList<>();
                    setPayDetails1(order, orderPayList);

                    if (!CollectionUtils.isEmpty(orderPayList)) {
                        payDetailsList.addAll(orderPayList);
                        order.setPayDetailInfo(JSON.toJSONString(orderPayList));
                    }
                }
                System.out.println("2222");

                // 执行变更
                long startAt2 = System.currentTimeMillis();
                commonManager.batchUpdateOrderInfo(orderList, i, j);
                System.out.println("3333");

                if (!CollectionUtils.isEmpty(payDetailsList)) {
                    payDetailsDao.insertList(payDetailsList);
                }
                System.out.println("4444");

                messageManager.sendBatchSyncMessage(messageList);
                System.out.println("5555");
            } catch (Throwable e) {
                logger.error("[executeTransfer1]failed！cause by:{}", Throwables.getStackTraceAsString(e));
            }
        });
    }

    private void setPayDetails1(Order order, List<OrderPayDetails> payDetailsList) {
        Integer payType = order.getPayType();
        Map<String, Object> extraMap = order.getExtraMap();
        if (!CollectionUtils.isEmpty(extraMap) && Objects.nonNull(extraMap.get("historyPayType"))) {
            payType = Integer.valueOf(extraMap.get("historyPayType").toString());
        }
        String payInfo = order.getPayInfo();
        if (!StringUtils.isEmpty(payInfo)) {
            Map<String, Object> payInfoMap = JSON.parseObject(payInfo);
            Integer useWallet = Objects.nonNull(payInfoMap.get("use_wallet")) ?
                    Integer.valueOf(payInfoMap.get("use_wallet").toString()) : null;
            String amountStr = Objects.nonNull(payInfoMap.get("amount")) ? payInfoMap.get("amount").toString() : "0";
            Integer amount = 0;
            if (amountStr.contains(".")) {
                amount = new BigDecimal(amountStr).multiply(new BigDecimal(100)).intValue();
            }else {
                amount = Integer.valueOf(amountStr);
            }

            Integer walletAmount = 0;
            String walletAmountStr = Objects.nonNull(payInfoMap.get("wallet_amount")) ?
                    payInfoMap.get("wallet_amount").toString() : "0";
            if (walletAmountStr.contains(".")) {
                walletAmount = new BigDecimal(walletAmountStr).multiply(new BigDecimal(100)).intValue();
            }else {
                walletAmount = Integer.valueOf(walletAmountStr);
            }

            // from_system = 1  --> payType = 7 在线支付
            if (Objects.equals(1, order.getFromSystem())) {
                order.setPayType(7);
                OrderPayDetails payDetails = buildPayDetails(7, order, amount);
                payDetailsList.add(payDetails);
                return;
            }

            // 余额 + 三方
            if (walletAmount > 0) {
                // 如果amount = 0 那么就是一种支付方式：余额支付（4），如果大于0，那么就是混合支付 payType = 9 混合支付
                if (amount == 0) {
                    order.setPayType(4);
                    OrderPayDetails payDetails = buildPayDetails(4, order, walletAmount);
                    payDetailsList.add(payDetails);
                    return;
                }
                // 混合支付
                if (amount > 0) {
                    order.setPayType(9);
                    OrderPayDetails payDetails1 = buildPayDetails(4, order, walletAmount);
                    Integer newPayType = mapThirdPay(payType);
                    OrderPayDetails payDetails2 = buildPayDetails(newPayType, order, amount);
                    payDetailsList.add(payDetails1);
                    payDetailsList.add(payDetails2);
                    return;
                }
            }
            // 现金 + 三方支付
            if (Objects.equals(19, order.getSource())) {
                Object cashAmountObj = payInfoMap.get("cash_amount");
                Object thirdAmountObj = payInfoMap.get("third_amount");
                if (Objects.nonNull(cashAmountObj) && Objects.nonNull(thirdAmountObj)) {
                    Integer cashAmount = Integer.valueOf(cashAmountObj.toString());
                    Integer thirdAmount = Integer.valueOf(thirdAmountObj.toString());
                    if (cashAmount > 0 && thirdAmount > 0) {
                        // 混合支付场景 现金 + 三方支付 payType = 99
                        order.setPayType(99);
                        OrderPayDetails cashPay = buildPayDetails(12, order, cashAmount);
                        OrderPayDetails thirdPay = buildPayDetails(mapThirdPay(payType), order, thirdAmount);
                        payDetailsList.add(cashPay);
                        payDetailsList.add(thirdPay);
                        return;
                    }
                }
            }
            // 三方支付
            if (amount > 0) {
                Integer newPayType = mapThirdPay(payType);
                order.setPayType(newPayType);
                OrderPayDetails payDetails = buildPayDetails(newPayType, order, amount);
                payDetailsList.add(payDetails);
                return;
            }
            // 免支付 payType = 16 新餐饮
            if (Objects.equals(0, order.getActualAmount())) {
                order.setPayType(16);
                OrderPayDetails payDetails = buildPayDetails(16, order, 0);
                payDetailsList.add(payDetails);
                return;
            }
            // 未匹配到的支付类型
            OrderPayDetails payDetails = buildPayDetails(mapThirdPay(payType), order, amount);
            payDetailsList.add(payDetails);
        }
    }

    private void executeTransferBatching(List<Order> orderList, int i, int j) {
        while (workQueue.remainingCapacity() < 20) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executorService.submit(() -> {
            try {
                // 批量查询订单下的所有商品
                List<OrderItem> itemList = queryOrderItemList(orderList);
                // 商品ID列表
                List<Long> itemIdList = itemList.stream().map(OrderItem::getId).collect(Collectors.toList());
                // 商品加料
                List<WmOrderAttachGoods> attachGoodsList = orderAttachGoodsDao.selectList(itemIdList);
                // 按照订单号分组
                Map<String, List<OrderItem>> itemMap = itemList.stream().collect(Collectors.groupingBy(OrderItem::getOrderNo));
                // 新增商品加料列表
                List<OrderItemBatching> itemBatchingList = new ArrayList<>();

                for (Order order : orderList) {
                    buildItemBatchingParam(order, itemMap, itemBatchingList, attachGoodsList);
                }
                if (!CollectionUtils.isEmpty(itemBatchingList)) {
                    itemBatchingDao.insertList(itemBatchingList);
                }
            } catch (Exception e) {
                logger.error("[executeTransferBatching]failed！cause by:{}", e);
            }
        });
    }

    private OrderQuery buildOrderQuery111() {
        OrderQuery orderQuery = new OrderQuery();
        orderQuery.setSellerId(203192L);
        orderQuery.setSize(200);
        return orderQuery;
    }

    @Override
    public Result bakingOrderSync() {
        int count = 0;
        OrderQuery orderQuery = new OrderQuery();
        orderQuery.setBizType(4);
        orderQuery.setPerformanceTypeList(Lists.newArrayList(1, 2));
//        Date date = new Date();
//        orderQuery.setOrderAtEnd(date);
//        orderQuery.setOrderAtStart(DateUtils.before(date, Calendar.DAY_OF_YEAR, 30));
//        orderQuery.setOrderNo("D60F6C9C26EA684079");
//        orderQuery.setSellerId(39339L);
        orderQuery.setSize(500);
        try {
            for (int i = 0; i < dbSize; i++) {
                for (int j = 0; j < tbSize; j++) {
                    Long lastId = 580900268489637887L;
                    for (;;) {
                        orderQuery.setLastId(lastId);
                        long startAt = System.currentTimeMillis();
                        List<Order> orderList = commonManager.scanOrder(orderQuery, i, j);
                        if (CollectionUtils.isEmpty(orderList)) {
                            break;
                        }
                        logger.info("query_time:{}ms", System.currentTimeMillis() - startAt);
                        bakingOrderSyncExecute(orderList, i, j);
                        count += orderList.size();
                        logger.info("bakingOrderSync:{}条", count);
                        if (orderList.size() < 500) {
                            break;
                        }
                        lastId = orderList.get(orderList.size() - 1).getId();
                        logger.info("bakingOrderSync_lastId:{},i:{},j:{}", lastId, i, j);

                        Result<String> redisData = redisManager.get("baking_Order_Sync");
                        if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                            return Result.successNullData();
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("[bakingOrderSync]failed!cause by:{}", e);
            return Result.failureData(ExceptionConstants.SYSTEM_ERROR);
        }
        return Result.successNullData();
    }

    @Override
    public Result updateItemDiscount() {
        for (String str : ListConst3.list) {
            String[] split = str.split("-");
            String orderNo = split[0];
            OrderIndex orderIndex = orderIndexDao.selectOne(orderNo);
            if (orderIndex == null) {
                continue;
            }
            Order order = orderDao.selectByOrderNo(orderIndex.getOrderNo(), orderIndex.getUserId());
            if (order == null) {
                continue;
            }
            List<OrderItem> itemList = orderItemDao.selectByOrderNo(orderIndex.getOrderNo(), orderIndex.getUserId());
            if (!CollectionUtils.isEmpty(itemList)) {
                for (OrderItem orderItem : itemList) {
                    if (ListConst4.list.contains(orderItem.getId())) {
                        OrderItem update = new OrderItem();
                        update.setId(orderItem.getId());
                        update.setUserId(orderItem.getUserId());
                        update.setDiscountAmount(orderItem.getDiscountAmount() - 900);
                        orderItemDao.update(update);
                    }
                }

                List<OrderItem> updateItemList = orderItemDao.selectByOrderNo(orderIndex.getOrderNo(), orderIndex.getUserId());
                Order update = new Order();
                update.setId(order.getId());
                update.setUserId(order.getUserId());
                update.setItemInfo(JSON.toJSONString(ConvertUtils.convertList(updateItemList, InnerOrderItem.class)));
                orderDao.update(update);
            }
        }
        return Result.successNullData();
    }

    private void bakingOrderSyncExecute(List<Order> orderList, int i, int j) {
        while (workQueue.remainingCapacity() < 20) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executorService.submit(() -> {
            try {
                searchManager.indexOrder(orderList);
            } catch (Throwable e) {
                logger.error("[bakingOrderSyncExecute]failed！cause by:{}", Throwables.getStackTraceAsString(e));
            }
        });
    }

    @Override
    public Result cateringTransferManual() {
        int count = 0;
        for (String orderNo : ListConst11.list) {
            try {
                OrderIndex orderIndex = orderIndexDao.selectOne(orderNo);
                if (orderIndex != null) {
                    Order order = orderDao.selectByOrderNo(orderIndex.getOrderNo(), orderIndex.getUserId());
                    if (order != null) {
//                        executeTransfer(Lists.newArrayList(order), 0, 0);
                    }
                }
            } catch (Exception e) {
                logger.error("[cateringTransferManual]failed!cause by:{}", e);
                return Result.failureData(ExceptionConstants.SYSTEM_ERROR);
            }
        }
        return Result.successNullData();
    }

    int stopHour = 7;

    @Override
    public Result findMergeDeleted() {
        Result result = new Result<>();
        int total = 0;
        int size = 1000;
        try {
            logger.info("[findMergeDeleted][start]");
            OrderQuery orderQuery = new OrderQuery();
            orderQuery.setIsDeleted(-3);
            orderQuery.setSize(size);
            for (int i = 17; i < dbSize; i++) {
                for (int j = 0; j < tbSize; j++) {
                    Long lastId = null;
                    for (; ; ) {
                        if (CommonUtils.getHour() == stopHour) {
                            logger.info("findMergeDeleted[stopHour], i:{}, j:{}, count:{}, lastId:{}", i, j, total, lastId);
                            return Result.successNullData();
                        }
                        Result<String> redisData = redisManager.get("find-merge-delete");
                        if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                            result.setStatus(true);
                            result.setData(lastId);
                            return result;
                        }
                        orderQuery.setLastId(lastId);
                        List<Order> orderList = commonManager.scanOrderDeleted(orderQuery, i, j);
                        if (CollectionUtils.isEmpty(orderList)) {
                            break;
                        }
                        List<MergeOrder> list = new ArrayList<>(size);
                        for (Order order : orderList) {
                            MergeOrder data = new MergeOrder();
                            data.setOrderId(order.getId());
                            data.setOrderNo(order.getOrderNo());
                            data.setUserId(order.getUserId());
                            data.setSellerId(order.getSellerId());
                            data.setStoreId(order.getStoreId());
                            list.add(data);
                        }
                        mergeOrderDao.insertList(list);
                        total += orderList.size();
                        lastId = orderList.get(orderList.size() - 1).getId();
                        logger.info("[findMergeDeleted] total:{}, i:{}, j:{}, lastId:{}", total, i, j, lastId);
                        if (orderList.size() < size) {
                            break;
                        }
                    }
                }
            }
            logger.info("[findMergeDeleted][end] total:{}", total);

            result.setStatus(true);
        } catch (Exception e) {
            logger.error("[findMergeDeleted]failed!cause by:{}", e);
            result.setException(ExceptionConstants.SYSTEM_ERROR);
        }
        return result;
    }

    /**
     * （物理）删除表中的压测数据
     * @param orderList
     * @return:
     * @Date: 2020/12/14 11:35 AM
     */
    public void doExecDelTestOrder(List<Order> orderList, int i, int j) {
        while (workQueue.remainingCapacity() < 20) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executorService.submit(() -> {
            try {
                // 删除订单
                List<Long> idList = orderList.stream().map(Order::getId).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(idList)) {
                    commonManager.deleteOrderTest(idList, i, j);
                }
                List<String> orderNoList = orderList.stream().map(Order::getOrderNo).collect(Collectors.toList());
                // 删除商品
                if (!CollectionUtils.isEmpty(orderNoList)) {
                    commonManager.deleteItemTest(orderNoList, i, j);
                }
                // 删除退款单
                if (!CollectionUtils.isEmpty(orderNoList)) {
                    refundDao.deleteByOrderNos(orderNoList);
                }
            } catch (Exception e) {
                logger.error("[quene_order_routing]failed！cause by:{}", e);
            }
        });
    }
}








