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

import cn.qmai.data.encrypt.service.DataEncryptService;
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.collect.Lists;
import com.zm.order.tool.server.component.ShardingKeyGenerator;
import com.zm.order.tool.server.constants.*;
import com.zm.order.tool.server.controller.DataDesensiHandler;
import com.zm.order.tool.server.cy.CyOrderRelationsDao;
import com.zm.order.tool.server.dao.*;
import com.zm.order.tool.server.design.DesignOrderDao;
import com.zm.order.tool.server.dto.SearchOrderDTO;
import com.zm.order.tool.server.helper.OrderScriptHelper;
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.newdatasource.*;
import com.zm.order.tool.server.query.*;
import com.zm.order.tool.server.request.OrderDataReviseRequest;
import com.zm.order.tool.server.service.ExceptionConstants;
import com.zm.order.tool.server.service.OrderScriptService;
import com.zm.order.tool.server.stream.convert.OrderStreamConverter;
import com.zm.order.tool.server.tb.TbOrderDiscountDao;
import com.zm.order.tool.server.tempdb.*;
import com.zm.order.tool.server.utils.ConvertUtils;
import com.zm.order.tool.server.utils.DateUtils;
import com.zm.util.dto.Result;
import net.sf.jsqlparser.JSQLParserException;
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.Assert;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;

import static com.zm.order.tool.server.constants.CommonConstants.ES_NEW_INDEX_TOPIC;

/**
 * @author NianChang
 * @ClassName ScriptServiceImpl
 * @date 2021/02/20 9:51 上午
 */
@Service
@SuppressWarnings("all")
public class OrderScriptServiceImpl implements OrderScriptService, InitializingBean {

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

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

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

    private BlockingQueue workQueue;

    private ExecutorService executorService;

    @Autowired
    private TempOrderDao tempOrderDao;

    @Autowired
    private TempOrderCaterDao tempOrderCaterDao;

    @Autowired
    private TempOrderBakingStdDao tempOrderBakingStdDao;

    @Autowired
    private RedisManager redisManager;

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private OrderIndexDao orderIndexDao;

    @Autowired
    private SearchManager searchManager;

    @Autowired
    private CyOrderRelationsDao cyRelationsDao;

    @Autowired
    private OrderItemDao orderItemDao;

    @Autowired
    private OrderScriptHelper helper;

    @Autowired
    private AsyncMessageManager asyncMessageManager;

    @Autowired
    private InnerApiManager innerApiManager;

    @Autowired
    private AsyncMessageManager messageManager;

    @Autowired
    private CommonManager commonManager;

    @Autowired
    private ShardingKeyGenerator keyGenerator;
    @Autowired
    private Mapper mapper;
    @Autowired
    private OrderPayDetailsDao payDetailsDao;
    @Autowired
    private RefundDao refundDao;
    @Autowired
    private NewDataSourceRefundDao newDataSourceRefundDao;
    @Autowired
    private RefundItemDao refundItemDao;

    @Autowired
    private NewDataSourceRefundItemDao newDataSourceRefundItemDao;

    @Autowired
    private OrderPayDetailsDao orderPayDetailsDao;

    @Autowired
    private TbOrderDiscountDao tbOrderDiscountDao;

    @Autowired
    private OrderDiscountDao orderDiscountDao;

    @Autowired
    private ShardingKeyGenerator shardingKeyGenerator;

    @Autowired
    private OrderRefundDetailsDao refundDetailsDao;

    @Autowired
    private NewDataSourceOrderRefundDetailsDao newDataSourceOrderRefundDetailsDao;

    @Autowired
    private NewDataSourceOrderDiscountDao newDataSourceOrderDiscountDao;

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

    static {
        sellerIdList.add(13377L);
        sellerIdList.add(50161L);
        sellerIdList.add(201424L);
        sellerIdList.add(202973L);
        sellerIdList.add(203192L);
        sellerIdList.add(203490L);
        sellerIdList.add(203548L);
        sellerIdList.add(204102L);
        sellerIdList.add(204365L);
        sellerIdList.add(205387L);
        sellerIdList.add(206021L);
        sellerIdList.add(206106L);
        sellerIdList.add(206198L);
        sellerIdList.add(206241L);
        sellerIdList.add(206467L);
        sellerIdList.add(206954L);
        sellerIdList.add(207243L);
        sellerIdList.add(207262L);
        sellerIdList.add(207343L);
        sellerIdList.add(207831L);
        sellerIdList.add(207964L);
    }

    @Override
    public Result transferOrderData(OrderDataReviseRequest request) {
        Result result = new Result<>();
        int count = 0;
        OrderQuery orderQuery = helper.buildQueryByTransfer(request);
        try {
            // 构建查询临时库条件
            for (int i = 0; i < dbSize; i++) {
                orderQuery.setDbIndex(i);
                for (int j = 0; j < tbSize; j++) {
                    orderQuery.setTbIndex(j);
                    Long lastId = 0L;
                    for (; ; ) {
                        orderQuery.setLastId(lastId);
                        // 查询
                        List<TempOrder> tempOrderList = tempOrderDao.selectList(orderQuery);
                        if (CollectionUtils.isEmpty(tempOrderList)) {
                            break;
                        }
                        transferQueue(tempOrderList);
                        count += tempOrderList.size();
                        logger.info("transferOrderData:{}条", count);
                        if (tempOrderList.size() < 200) {
                            break;
                        }
                        lastId = tempOrderList.get(tempOrderList.size() - 1).getId();
                        Result<String> redisData = redisManager.get("transfer_order_data");
                        if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                            result.setStatus(true);
                            result.setData(lastId);
                            return result;
                        }
                    }
                }
            }
            result.setStatus(true);
        } catch (Exception e) {
            logger.error("[transferOrderData]failed!cause by:{}", e);
            result.setException(ExceptionConstants.SYSTEM_ERROR);
        }
        return result;
    }

    private void transferQueue(List<TempOrder> tempOrderList) {
        while (workQueue.remainingCapacity() < 20) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executorService.submit(() -> {
            try {
                List<Order> orderList = new ArrayList<>(tempOrderList.size());
                List<OrderIndex> indexList = new ArrayList<>(tempOrderList.size());
                List<CyOrderRelations> relationsList = new ArrayList<>(tempOrderList.size());
                List<OrderItem> itemList = helper.queryItemList(tempOrderList);
                Map<String, List<OrderItem>> itemMap = itemList.stream().collect(
                        Collectors.groupingBy(OrderItem::getOrderNo));
                // 30天之前
                long beforeTime = DateUtils.before(new Date(), Calendar.DATE, 30).getTime();
                for (TempOrder tempOrder : tempOrderList) {
                    orderList.add(helper.getOrder(beforeTime, tempOrder, itemMap));
                    indexList.add(helper.getOrderIndex(tempOrder));
                    relationsList.add(helper.getOrderRelations(tempOrder));
                }
                orderDao.insertList(orderList);
                orderItemDao.inserts(itemList);
                orderIndexDao.insertList(indexList);
                cyRelationsDao.insertList(relationsList);
                searchManager.indexOrder(orderList);
            } catch (Exception e) {
                logger.error("[transferQueue]failed！cause by:{}", e);
            }
        });
    }

    @Override
    public Result syncOrderData(OrderDataReviseRequest request) {
        Result result = new Result<>();
        try {
            logger.info("[service_before]");
            Assert.notNull(request.getOrderNo(), "订单号为空");
            String orderNo = request.getOrderNo();
            String[] split = orderNo.split("-");
            for (int i = 0; i < split.length; i++) {
                OrderIndex orderIndex = orderIndexDao.selectOne(split[i]);
                if (orderIndex != null) {
                    Order order = orderDao.selectByOrderNoAll(orderIndex.getOrderNo(), orderIndex.getUserId());
                    if (order != null) {
                        searchManager.indexOrder(order, null);
                    }

                    Order order1 = newOrderDao.selectByOrderNo(orderIndex.getOrderNo(), orderIndex.getUserId());
                    if (order1 != null) {
                        searchManager.indexOrder(Lists.newArrayList(order1), ES_NEW_INDEX_TOPIC);
                    }
                }
            }
            result.setStatus(true);
        } catch (Exception e) {
            logger.error("[syncOrderData]failed!cause by:{}", e);
            result.setException(ExceptionConstants.SYSTEM_ERROR);
        }
        return result;
    }

    @Autowired
    OrderUserRelationDao relationDao;
    
    @Override
    public Result syncOrderDataList(OrderDataReviseRequest request) {
        int count = 0;
        List<String> orderNoList = request.getOrderNoList();
        if (!CollectionUtils.isEmpty(orderNoList)) {
            for (String s : orderNoList) {
                OrderIndex orderIndex = orderIndexDao.selectOne(s);
                if (orderIndex != null) {
                    Order order = orderDao.selectByOrderNo(orderIndex.getOrderNo(), orderIndex.getUserId());
                    if (order != null) {
                        try {
                            execute(order);
                            count++;
                            logger.info("syncOrderDataList_count:{}", count);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        } else if (!CollectionUtils.isEmpty(ListConst.list)) {
            for (String orderNo : ListConst.list) {
                OrderIndex orderIndex = orderIndexDao.selectOne(orderNo);
                if (orderIndex != null) {
                    Order order = orderDao.selectByOrderNo(orderIndex.getOrderNo(), orderIndex.getUserId());
                    if (order != null) {
                        try {
                            execute(order);
                            count++;
                            logger.info("syncOrderDataList_count:{}", count);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return Result.successNullData();
    }

    @Override
    public void scanSyncExceptionOrder() {
        int count = 0;
        Date now = new Date();
        final String[] includes = {"orderNo"};
        try {
            SearchOrderQuery query = buildQuery(now);
            SearchOrderDTO orderDTO = searchManager.searchOrder(query, includes, null, 5);
            if (!CollectionUtils.isEmpty(orderDTO.getOrderList())) {
                for (BaseIndexOrder index : orderDTO.getOrderList()) {
                    OrderIndex orderIndex = indexDao.selectOne(index.getOrderNo());
                    if (orderIndex != null) {
                        Order order = orderDao.selectByOrderNo(orderIndex.getOrderNo(), orderIndex.getUserId());
                        if (order != null) {
                            Order update = new Order();
                            update.setId(order.getId());
                            update.setUserId(order.getUserId());
                            orderDao.update(update);
                            searchManager.indexOrder(order,null);
                            count++;
                        }
                    }
                }
            }
            logger.info("[scanSyncExceptionOrder]count:{}", count);
        } catch (Exception e) {
            logger.error("[scanSyncExceptionOrder]cause by:{}", e);
        }
    }

    private SearchOrderQuery buildQuery(Date now) {
        SearchOrderQuery query = new SearchOrderQuery();
        query.setOrderAtStart(DateUtils.before(DateUtils.getStartDate0(now), Calendar.YEAR, 1));
        query.setIndexRouteSeller(CommonConstants.INDEX_ROUTES);
        query.setOrderAtEnd(now);
        query.setSpecialDeleted(1);
        query.setPageNo(1);
        query.setPageSize(1000);
        return query;
    }

    public static void main(String[] args) {
        System.out.println(DateUtils.before(DateUtils.getStartDate0(new Date()), Calendar.YEAR, 1).getTime());
    }

    private void execute(Order order) throws IOException {
        while (workQueue.remainingCapacity() < 20) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executorService.submit(() -> {
            try {
                searchManager.indexOrder(order, null);
            } catch (Exception e) {
                e.printStackTrace();
            }

            OrderUserRelationQuery query = new OrderUserRelationQuery();
            query.setOrderNo(order.getOrderNo());
            List<OrderUserRelation> relations = relationDao.selectList(query);
            if (!CollectionUtils.isEmpty(relations)) {
                for (OrderUserRelation relation : relations) {
                    if (relation.getIsRoot().equals(1)) {
                        Order del = orderDao.selectByOrderNo(relation.getOrderNo(), relation.getUserId());
                        searchManager.deleteOrder(del.getId(), del.getSellerId());
                    }
                }
            }
        });

    }

    @Override
    public Result orderMessagePush(OrderPush orderPush) {
        Assert.notNull(orderPush.getOrderNo(), "订单号为空");
        Assert.notNull(orderPush.getScene(), "场景值为空");
        Assert.notNull(orderPush.getStatus(), "订单状态为空");
        OrderIndex orderIndex = orderIndexDao.selectOne(orderPush.getOrderNo());
        if (orderIndex != null) {
            Order order = orderDao.selectByOrderNo(orderIndex.getOrderNo(), orderIndex.getUserId());
            if (order != null) {
                OrderPush snapshot = new OrderPush();
                snapshot.setBizType(order.getBizType());
                snapshot.setOrderNo(order.getOrderNo());
                snapshot.setUserId(order.getUserId());
                snapshot.setSellerId(order.getSellerId());
                snapshot.setStoreId(order.getStoreId());
                snapshot.setScene(orderPush.getScene());
                snapshot.setStatus(orderPush.getStatus());
                snapshot.setOrderAt(order.getOrderAt());
                snapshot.setVersion(order.getVersion());
                if (Objects.equals(1, orderPush.getPushType())) {
                    messageManager.orderMessagePush(snapshot);
                }
                if (Objects.equals(2, orderPush.getPushType())) {
                    innerApiManager.noticePushOrder(snapshot);
                }
                if (Objects.equals(3, orderPush.getPushType())) {
                    innerApiManager.noticePushOrder(snapshot);
                    messageManager.orderMessagePush(snapshot);
                }
            }
        }
        return Result.successNullData();
    }

    @Override
    public Result messagePushRefund(OrderPush orderPush) {
        Assert.notNull(orderPush.getRefundNo(), "退款单号为空");
        Refund refund = refundDao.selectByRefundNo(orderPush.getRefundNo());
        if (Objects.equals(1, orderPush.getPushType())) {

        }
        if (Objects.equals(2, orderPush.getPushType())) {
            innerApiManager.noticePushRefund(refund, "storeApplyRefund");
        }
        if (Objects.equals(3, orderPush.getPushType())) {

        }
        return Result.successNullData();
    }

    @Override
    public Result orderMessagePushList(OrderPush orderPush) {
        Assert.notNull(orderPush.getScene(), "场景值为空");
        Assert.notNull(orderPush.getStatus(), "订单状态为空");
        int count = 0;
        for (String orderNo : ListConst.list) {
            OrderIndex orderIndex = orderIndexDao.selectOne(orderNo);
            if (orderIndex != null) {
                Order order = orderDao.selectByOrderNo(orderIndex.getOrderNo(), orderIndex.getUserId());
                OrderPush snapshot = new OrderPush();
                snapshot.setBizType(5);
                snapshot.setOrderNo(order.getOrderNo());
                snapshot.setUserId(order.getUserId());
                snapshot.setSellerId(order.getSellerId());
                snapshot.setStoreId(order.getStoreId());
                snapshot.setScene(orderPush.getScene());
                snapshot.setOrderAt(order.getOrderAt());
                snapshot.setVersion(order.getVersion());
                snapshot.setStatus(orderPush.getStatus());
                messageManager.orderMessagePush(snapshot);
                innerApiManager.noticePushOrder(snapshot);
                count++;
                logger.info("push_count:{}", count);
            }
        }
        return Result.successNullData();
    }

    @Override
    public Result orderMessageCanCelPush() {
        logger.info("[orderMessagePush]before!");
        int count = 0;
        for (String orderNo : ListConst.list) {
            Order order = queryOrder(orderNo);
            if (order != null) {
                count++;
                innerApiManager.noticeOrderCancel(order);
            }
        }
        for (String orderNo : ListConst2.list) {
            Order order = queryOrder(orderNo);
            if (order != null) {
                count++;
                innerApiManager.noticeOrderCancel(order);
            }
        }
        for (String orderNo : ListConst3.list) {
            Order order = queryOrder(orderNo);
            if (order != null) {
                count++;
                innerApiManager.noticeOrderCancel(order);
            }
        }
        for (String orderNo : ListConst5.list) {
            Order order = queryOrder(orderNo);
            if (order != null) {
                count++;
                innerApiManager.noticeOrderCancel(order);
            }
        }
        logger.info("ORDER_MESSAGE_PUSH_COUNT:{}", count);
        return Result.successNullData();
    }

    private Order queryOrder(String orderNo) {
        OrderIndex orderIndex = orderIndexDao.selectOne(orderNo);
        if (orderIndex != null) {
            return orderDao.selectByOrderNo(orderIndex.getOrderNo(), orderIndex.getUserId());
        }
        return null;
    }

    @Override
    public Result orderDataCorrection(DataCorrectionRequest request) {
        logger.info("[orderDataCorrection]before!request:{}", request);
        Assert.notNull(request.getOrderNo(), "订单号为空");
        Assert.notNull(request.getUserId(), "用户ID为空");
        Order order = orderDao.selectByOrderNo(request.getOrderNo(), request.getUserId());
        OrderPayDetails payDetails = buildPayInfo(order, request);
        if (payDetails != null) {
            payDetailsDao.insert(payDetails);
            InnerOrderPayDetails innerOrderPayDetails = mapper.map(payDetails, InnerOrderPayDetails.class);
            order.setPayDetailInfo(JSON.toJSONString(Lists.newArrayList(innerOrderPayDetails)));
        }
        request.setId(order.getId());
        orderDao.dataUpdate(request);
        messageManager.sendOrderSyncEsMessage(order.getOrderNo(), order.getUserId(), order.getVersion() + 1);
        return Result.successNullData();
    }


    private OrderPayDetails buildPayInfo(Order order, DataCorrectionRequest request) {
        if (Objects.equals(5, order.getBizType()) && Objects.equals(1, request.getInsertPay())) {
            OrderPayDetails payDetails = new OrderPayDetails();
            payDetails.setId(keyGenerator.generateSnowflakeNumKey());
            payDetails.setOrderNo(order.getOrderNo());
            payDetails.setUserId(order.getUserId());
            payDetails.setAmount(order.getActualAmount());
            payDetails.setPayType(order.getPayType());
            payDetails.setStoreId(order.getStoreId());
            payDetails.setSellerId(order.getSellerId());
            payDetails.setOrderAt(order.getOrderAt());
            payDetails.setPayAt(order.getPayAt());
            payDetails.setOrderType(order.getOrderType());
            payDetails.setSource(Objects.nonNull(order.getSource()) ? order.getSource() : 0);
            payDetails.setPayNo(Objects.nonNull(order.getPayNo()) ? order.getPayNo() : "");
            payDetails.setThirdPayNo(Objects.nonNull(order.getThirdPayNo()) ? order.getThirdPayNo() : "");
            return payDetails;
        }
        return null;
    }

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

    static {
        syncSellerId.add(205387L);
    }

    @Autowired
    private OrderStreamConverter orderStreamConverter;

    // TODO
    @Override
    public Result syncEs() {
        int count = 0;
        Date current = new Date();
        Date queryStartAt = DateUtils.before(current, Calendar.DAY_OF_YEAR, 365);
        try {
            for (Long sellerId : syncSellerId) {
                OrderQuery orderQuery = new OrderQuery();
                orderQuery.setSellerId(sellerId);
                orderQuery.setSize(200);
                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);
                            executeSync(orderList, i, j);
                            count += orderIdList.size();
                            logger.info("syncEsData:{}条", count);
                            if (orderIdList.size() < 200) {
                                break;
                            }
                            lastId = orderIdList.get(orderIdList.size() - 1);
                            logger.info("syncEsData_lastId:{},i:{},j:{}", lastId, i, j);
                            Result<String> redisData = redisManager.get("sync_es_data_1");
                            if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                                return Result.successNullData();
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("[syncEs]failed!cause by:{0}", e);
            return Result.failureData(ExceptionConstants.SYSTEM_ERROR);
        }
        return Result.successNullData();
    }

    private void executeSync(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<Order> converted = new ArrayList<>(orderList.size());
                orderList.forEach(each -> {
                    // 枚举值
                    Order newOrder = (Order) orderStreamConverter.streamIn(each);
                    converted.add(newOrder);
                });

                searchManager.indexOrder(filter(converted), ES_NEW_INDEX_TOPIC);
            } catch (Exception e) {
                logger.error("[executeSync]failed！cause by:{}", e);
            }
        });
    }

    private List<Order> filter(List<Order> converted) {
        List<Order> newList = new ArrayList<>(converted.size());
        for (Order order : converted) {
            Integer bizType = order.getBizType();
            if (order.getOrderSubType() == 1 || order.getOrderSubType() == 2) {
                OrderUserRelation relation = relationDao.selectRoot(order.getOrderNo());
                if (relation == null) {
                    newList.add(order);
                    continue;
                }
                if (Objects.equals(order.getUserId(), relation.getUserId())) {
                    newList.add(order);
                }
                continue;
            }
            newList.add(order);
        }
        return newList;
    }

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

    private OrderQuery buildOrderQuery() {
        OrderQuery orderQuery = new OrderQuery();
        orderQuery.setSellerId(203009L);
//        orderQuery.setOrderNo("D5E82F6E4A79799132");
        orderQuery.setSize(200);
        return orderQuery;
    }

    @Override
    public void afterPropertiesSet() {
        workQueue = new ArrayBlockingQueue(20);
            executorService = new ThreadPoolExecutor(8, 8, 1,
                TimeUnit.MINUTES, workQueue,
                new NamedThreadFactory("script-order-data-thread"),
                new ThreadPoolExecutor.AbortPolicy());
    }

    @Override
    public void delEs() {
        try {
            SearchOrderQuery searchOrderQuery = new SearchOrderQuery();
            Date start = DateUtils.getStartDate(DateUtils.before(Calendar.DAY_OF_YEAR, CommonConstants.DAYS_OF_ES_OVER_TIME));
            Date end = DateUtils.getEndDate(DateUtils.before(Calendar.DAY_OF_YEAR, CommonConstants.DAYS_OF_ES_OVER_TIME));
            searchOrderQuery.setOrderAtStart(start);
            searchOrderQuery.setOrderAtEnd(end);
            searchManager.delOrder(searchOrderQuery);
        } catch (Throwable e) {
            logger.error("[delEs]failed！cause by:{}", e);
        }

    }
    
    @Autowired
    private DataEncryptService encryptService;

    @Autowired
    private OrderStreamConverter streamConverter;

    @Override
    public Result updateItemType() {
        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) {
                    if (StringUtils.isNotEmpty(order.getMobile())) {
                        try {
                            order.setMobileCipher(encryptService.encrypt(order.getMobile()));
                            orderDao.updateItemInfo(order);
                        } catch (JSQLParserException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        logger.info("updateItemTypeCount:{}", count);
        return Result.successNullData();
    }

    private void executeUpdateItem(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 {
                for (Order order : orderList) {
                    List<OrderItem> orderItemList = orderItemDao.selectByOrderNo(order.getOrderNo(), order.getUserId());
                    if (CollectionUtils.isEmpty(orderItemList)) {
                        continue;
                    }
                    Boolean updataItemFlag = false;
                    for (OrderItem orderItem : orderItemList) {
                        if (Objects.equals(1, orderItem.getItemType())) {
                            orderItem.setItemType(3);
                            orderItemDao.updateItemType(orderItem);
                            updataItemFlag = true;
                        }
                    }
                    if (updataItemFlag) {
                        order.setItemInfo(JSON.toJSONString(ConvertUtils.convertList(orderItemList, InnerOrderItem.class)));
                        orderDao.updateItemInfo(order);
                    }
                }
            } catch (Exception e) {
                logger.error("[executeSync]failed！cause by:{}", e);
            }
        });
    }

    @Override
    public Result insertOrderPayDetails(OrderDataReviseRequest request) {
        Result result = new Result<>();
        try {
            logger.info("[insertOrderPayDetails_before]");
            Assert.notNull(request.getOrderNo(), "订单号为空");
            String orderNo = request.getOrderNo();
            String[] split = orderNo.split("-");
            for (int i = 0; i < split.length; i++) {
                OrderIndex orderIndex = orderIndexDao.selectOne(split[i]);
                if (orderIndex != null) {
                    Order order = orderDao.selectByOrderNo(orderIndex.getOrderNo(), orderIndex.getUserId());
                    if (order != null) {

                        //构建OrderPayDetails
                        OrderPayDetails orderPayDetails = helper.buildOrderPayDetails(order);

                        //构建订单支付快照
                        List<OrderPayDetails> payDetailsList = new ArrayList<>();
                        String payDetailInfo = order.getPayDetailInfo();
                        //判断原支付快照是否有数据，有就在此基础上add
                        if (!StringUtils.isEmpty(payDetailInfo) && !Objects.equals("PF", payDetailInfo)) {
                            payDetailsList = JSON.parseArray(payDetailInfo, OrderPayDetails.class);
                        }
                        payDetailsList.add(orderPayDetails);
                        order.setPayDetailInfo(JSON.toJSONString(payDetailsList));

                        commonManager.insertOrderPayDetails(orderPayDetails, order);
                    }
                }
            }
            result.setStatus(true);
        } catch (Throwable e) {
            logger.error("[insertOrderPayDetails]failed!cause by:{}", e);
            result.setException(ExceptionConstants.SYSTEM_ERROR);
        }
        return result;
    }

    @Override
    public Result updateOrderDeleted(OrderDataReviseRequest request) {
        Result result = new Result<>();
        try {
            logger.info("[updateOrderDeleted_start]");
            Assert.notNull(request.getOrderNo(), "订单号为空");
            String orderNo = request.getOrderNo();
            String[] split = orderNo.split("-");
            for (int i = 0; i < split.length; i++) {
                deleteOrder(split[i]);
            }
            result.setStatus(true);
        } catch (Throwable e) {
            logger.error("[updateOrderDeleted]failed!cause by:{}", e);
            result.setException(ExceptionConstants.SYSTEM_ERROR);
        }
        return result;
    }

    @Override
    public Result updateOrderDelete() {
        int count = 0;
        for (String orderNo : ListConst10.list) {
            deleteOrder(orderNo);
            count++;
            logger.info("delete_count:{}", count);
        }
        return Result.successNullData();
    }

    private void deleteOrder(String orderNo1) {
        OrderIndex orderIndex = orderIndexDao.selectOne(orderNo1);
        if (orderIndex != null) {
            Order order = orderDao.selectByOrderNo(orderIndex.getOrderNo(), orderIndex.getUserId());
            if (order != null) {
                order.setIsDeleted(-1);
                orderDao.updateDeleted(order);
                try {
                    searchManager.indexOrder(order, null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public Result deleteOrder(OrderDataReviseRequest request) {
        Result result = new Result();
        Assert.notNull(request.getUserId(), "用户ID为空");
        Assert.notNull(request.getOrderNo(), "订单号为空");

        try {
            Order order = orderDao.selectByOrderNo(request.getOrderNo(), request.getUserId());
            if (order != null) {
                searchManager.deleteOrder(order.getId(), order.getSellerId());
            }
            result.setStatus(true);
        } catch (Exception e) {
            logger.error("[deleteOrder]failed!cause by:{}", e);
            result.setException(ExceptionConstants.SYSTEM_ERROR);
        }
        return result;
    }

    @Override
    public Result deleteMultiOrder() {
        int count = 0;
        int pageNo = 1;
        try {
            SearchOrderQuery query = new SearchOrderQuery();
            query.setSellerIdList(Lists.newArrayList(45719L, 46765L));
            query.setOrderAtStart(DateUtils.getStartDate(new Date()));
            query.setOrderAtEnd(DateUtils.getEndDate(new Date()));
            query.setPageSize(200);
            for (;;) {
                query.setPageNo(pageNo);
                SearchOrderDTO searchOrder = searchManager.searchOrder(query);
                if (searchOrder == null) {
                    break;
                }
                List<BaseIndexOrder> orderList = searchOrder.getOrderList();
                if (CollectionUtils.isEmpty(orderList)) {
                    break;
                }

                for (BaseIndexOrder baseIndexOrder : orderList) {
                    Order order = orderDao.selectByOrderNo(
                            baseIndexOrder.getOrderNo(), baseIndexOrder.getUserId());
                    if (order != null) {
                        Map<String, Object> extraMap = order.getExtraMap();
                        if (!CollectionUtils.isEmpty(extraMap)) {
                            if (Objects.nonNull(extraMap.get("masterId"))) {
                                Long masterId = Long.valueOf(extraMap.get("masterId").toString());
                                if (!Objects.equals(masterId, order.getId())) {
                                    searchManager.deleteOrder(order.getId(), order.getSellerId());
                                    count++;
                                    logger.info("[DELETE_MULTI_ORDER]orderNo:{},userId:{}",
                                            order.getOrderNo(), order.getUserId());
                                }
                            }
                        }
                    }
                }

                logger.info("deleteMultiOrder_count:{}条", count);
                if (orderList.size() < 200) {
                    break;
                }
                pageNo++;
            }

        } catch (Exception e) {
            logger.error("[deleteOrder]failed!cause by:{}", e);
            Result.failureData(ExceptionConstants.SYSTEM_ERROR);
        }
        return Result.successNullData();
    }

    @Override
    public Result updateAmount() {
        for (String orderNo : ListConst11.list) {
            OrderIndex orderIndex = orderIndexDao.selectOne(orderNo);
            if (orderIndex != null) {
                Order order = orderDao.selectByOrderNo(orderIndex.getOrderNo(), orderIndex.getUserId());
                if (order != null) {
                    update(order);
                }
            }
        }
        return Result.successNullData();
    }

    @Override
    public Result refundPayDetail() {
        int count = 0;
        Long lastId = null;
        RefundQuery query = new RefundQuery();
        query.setSellerId(202973L);
//        query.setUpdatedAtStart(new Date(1609430400000L));
//        query.setUpdatedAtEnd(new Date(1632412799000L));
        query.setSize(200);

        try {
            for (;;) {
                query.setLastId(lastId);
                List<Refund> refundList = refundDao.selectList(query);
                if (CollectionUtils.isEmpty(refundList)) {
                    break;
                }
                execute0(refundList);
                count += refundList.size();
                logger.info("refundPayDetail_count:{}条", count);
                if (refundList.size() < 200) {
                    break;
                }
                lastId = refundList.get(refundList.size() - 1).getId();
                logger.info("refundPayDetail_lastId:{}", lastId);
            }
        } catch (Exception e) {
            logger.error("[refundPayDetail]failed!cause by:{}", e);
            Result.failureData(ExceptionConstants.SYSTEM_ERROR);
        }
        return Result.successNullData();
    }


    @Override
    public void dinnerOrder() {
            try {
                int total = 0;
                OrderQuery query = new OrderQuery();
                for (int i = 0; i < dbSize; i++) {
                    for (int j = 0; j < tbSize; j++) {
                        Long lastId = null;
                        query.setDbIndex(i + 1);
                        query.setTbIndex(j);
                        query.setSize(500);
                        for (;;) {
                            query.setLastId(lastId);
                            List<TempOrder> orderIdList = tempOrderDao.selectList(query);
                            if (CollectionUtils.isEmpty(orderIdList)) {
                                break;
                            }
                            execute1(orderIdList, i, j);
                            total += orderIdList.size();
                            logger.info("[dinnerOrder]lastId:{}, total:{}, i:{}, j:{}",
                                    lastId, total, i, j);
                            if (orderIdList.size() < 500) {
                                break;
                            }
                            Result<String> redisData = redisManager.get("transfer_dinner_order_data_20240422");
                            if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                                return;
                            }
                            lastId = orderIdList.get(orderIdList.size() - 1).getId();
                        }
                    }
                }
            } catch (Exception e) {
                logger.error("[dinnerOrder]failed!cause by:{}", e);
            }
    }

    @Override
    public void tempTest() {
            try {
                int total = 0;
                int success = 0;
                int fail = 0;
                for (int i = 0; i < dbSize; i++) {
                    for (int j = 0; j < tbSize; j++) {
                        try {
                            commonManager.checkOrder(i, j);
                            commonManager.checkOrderItem(i, j);
                            commonManager.checkOrderDiscount(i, j);
                            commonManager.checkOrderPay(i, j);
                            success++;
                        } catch (Throwable e) {
                            logger.info("tempTest[error] failed!, i:{},j:{}, cause by:{}", i, j, e);
                            fail++;
                        }
                        total++;
                    }
                }
                logger.info("tempTest[end] total:{},success:{},fail:{}", total, success, fail);

            } catch (Exception e) {
                logger.error("[tempTest]failed!cause by:{}", e);
            }
    }

    @Override
    public void appointOrderTransfer() {
        for (String orderNo : ListConst.list) {
            OrderIndex index = orderIndexDao.selectOne(orderNo);
            if (index != null) {
                Order order = orderDao.selectByOrderNo(index.getOrderNo(), index.getUserId());
                order.setBizType(8);

                orderDao.updateBizType(order);

                orderItemDao.updateBizType(8, order.getUserId(), order.getOrderNo());

                orderPayDetailsDao.updateBizType(8, order.getUserId(), order.getOrderNo());

                refundDao.updateBizType(8, Lists.newArrayList(order.getOrderNo()));

                refundItemDao.updateBiz(8, Lists.newArrayList(order.getOrderNo()));

                refundDetailsDao.updateBiz(8, Lists.newArrayList(order.getOrderNo()));
            }
        }
    }

    @Autowired
    private OrderCommentDao commentDao;

    @Override
    public void updateStoreId() {
        int count = 0;
        for (String orderNo : ListConst9.list) {
            OrderIndex index = orderIndexDao.selectOne(orderNo);
            if (index != null) {
                Order order = orderDao.selectByOrderNo(index.getOrderNo(), index.getUserId());
                order.setStoreId(0L);
                orderDao.updateStoreId(order);
                try {
                    searchManager.indexOrder(order, null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                orderPayDetailsDao.updateStoreId(0L, index.getUserId(), index.getOrderNo());

                refundDao.updateStoreId(0L, index.getUserId(), index.getOrderNo());

                refundDetailsDao.updateStoreId(0L, index.getUserId(), index.getOrderNo());

                count++;
                logger.info("[updateStoreId]count:{}", count);
            }
        }

        for (String orderNo : ListConst10.list) {
            OrderIndex index = orderIndexDao.selectOne(orderNo);
            if (index != null) {
                Order order = orderDao.selectByOrderNo(index.getOrderNo(), index.getUserId());
                order.setStoreId(0L);
                orderDao.updateStoreId(order);
                try {
                    searchManager.indexOrder(order, null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                orderPayDetailsDao.updateStoreId(0L, index.getUserId(), index.getOrderNo());
                refundDao.updateStoreId(0L, index.getUserId(), index.getOrderNo());
                refundDetailsDao.updateStoreId(0L, index.getUserId(), index.getOrderNo());
                commentDao.updateStoreId(0L, order.getSellerId(), index.getOrderNo());
                count++;
                logger.info("[updateStoreId]count:{}", count);
            }
        }
    }

    @Override
    public void insertPay(OrderPayDetails payDetails) {
        OrderIndex orderIndex = orderIndexDao.selectOne(payDetails.getOrderNo());
        if (orderIndex == null) {
            return;
        }
        Order order = orderDao.selectByOrderNo(orderIndex.getOrderNo(), orderIndex.getUserId());
        if (order == null) {
            return;
        }
        try {
            payDetails.setId(keyGenerator.generateSnowflakeNumKey());
            payDetails.setSellerId(order.getSellerId());
            payDetails.setStoreId(order.getStoreId());
            payDetails.setUserId(order.getUserId());
            payDetails.setOrderType(order.getOrderType());
            payDetails.setPerformanceType(order.getPerformanceType());
            payDetails.setBizType(order.getBizType());
            payDetails.setSource(order.getSource());
            payDetails.setStatus(0);
            payDetails.setPayAt(payDetails.getPayAt() != null ? payDetails.getPayAt() : order.getPayAt());
            payDetails.setOrderAt(order.getOrderAt());
            payDetails.setCreatedAt(new Date());
            payDetails.setUpdatedAt(new Date());
            payDetails.setIsDeleted(0);
            payDetails.setPayAt(order.getOrderAt());
            payDetails.setPayNo(org.springframework.util.StringUtils.isEmpty(
                    payDetails.getPayNo()) ? "" : payDetails.getPayNo());
            payDetails.setThirdPayNo(org.springframework.util.StringUtils.isEmpty(
                    payDetails.getThirdPayNo()) ? "" : payDetails.getThirdPayNo());

            orderPayDetailsDao.inserts(Lists.newArrayList(payDetails));

            if (!Objects.equals("PF", order.getPayDetailInfo())) {
                List<OrderPayDetails> payDetailsList = orderPayDetailsDao.selectByOrderNo(payDetails.getOrderNo(), payDetails.getUserId());
                order.setPayDetailInfo(JSON.toJSONString(ConvertUtils.convertList(payDetailsList, InnerOrderPayDetails.class)));
                orderDao.updatePayDetail(order);
            }
        } catch (Exception e) {
            logger.error("insertPay cause by:{}", e);
        }
    }

    @Override
    public void appointInsertPay() {
        for (String each : ListConst10.list) {
            String[] split = each.split("-");
            Map<String, Object> map = new HashMap<>();
            Map<String, Object> map1 = new HashMap<>();
            map1.put("bizId", split[0]);
            map1.put("rechargeAmount", Double.valueOf(split[2]));
            map1.put("giftAmount", Double.valueOf(split[3]));
            map.put("extraMap", JSON.toJSONString(map1));

            OrderPayDetails p = new OrderPayDetails();
            p.setOrderNo(split[0]);
            p.setPayType(4);
            Double d = (Double.valueOf(split[2]) + Double.valueOf(split[3])) * 100;
            p.setAmount(d.intValue());
            p.setExtraMap(map);
            insertPay(p);
        }
    }

    @Autowired
    private TempOrderCommentDao tempOrderCommentDao;

    @Override
    public void repairComment() {
        try {
            int count = 0;
            Long lastId = null;
            for (;;) {
                List<OrderComment> comments = tempOrderCommentDao.scan(lastId);
                if (CollectionUtils.isEmpty(comments)) {
                    return;
                }
                execute000(comments);
                if (comments.size() < 200) {
                    return;
                }
                count += comments.size();
                lastId = comments.get(comments.size() - 1).getId();
                logger.info("[repairCommentCount] count:{}, lastId:{}", count, lastId);

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

    private void execute000(List<OrderComment> comments) {
        while (workQueue.remainingCapacity() < 20) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executorService.submit(() -> {
            try {
                commentDao.replaceList(comments);
            } catch (Exception e) {
                logger.error("[execute000]failed！cause by:{}", e);
            }
        });
    }

    @Autowired
    private NewHintManager newHintManager;


    @Autowired
    private NewDataSourceOrderRefundDetailsDao newRefundDetailDao;
    
    @Autowired
    private NewDataSourceOrderDao newOrderDao;

    @Autowired
    private NewDataSourceOrderItemDao newDataSourceOrderItemDao;

    @Autowired
    private NewDataSourceOrderPayDetailsDao newDataSourceOrderPayDetailsDao;

    private void execute1(List<TempOrder> list, int i, int j) {
        while (workQueue.remainingCapacity() < 10) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        executorService.submit(() -> {
            try {
                if (!CollectionUtils.isEmpty(list)) {
                    List<Long> orderIdList = list.stream().map(TempOrder::getId).collect(Collectors.toList());
                    commonManager.updateBizType(orderIdList, i, j);

                    List<String> orderNoList = list.stream().map(TempOrder::getOrderNo).collect(Collectors.toList());
                    commonManager.updateBizTypeForItem(orderNoList, i, j);

                    commonManager.updateBizTypeForDiscount(orderNoList, i, j);

                    commonManager.updatePayBizType(8, orderNoList, i, j);

                    refundDao.updateBizType(8, orderNoList);

                    refundItemDao.updateBiz(8, orderNoList);

                    refundDetailsDao.updateBiz(8, orderNoList);

                    List<Order> orderList = commonManager.listOrderById(orderIdList, i, j);
                    searchManager.indexOrder(orderList);
                }
            } catch (Exception e) {
                logger.error("[execute1]failed！cause by:{}", e);
            }
        });
    }

    private List<String> filterDiscount(List<Order> list) {
        List<String> existDiscount = new ArrayList<>();
        for (Order order : list) {
            if (StringUtils.isNotEmpty(order.getDiscountInfo())) {
                existDiscount.add(order.getOrderNo());
            }
        }
        return existDiscount;
    }

    private void execute0(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 {
                rebuild(refundList);
            } catch (Exception e) {
                logger.error("[executeSync]failed！cause by:{}", e);
            }
        });
    }

    private void rebuild(List<Refund> refundList) {
        for (Refund refund : refundList) {
            List<OrderRefundDetails> detailsList = refundDetailsDao.selectByRefundNo(refund.getRefundNo());
            if (!CollectionUtils.isEmpty(detailsList)) {
                continue;
            }
            Map<String, Object> extraMap = refund.getExtraMap();
            // 1.0迁移2.0
            List<OrderRefundDetails> payDetails;
            if (!CollectionUtils.isEmpty(extraMap) && extraMap.containsKey("isHistoryRefund")) {
                payDetails = rebuild0(refund);
            } else {
                payDetails = rebuild1(refund);
            }
            if (!CollectionUtils.isEmpty(payDetails)) {
                refund.setRefundDetailInfo(JSON.toJSONString(ConvertUtils.convertList(payDetails, InnerOrderRefundDetail.class)));
                refundDetailsDao.insertList(payDetails);
                refundDao.updateDetailInfo(refund);
            }
        }
    }

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

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

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

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

    /**
     * 1.0的数据结构
     * @param refund
     * @return
     * Date: 2021/9/27 4:38 下午
     */
    private List<OrderRefundDetails> rebuild0(Refund refund) {
        List<OrderRefundDetails> payDetailList = new ArrayList<>();
        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);
        }
        return payDetailList;
    }

    /**
     * 2.0的数据结构
     * @param refund
     * @return
     * Date: 2021/9/27 4:38 下午
     */
    private List<OrderRefundDetails> rebuild1(Refund refund) {
        List<OrderRefundDetails> payDetailList = new ArrayList<>();
        Order order = orderDao.selectByOrderNo(refund.getOrderNo(), refund.getUserId());
        if (order == null) {
            return payDetailList;
        }
        // 聚合接单
        if (Objects.equals(1, order.getFromSystem())) {
            OrderRefundDetails refundDetails = rebuildParam(7, refund, refund.getRefundAmount());
            payDetailList.add(refundDetails);
            return payDetailList;
        }
        // pos
        if (Objects.equals(8, order.getSource())) {
            OrderRefundDetails refundDetails = rebuildParam(14, refund, refund.getRefundAmount());
            payDetailList.add(refundDetails);
            return payDetailList;
        }
        // 三方支付
        if (refund.getAmount() > 0) {
            int payType = 0;
            List<OrderPayDetails> payDetailsList = payDetailsDao.selectByOrderNo(refund.getOrderNo(), refund.getUserId());
            if (!CollectionUtils.isEmpty(payDetailsList)) {
                for (OrderPayDetails payDetails : payDetailsList) {
                    if (!Objects.equals(payDetails.getPayType(), 4)) {
                        payType = payDetails.getPayType();
                        break;
                    }
                }
            }
            OrderRefundDetails refundDetails = rebuildParam(payType, refund, refund.getAmount());
            payDetailList.add(refundDetails);
        }
        // 余额支付
        if (refund.getWalletAmount() > 0) {
            OrderRefundDetails refundDetails = rebuildParam(4, refund, refund.getWalletAmount());
            payDetailList.add(refundDetails);
        }
        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 update(Order order) {
        if (Objects.nonNull(order.getChangeAmount())) {
            if (order.getChangeAmount() > 0) {
                List<OrderPayDetails> payDetailsList = payDetailsDao.selectByOrderNo(order.getOrderNo(), order.getUserId());
                if (!CollectionUtils.isEmpty(payDetailsList)) {
                    for (OrderPayDetails payDetails : payDetailsList) {
                        if (Objects.equals(payDetails.getPayType(), 12)) {
                            payDetails.setAmount(payDetails.getAmount() - order.getChangeAmount());
                            payDetailsDao.update(payDetails);
                        }
                    }
                    order.setPayDetailInfo(JSON.toJSONString(ConvertUtils.convertList(payDetailsList, InnerOrderPayDetails.class)));
                    orderDao.updatePayDetail(order);
                }
            }
        }
    }
//    @Override
//    public Result orderDiscountIdCheck() {
//        int count = 0;
//        int idCount = 0;
//        int tbLoseCount = 0;
//        int size = 300;//每次查询处理数量
//        try {
////            Date start = DateUtils.parse("2021-08-01 00:00:00", "yyyy-MM-dd hh:mm:ss");
//            OrderDiscountQuery orderDiscountQuery = new OrderDiscountQuery();
//            orderDiscountQuery.setSellerId(39339L);
//            orderDiscountQuery.setBizType(5);
//            orderDiscountQuery.setSize(size);
////            orderDiscountQuery.setOrderAtStart(start);
//            for (int i = 0; i < dbSize; i++) {
//                for (int j = 0; j < tbSize; j++) {
//                    Long lastId = 583161006365196036L;
//                    for (; ; ) {
//                        orderDiscountQuery.setLastId(lastId);
//                        long startAt = System.currentTimeMillis();
//                        List<OrderDiscount> orderDiscountList = commonManager.listOrderDiscount(orderDiscountQuery, i, j);
//                        logger.info("orderDiscountIdCheck-scanOrderTime:{}ms", System.currentTimeMillis() - startAt);
//                        if (CollectionUtils.isEmpty(orderDiscountList)) {
//                            break;
//                        }
//                        List<Long> idList = orderDiscountList.stream().map(OrderDiscount->OrderDiscount.getId()).collect(Collectors.toList());
//                        List<OrderDiscount> tbOrderDiscountList = tbOrderDiscountDao.selectByIdList(idList);
//                        Map<Long, List<OrderDiscount>> map = tbOrderDiscountList.stream().collect(Collectors.groupingBy(OrderDiscount::getId));
//
//                        for (OrderDiscount orderDiscount : orderDiscountList) {
//                            OrderDiscount tbOrderDiscount = map.get(orderDiscount.getId());
//                            if (Objects.nonNull(tbOrderDiscount)) {
//                                //业务库和tidb 相同的主键订单号不同
//                                if (!Objects.equals(tbOrderDiscount.getOrderNo(), orderDiscount.getOrderNo())) {
//                                    //更新业务库主键
//                                    Long newId = shardingKeyGenerator.generateSnowflakeNumKey();
//                                    orderDiscountDao.updateId(orderDiscount.getId(), orderDiscount.getUserId(), newId);
//                                    idCount++;
//                                    logger.info("orderDiscountIdCheck: i:{}, j:{}, 冲突主键:{}, tidb_orderNo：{}, orderpro_0{}.orders_{}:OrderNo：{}", i, j, orderDiscount.getId(), tbOrderDiscount.getOrderNo(), i + 1, j, orderDiscount.getOrderNo());
//                                }
//                            } else {
//                                //tidb无数据 更新时间
//                                orderDiscountDao.updateUpdatedAt(orderDiscount.getId(), orderDiscount.getUserId());
//                                tbLoseCount++;
//                            }
//                        }
//                        lastId = orderDiscountList.get(orderDiscountList.size() - 1).getId();
//                        count += orderDiscountList.size();
//                        logger.info("orderDiscountIdCheck: i:{}, j:{}, lastId:{}, 累计扫描数量：{}, id更新数量：{}, tidb缺失数量：{}", i, j, lastId, count, idCount, tbLoseCount);
//                        if (orderDiscountList.size() < size) {
//                            break;
//                        }
//                    }
//                }
//            }
//            logger.info("orderDiscountIdCheck:end");
//        } catch (Exception e) {
//            logger.error("[orderDiscountIdCheck]failed!cause by:{}", e);
//            return Result.failureData(ExceptionConstants.SYSTEM_ERROR);
//        }
//        return Result.successNullData();
//    }

    @Override
    public Result orderDiscountIdCheck() {
        try {
            for (int i = 0; i < dbSize; i++) {
                for (int j = 0; j < tbSize; j++) {
                    executeCheckOrderDiscounts(i, j);
                }
            }
            logger.info("orderDiscountIdCheck:end");
        } catch (Exception e) {
            logger.error("[orderDiscountIdCheck]failed!cause by:{}", e);
            return Result.failureData(ExceptionConstants.SYSTEM_ERROR);
        }
        return Result.successNullData();
    }

    private void executeCheckOrderDiscounts(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 {
                logger.info("orderDiscountIdCheckStart: i:{}, j:{}", i, j);

                Long sellerId = 39339L;
                Integer bizType = 5;
                int size = 200;//每次查询处理数量
                Long lastId = 583161006365196036L;
                int count = 0;
                int idCount = 0;
                OrderDiscountQuery orderDiscountQuery = new OrderDiscountQuery();
                for (; ; ) {
                    orderDiscountQuery.setLastId(lastId);
                    List<OrderDiscount> orderDiscountList = commonManager.listOrderDiscountById(orderDiscountQuery, i, j);
                    if (CollectionUtils.isEmpty(orderDiscountList)) {
                        break;
                    }
                    Map<Long, OrderDiscount> orderDiscountMap = new HashMap<>(size);
                    List<Long> idList = new ArrayList<>();
                    for (OrderDiscount orderDiscount : orderDiscountList) {
                        //业务库符合对比条件的数据暂存
                        if (Objects.equals(sellerId, orderDiscount.getSellerId()) && Objects.equals(bizType, orderDiscount.getBizType())) {
                            orderDiscountMap.put(orderDiscount.getId(), orderDiscount);
                            idList.add(orderDiscount.getId());

                            //暂存数据到达阈值 开始对比处理
                            if (Objects.equals(size, idList.size())) {
                                List<OrderDiscount> tbOrderDiscountList = tbOrderDiscountDao.selectByIdList(idList);
                                for (OrderDiscount tbOrderDiscount : tbOrderDiscountList) {
                                    OrderDiscount catringOrderDiscount = orderDiscountMap.get(tbOrderDiscount.getId());
                                    if (Objects.nonNull(catringOrderDiscount)) {
                                        //业务库和tidb 相同的主键订单号不同
                                        if (!Objects.equals(tbOrderDiscount.getOrderNo(), catringOrderDiscount.getOrderNo())) {
                                            //更新业务库主键
                                            Long newId = shardingKeyGenerator.generateSnowflakeNumKey();
//                                            orderDiscountDao.updateId(catringOrderDiscount.getId(), catringOrderDiscount.getUserId(), newId);
                                            idCount++;
                                            logger.info("orderDiscountIdCheckMidd: i:{}, j:{}, errorId:{}, tidb_orderNo：{}, orderpro_0{}.orders_{}:OrderNo：{}", i, j, catringOrderDiscount.getId(), tbOrderDiscount.getOrderNo(), i + 1, j, catringOrderDiscount.getOrderNo());
                                        }
                                    }
                                }
                                // 清空暂存数据
                                orderDiscountMap = new HashMap<>(size);
                                idList = new ArrayList<>(size);
                            }
                        }
                    }

                    //剩余数据
                    if (idList.size() > 0) {
                        List<OrderDiscount> tbOrderDiscountList = tbOrderDiscountDao.selectByIdList(idList);
                        for (OrderDiscount tbOrderDiscount : tbOrderDiscountList) {
                            OrderDiscount catringOrderDiscount = orderDiscountMap.get(tbOrderDiscount.getId());
                            if (Objects.nonNull(catringOrderDiscount)) {
                                //业务库和tidb 相同的主键订单号不同
                                if (!Objects.equals(tbOrderDiscount.getOrderNo(), catringOrderDiscount.getOrderNo())) {
                                    //更新业务库主键
                                    Long newId = shardingKeyGenerator.generateSnowflakeNumKey();
//                                    orderDiscountDao.updateId(catringOrderDiscount.getId(), catringOrderDiscount.getUserId(), newId);
                                    idCount++;
                                    logger.info("orderDiscountIdCheckLast: i:{}, j:{}, 冲突主键:{}, tidb_orderNo：{}, orderpro_0{}.orders_{}:OrderNo：{}", i, j, catringOrderDiscount.getId(), tbOrderDiscount.getOrderNo(), i + 1, j, catringOrderDiscount.getOrderNo());
                                }
                            }
                        }
                        // 清空暂存数据
                        orderDiscountMap = new HashMap<>(size);
                        idList = new ArrayList<>(size);
                    }

                    lastId = orderDiscountList.get(orderDiscountList.size() - 1).getId();
                    count += orderDiscountList.size();
                    logger.info("orderDiscountIdCheck: i:{}, j:{}, lastId:{}, 累计扫描数量：{}, id更新数量：{}", i, j, lastId, count, idCount);
                    if (orderDiscountList.size() < size) {
                        break;
                    }
                }
                logger.info("orderDiscountIdCheckEnd: i:{}, j:{},idCount:{}, 累计扫描数量：{}", i, j, idCount, count);

            } catch (Exception e) {
                logger.error("[executeSync]failed！cause by:{}", e);
            }
        });
    }


    @Override
    public Result currentOrderSyncEs() {
        int count = 0;
        int pageNo = 1;
        try {
            SearchOrderQuery query = new SearchOrderQuery();
            query.setGoodsOrderSource(1);
            query.setBizType(4);
            query.setSellerIdList(Lists.newArrayList(204102L, -1L));
            query.setOrderAtStart(DateUtils.getStartDate(new Date()));
            query.setOrderAtEnd(DateUtils.getEndDate(new Date()));
            query.setPageSize(200);
            for (; ; ) {
                query.setPageNo(pageNo);
                SearchOrderDTO searchOrder = searchManager.searchOrder(query, query.getBizType());
                if (searchOrder == null) {
                    break;
                }
                List<BaseIndexOrder> orderList = searchOrder.getOrderList();
                if (CollectionUtils.isEmpty(orderList)) {
                    break;
                }
                OrderQuery orderQuery = new OrderQuery();
                for (BaseIndexOrder baseIndexOrder : orderList) {
                    Order order = orderDao.selectById(baseIndexOrder.getOrderId(), baseIndexOrder.getUserId());
                    searchManager.indexOrder(order, null);

                    if (!Objects.equals(order.getReceiveStatus(), baseIndexOrder.getReceiveStatus())) {
                        logger.info("currentOrderSyncEsDiff:[ReceiveStatus]:orderNo:{}:mysql:{}:ES:{}", order.getOrderNo(), order.getReceiveStatus(), baseIndexOrder.getReceiveStatus());
                    }
                    if (!Objects.equals(order.getStatus(), baseIndexOrder.getStatus())) {
                        logger.info("currentOrderSyncEsDiff:[status]:orderNo:{}:mysql:{}:ES:{}", order.getOrderNo(), order.getStatus(), baseIndexOrder.getStatus());
                    }
                    if (!Objects.equals(order.getPayStatus(), baseIndexOrder.getPayStatus())) {
                        logger.info("currentOrderSyncEsDiff:[payStatus]:orderNo:{}:mysql:{}:ES:{}", order.getOrderNo(), order.getPayStatus(), baseIndexOrder.getPayStatus());
                    }
                    if (!Objects.equals(order.getPerformanceStatus(), baseIndexOrder.getPerformanceStatus())) {
                        logger.info("currentOrderSyncEsDiff:[PerformanceStatus]:orderNo:{}:mysql:{}:ES:{}", order.getOrderNo(), order.getPerformanceStatus(), baseIndexOrder.getPerformanceStatus());
                    }
                }
                count = count + orderList.size();
                if (orderList.size() < 200) {
                    break;
                }
                pageNo++;
            }
            logger.info("currentOrderSyncEsCount:{}条", count);
        } catch (Exception e) {
            logger.error("[currentOrderSyncEs]failed!cause by:{}", e);
            Result.failureData(ExceptionConstants.SYSTEM_ERROR);
        }
        return Result.successNullData();
    }

    @Autowired
    private DesignOrderDao designOrderDao;

    @Override
    public void mtSourceOrder() {
        try {
            int count = 0;
            Long lastId = null;
            while (true) {
                List<Order> orderList = designOrderDao.selectListById(lastId);
                if (CollectionUtils.isEmpty(orderList)) {
                    return;
                }
                Order order = orderList.get(orderList.size() - 1);
                if (order.getOrderAt().getTime() < 1699830000000L) {
                    executeMtSourceOrder(orderList);
                }

                count += orderList.size();
                logger.info("[mt_source_order]lastId:{}, count:{}", lastId, count);
                if (orderList.size() < 200) {
                    return;
                }
                Result<String> redisData = redisManager.get("mt_source_order_key");
                if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                    return;
                }
                lastId = orderList.get(orderList.size() - 1).getId();
            }
        } catch (Exception e) {
            logger.error("[mtSourceOrder]cause by:{}", e);
        }
    }

    private void executeMtSourceOrder(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> updateList = new ArrayList<>(orderList.size());
                for (Order order : orderList) {
                    if (StringUtils.isNotEmpty(order.getPayInfo()) && order.getPayInfo().contains("order_processed")) {
                        continue;
                    }
                    Order update = new Order();
                    update.setId(order.getId());
                    update.setPayInfo(order.getPayInfo());
                    update.setPerformanceInfo(order.getPerformanceInfo());
                    update.setBuyerRemarks(order.getBuyerRemarks());
                    update.setAddrInfo(order.getAddrInfo());
                    
                    // 重新构建
                    String payInfo1 = update.getPayInfo();
                    Map<String, Object> payInfo = null;
                    if (!org.springframework.util.StringUtils.isEmpty(payInfo1)) {
                        payInfo = JSON.parseObject(update.getPayInfo());
                    } else {
                        payInfo = new HashMap<>(2);
                    }
                    payInfo.put("order_processed", 1);
                    update.setPayInfo(JSON.toJSONString(payInfo));

                    if (!org.springframework.util.StringUtils.isEmpty(update.getPerformanceInfo())) {
                        String info = DataDesensiHandler.handlePerformanceInfo(update.getPerformanceInfo());
                        update.setPerformanceInfo(info);
                    }
                    if (!org.springframework.util.StringUtils.isEmpty(update.getBuyerRemarks())) {
                        String info = DataDesensiHandler.handleBuyerRemarks(update.getBuyerRemarks());
                        update.setBuyerRemarks(info);
                    }
                    if (!org.springframework.util.StringUtils.isEmpty(update.getAddrInfo())) {
                        String info = DataDesensiHandler.handleAddrInfo(update.getAddrInfo());
                        update.setAddrInfo(info);
                    }
                    updateList.add(update);
                }
                if (!CollectionUtils.isEmpty(updateList)) {
                    designOrderDao.updateBatchOrderInfo(updateList);
                }
            } catch (Exception e) {
                logger.error("[executeSync]failed！cause by:{}", e);
            }
        });
    }

    @Autowired
    private OrderIndexDao indexDao;
    

    @Override
    public void mtOrderRepair() {
        int count = 0;
        for (String orderNo : ListConst.list) {
            OrderIndex orderIndex = indexDao.selectOne(orderNo);
            if (orderIndex != null) {
                Order order = orderDao.selectByOrderNo(orderNo, orderIndex.getUserId());
                if (order != null) {
                    Order one = designOrderDao.selectOne(order.getId());
                    if (one == null) {
                        designOrderDao.insert(order);
                        count++;
                        logger.info("mtOrderRepair count:{}", count);
                    }
                }
            }
        }
    }

    String[] INCLUDES = {"orderId", "orderNo", "userId", "sellerId", "payType"};

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

    static {
        payTypes.add(10002);
        payTypes.add(11257);
        payTypes.add(11244);
        payTypes.add(11247);
        payTypes.add(10466);
        payTypes.add(11087);
        payTypes.add(10578);
        payTypes.add(11198);
        payTypes.add(10708);
        payTypes.add(10833);
        payTypes.add(11248);
        payTypes.add(10944);
        payTypes.add(11116);
        payTypes.add(10757);
        payTypes.add(11092);
        payTypes.add(11182);
        payTypes.add(10914);
        payTypes.add(11099);
        payTypes.add(10539);
        payTypes.add(10814);
        payTypes.add(10352);
        payTypes.add(11164);
        payTypes.add(10719);
        payTypes.add(11263);
        payTypes.add(10161);
        payTypes.add(11063);
        payTypes.add(11069);
        payTypes.add(11002);
        payTypes.add(11187);
        payTypes.add(10514);
        payTypes.add(10731);
        payTypes.add(11060);
        payTypes.add(10524);
        payTypes.add(10732);
        payTypes.add(10159);
        payTypes.add(10355);
        payTypes.add(10435);
        payTypes.add(11219);
        payTypes.add(11174);
        payTypes.add(11190);
        payTypes.add(10338);
        payTypes.add(10554);
        payTypes.add(10792);
        payTypes.add(10894);
        payTypes.add(11188);
        payTypes.add(11239);
        payTypes.add(10816);
        payTypes.add(11018);
        payTypes.add(10697);
        payTypes.add(11127);
        payTypes.add(11159);
        payTypes.add(11183);
        payTypes.add(10868);
        payTypes.add(10552);
        payTypes.add(10761);
        payTypes.add(10921);
        payTypes.add(10964);
        payTypes.add(10642);
        payTypes.add(10892);
        payTypes.add(11049);
        payTypes.add(11217);
        payTypes.add(11029);
        payTypes.add(11245);
        payTypes.add(10548);
        payTypes.add(10550);
        payTypes.add(10714);
        payTypes.add(11050);
        payTypes.add(11221);
        payTypes.add(10926);
        payTypes.add(10958);
        payTypes.add(11089);
        payTypes.add(11209);
        payTypes.add(11039);
        payTypes.add(11051);
        payTypes.add(10992);
        payTypes.add(10826);
        payTypes.add(10966);
        payTypes.add(11054);
        payTypes.add(11094);
        payTypes.add(10111);
        payTypes.add(10767);
        payTypes.add(10951);
        payTypes.add(10681);
        payTypes.add(10852);
        payTypes.add(10869);
        payTypes.add(11210);
        payTypes.add(10383);
        payTypes.add(10518);
        payTypes.add(10903);
        payTypes.add(11225);
        payTypes.add(10902);
        payTypes.add(11215);
        payTypes.add(10862);
        payTypes.add(10436);
        payTypes.add(10571);
        payTypes.add(10730);
        payTypes.add(11213);
        payTypes.add(10533);
        payTypes.add(10725);
        payTypes.add(10805);
        payTypes.add(10729);
        payTypes.add(10853);
        payTypes.add(10857);
        payTypes.add(11034);
        payTypes.add(11140);
        payTypes.add(11154);
        payTypes.add(10860);
        payTypes.add(11157);
        payTypes.add(10513);
        payTypes.add(10551);
        payTypes.add(10653);
        payTypes.add(10682);
        payTypes.add(10955);
        payTypes.add(11223);
        payTypes.add(11234);
        payTypes.add(10320);
        payTypes.add(11131);
        payTypes.add(10517);
        payTypes.add(10683);
        payTypes.add(10831);
        payTypes.add(10987);
        payTypes.add(11153);
        payTypes.add(11238);
        payTypes.add(10773);
        payTypes.add(10815);
        payTypes.add(10834);
        payTypes.add(11235);
        payTypes.add(10783);
        payTypes.add(10976);
        payTypes.add(10991);
        payTypes.add(11107);
        payTypes.add(11168);
        payTypes.add(10134);
        payTypes.add(10486);
        payTypes.add(10741);
        payTypes.add(10916);
        payTypes.add(11134);
        payTypes.add(11208);
        payTypes.add(10121);
        payTypes.add(10475);
        payTypes.add(10654);
        payTypes.add(10749);
        payTypes.add(10835);
        payTypes.add(10838);
        payTypes.add(10910);
        payTypes.add(10950);
        payTypes.add(11032);
        payTypes.add(11090);
        payTypes.add(11155);
        payTypes.add(11224);
        payTypes.add(10141);
        payTypes.add(10205);
        payTypes.add(10340);
        payTypes.add(10525);
        payTypes.add(10652);
        payTypes.add(10667);
        payTypes.add(10739);
        payTypes.add(10810);
        payTypes.add(10909);
        payTypes.add(10967);
        payTypes.add(11007);
        payTypes.add(11173);
        payTypes.add(11201);
        payTypes.add(11236);
        payTypes.add(11237);
        payTypes.add(10003);
        payTypes.add(10012);
        payTypes.add(10423);
        payTypes.add(10832);
        payTypes.add(10891);
        payTypes.add(10940);
        payTypes.add(10949);
        payTypes.add(11111);
        payTypes.add(11123);
        payTypes.add(11193);
        payTypes.add(11199);
        payTypes.add(11229);
        payTypes.add(10222);
        payTypes.add(10376);
        payTypes.add(10421);
        payTypes.add(10688);
        payTypes.add(11151);
        payTypes.add(11195);
        payTypes.add(11241);
        payTypes.add(11273);
        payTypes.add(11275);
        payTypes.add(10495);
        payTypes.add(10538);
        payTypes.add(10570);
        payTypes.add(10639);
        payTypes.add(10696);
        payTypes.add(10812);
        payTypes.add(11103);
        payTypes.add(11137);
        payTypes.add(11179);
        payTypes.add(11240);
        payTypes.add(10109);
        payTypes.add(10117);
        payTypes.add(10179);
        payTypes.add(10326);
        payTypes.add(10706);
        payTypes.add(10887);
        payTypes.add(10899);
        payTypes.add(10905);
        payTypes.add(11009);
        payTypes.add(11122);
        payTypes.add(11200);
        payTypes.add(11212);
        payTypes.add(10182);
        payTypes.add(10532);
        payTypes.add(10915);
        payTypes.add(11073);
        payTypes.add(11133);
        payTypes.add(11194);
        payTypes.add(11284);
        payTypes.add(10411);
        payTypes.add(10418);
        payTypes.add(10636);
        payTypes.add(10858);
        payTypes.add(10989);
        payTypes.add(11016);
        payTypes.add(11096);
        payTypes.add(11120);
        payTypes.add(11261);
        payTypes.add(11264);
        payTypes.add(10013);
        payTypes.add(10018);
        payTypes.add(10031);
        payTypes.add(10072);
        payTypes.add(10433);
        payTypes.add(10482);
        payTypes.add(10496);
        payTypes.add(10580);
        payTypes.add(10587);
        payTypes.add(10629);
        payTypes.add(10685);
        payTypes.add(10763);
        payTypes.add(10895);
        payTypes.add(10975);
        payTypes.add(11006);
        payTypes.add(11012);
        payTypes.add(11024);
        payTypes.add(11085);
        payTypes.add(11098);
        payTypes.add(11197);
        payTypes.add(11207);
        payTypes.add(11282);
        payTypes.add(10239);
        payTypes.add(10278);
        payTypes.add(10334);
        payTypes.add(10417);
        payTypes.add(10430);
        payTypes.add(10521);
        payTypes.add(10542);
        payTypes.add(10617);
        payTypes.add(10666);
        payTypes.add(10707);
        payTypes.add(10743);
        payTypes.add(10765);
        payTypes.add(10770);
        payTypes.add(10785);
        payTypes.add(10836);
        payTypes.add(10845);
        payTypes.add(10854);
        payTypes.add(10913);
        payTypes.add(10990);
        payTypes.add(10995);
        payTypes.add(11028);
        payTypes.add(11125);
        payTypes.add(11162);
        payTypes.add(11172);
        payTypes.add(11262);
        payTypes.add(11265);
        payTypes.add(10022);
        payTypes.add(10079);
        payTypes.add(10218);
        payTypes.add(10234);
        payTypes.add(10311);
        payTypes.add(10386);
        payTypes.add(10403);
        payTypes.add(10434);
        payTypes.add(10437);
        payTypes.add(10574);
        payTypes.add(10686);
        payTypes.add(10691);
        payTypes.add(10694);
        payTypes.add(10742);
        payTypes.add(10758);
        payTypes.add(10768);
        payTypes.add(10782);
        payTypes.add(10811);
        payTypes.add(10813);
        payTypes.add(10822);
        payTypes.add(10824);
        payTypes.add(10847);
        payTypes.add(10939);
        payTypes.add(11052);
        payTypes.add(11077);
        payTypes.add(11105);
        payTypes.add(11138);
        payTypes.add(11148);
        payTypes.add(11160);
        payTypes.add(11166);
        payTypes.add(11176);
        payTypes.add(11220);
        payTypes.add(11228);
        payTypes.add(11242);
        payTypes.add(11243);
        payTypes.add(11280);
        payTypes.add(10011);
        payTypes.add(10015);
        payTypes.add(10017);
        payTypes.add(10033);
        payTypes.add(10110);
        payTypes.add(10114);
        payTypes.add(10146);
        payTypes.add(10177);
        payTypes.add(10196);
        payTypes.add(10229);
        payTypes.add(10263);
        payTypes.add(10286);
        payTypes.add(10371);
        payTypes.add(10479);
        payTypes.add(10546);
        payTypes.add(10553);
        payTypes.add(10576);
        payTypes.add(10585);
        payTypes.add(10586);
        payTypes.add(10596);
        payTypes.add(10604);
        payTypes.add(10615);
        payTypes.add(10648);
        payTypes.add(10658);
        payTypes.add(10659);
        payTypes.add(10689);
        payTypes.add(10692);
        payTypes.add(10695);
        payTypes.add(10711);
        payTypes.add(10753);
        payTypes.add(10754);
        payTypes.add(10756);
        payTypes.add(10772);
        payTypes.add(10803);
        payTypes.add(10849);
        payTypes.add(10863);
        payTypes.add(10865);
        payTypes.add(10893);
        payTypes.add(10920);
        payTypes.add(10941);
        payTypes.add(10947);
        payTypes.add(10959);
        payTypes.add(10960);
        payTypes.add(10988);
        payTypes.add(11003);
        payTypes.add(11005);
        payTypes.add(11033);
        payTypes.add(11064);
        payTypes.add(11165);
        payTypes.add(11167);
        payTypes.add(11177);
        payTypes.add(11180);
        payTypes.add(11191);
        payTypes.add(11202);
        payTypes.add(11203);
        payTypes.add(11204);
        payTypes.add(11205);
        payTypes.add(11206);
        payTypes.add(11216);
        payTypes.add(11218);
        payTypes.add(11231);
        payTypes.add(11233);
        payTypes.add(11255);
        payTypes.add(11266);
        payTypes.add(11267);
        payTypes.add(11269);
        payTypes.add(11271);
    }

    @Override
    public void pullData() {
        try {
            int count = 0;
            for (Long sellerId : list) {
                SearchOrderQuery query = new SearchOrderQuery();
                query.setSize(1000);
                query.setBizType(4);
                query.setPayTypeList(payTypes);
                query.setRespCount(false);
                query.setSource(19);
                query.setOrderAtStart(new Date(1729526400000L));
                query.setOrderAtEnd(new Date());
                query.setSearchAfter(true);
//                query.setSellerId(sellerId);
                query.setIndexRouteSeller(CommonConstants.INDEX_ROUTES);

                // 商城订单查询逻辑
//                query.setOrderTypeList(Lists.newArrayList(20));
//                query.setBizType(5);
                // 商城订单查询逻辑

                Long lastId = 0L;
                for (;;) {
                    query.setLastId(lastId);
                    SearchOrderDTO searchOrderDTO = searchManager.searchOrder(query, INCLUDES, null);
                    List<BaseIndexOrder> orderList = searchOrderDTO.getOrderList();
                    if (CollectionUtils.isEmpty(orderList)) {
                        break;
                    }
                    executePull(orderList);

                    count += orderList.size();
                    logger.info("pullData, count:{}", count);
                    if (orderList.size() < 1000) {
                        break;
                    }
                    Result<String> redisData = redisManager.get("pullData_004");
                    if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                        return;
                    }
                    lastId = orderList.get(orderList.size() - 1).getOrderId();
                }
            }
            logger.info("pullData end, count:{}", count);
        } catch (Exception e) {
            logger.error("[pullData]cause by:{}", e);
        }
    }


    static List<Long> listCatering = Lists.newArrayList();

    static {
        listCatering.add(203543L);
        listCatering.add(209271L);
        listCatering.add(215720L);
        listCatering.add(216111L);
        listCatering.add(217930L);
        listCatering.add(218734L);
    }

    @Override
    public void pullDataCatering() {
        try {
            int count = 0;
            for (Long sellerId : listCatering) {
                SearchOrderQuery query = new SearchOrderQuery();
                query.setSize(1000);
                query.setRespCount(false);
                query.setSearchAfter(true);
                query.setSellerId(sellerId);
                // 商城订单查询逻辑
                query.setOrderTypeList(Lists.newArrayList(20));
//                query.setBizType(5);

                Long lastId = 0L;
                for (;;) {
                    query.setLastId(lastId);
                    SearchOrderDTO searchOrderDTO = searchManager.searchOrder(query, INCLUDES, null);
                    List<BaseIndexOrder> orderList = searchOrderDTO.getOrderList();
                    if (CollectionUtils.isEmpty(orderList)) {
                        break;
                    }
                    executePullCatering(orderList);

                    count += orderList.size();
                    logger.info("pullData, count:{}", count);
                    if (orderList.size() < 1000) {
                        break;
                    }
                    Result<String> redisData = redisManager.get("pullData_004");
                    if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                        return;
                    }
                    lastId = orderList.get(orderList.size() - 1).getOrderId();
                }
            }
            logger.info("pullData end, count:{}", count);
        } catch (Exception e) {
            logger.error("[pullData]cause by:{}", e);
        }
    }


    @Override
    public void jifenOrderCatering() {
        try {
            int total = 0;
            OrderQuery query = new OrderQuery();
            for (int i = 0; i < dbSize; i++) {
                for (int j = 0; j < tbSize; j++) {
                    Long lastId = null;
                    query.setDbIndex(i + 1);
                    query.setTbIndex(j);
                    query.setSize(500);
                    for (;;) {
                        query.setLastId(lastId);
                        List<TempOrder> orderIdList = tempOrderCaterDao.selectList(query);
                        if (CollectionUtils.isEmpty(orderIdList)) {
                            break;
                        }
                        execute1(orderIdList, i, j);
                        total += orderIdList.size();
                        logger.info("[dinnerOrder]lastId:{}, total:{}, i:{}, j:{}",
                                lastId, total, i, j);
                        if (orderIdList.size() < 500) {
                            break;
                        }
                        Result<String> redisData = redisManager.get("transfer_dinner_order_data_20240422");
                        if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                            return;
                        }
                        lastId = orderIdList.get(orderIdList.size() - 1).getId();
                    }
                }
            }
        } catch (Exception e) {
            logger.error("[dinnerOrder]failed!cause by:{}", e);
        }
    }


    static List<Long> list = Lists.newArrayList();

    static {
        list.add(203683L);
    }

    static List<Long> bakingList = Lists.newArrayList();

    static {
        bakingList.add(203695L);
        bakingList.add(208714L);
        bakingList.add(216406L);
        bakingList.add(214159L);
        bakingList.add(214778L);
        bakingList.add(209538L);
        bakingList.add(204191L);
        bakingList.add(218858L);
        bakingList.add(217880L);
        bakingList.add(219022L);
        bakingList.add(214987L);
    }

    @Override
    public void pullDataBakingEs() {
        try{
            int count = 0;
            Long lastId = 0L;
            for (;;) {
                OrderQuery query = new OrderQuery();
                query.setSize(200);
                query.setLastId(lastId);
                List<TempOrder> orderIdList = tempOrderCaterDao.selectList(query);
                if (CollectionUtils.isEmpty(orderIdList)) {
                    break;
                }

                for(TempOrder tempOrderBaking : orderIdList){
                    OrderDataReviseRequest request = new OrderDataReviseRequest();
                    request.setOrderNo(tempOrderBaking.getOrderNo());
                    syncOrderData(request);
                    count++;
                }
                logger.info("[pullDataBakingEs][catering] count:{}",count);

                if (orderIdList.size() < 200) {
                    break;
                }
                lastId = orderIdList.get(orderIdList.size() - 1).getId();
            }
            logger.info("[pullDataBakingEs][catering]end count:{}",count);

             count = 0;
             lastId = 0L;
            for (;;) {
                OrderQuery query = new OrderQuery();
                query.setSize(200);
                query.setLastId(lastId);
                List<TempOrderBaking> orderIdList = tempOrderBakingDao.selectList(query);
                if (CollectionUtils.isEmpty(orderIdList)) {
                    break;
                }

                for(TempOrderBaking tempOrderBaking : orderIdList){
                    OrderDataReviseRequest request = new OrderDataReviseRequest();
                    request.setOrderNo(tempOrderBaking.getOrderNo());
                    syncOrderData(request);
                    count++;
                }
                logger.info("[pullDataBakingEs][baking] count:{}",count);
                if (orderIdList.size() < 200) {
                    break;
                }
                lastId = orderIdList.get(orderIdList.size() - 1).getId();
            }
            logger.info("[pullDataBakingEs][baking]end count:{}",count);


        }catch (Throwable throwable){
            logger.error("[pullDataBaking]cause by:{}", throwable);
        }
    }

    @Override
    public void pullDataBaking() {
        try {
            int count = 0;
            for (Long sellerId : bakingList) {
                SearchOrderQuery query = new SearchOrderQuery();
                query.setSize(1000);
                query.setRespCount(false);
                query.setSearchAfter(true);
                query.setSellerId(sellerId);

                // 烘焙商城订单查询逻辑
                query.setOrderTypeList(Lists.newArrayList(7));
                query.setBizType(4);
                query.setOrderSubType(0);

                Long lastId = 0L;
                for (;;) {
                    query.setLastId(lastId);
                    SearchOrderDTO searchOrderDTO = searchManager.searchOrder(query, INCLUDES, null);
                    List<BaseIndexOrder> orderList = searchOrderDTO.getOrderList();
                    if (CollectionUtils.isEmpty(orderList)) {
                        break;
                    }
                    executePullBaking(orderList);

                    count += orderList.size();
                    logger.info("pullDataBaking, count:{}", count);
                    if (orderList.size() < 1000) {
                        break;
                    }
                    Result<String> redisData = redisManager.get("pullDataBaking_002");
                    if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                        return;
                    }
                    lastId = orderList.get(orderList.size() - 1).getOrderId();
                }
            }
            logger.info("pullDataBaking end, count:{}", count);
        } catch (Exception e) {
            logger.error("[pullDataBaking]cause by:{}", e);
        }
    }


    static List<Long> bakingStdList = Lists.newArrayList();

    static {
        bakingStdList.add(216131L);
        bakingStdList.add(217716L);
    }

    @Override
    public void pullDataBakingStd() {
        try {
            int count = 0;
            for (Long sellerId : bakingStdList) {
                SearchOrderQuery query = new SearchOrderQuery();
                query.setSize(1000);
                query.setRespCount(false);
                query.setSearchAfter(true);
                query.setSellerId(sellerId);

                // 烘焙商城订单查询逻辑
                query.setOrderTypeList(Lists.newArrayList(10));
//                query.setBizType(4);
                query.setOrderSubType(0);

                Long lastId = 0L;
                for (;;) {
                    query.setLastId(lastId);
                    SearchOrderDTO searchOrderDTO = searchManager.searchStdOrder(query, INCLUDES, null);
                    List<BaseIndexOrder> orderList = searchOrderDTO.getOrderList();
                    if (CollectionUtils.isEmpty(orderList)) {
                        break;
                    }
                    executePullBakingStd(orderList);

                    count += orderList.size();
                    logger.info("pullDataBakingStd, count:{}", count);
                    if (orderList.size() < 1000) {
                        break;
                    }
                    Result<String> redisData = redisManager.get("pullDataBakingStd_002");
                    if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                        return;
                    }
                    lastId = orderList.get(orderList.size() - 1).getOrderId();
                }
            }
            logger.info("pullDataBakingStd end, count:{}", count);
        } catch (Exception e) {
            logger.error("[pullDataBakingStd]cause by:{}", e);
        }
    }

    @Override
    public void bakingStdDoTransfer() {
        try {
            int total = 0;
            OrderQuery query = new OrderQuery();
            for (int i = 0; i < dbSize; i++) {
                for (int j = 0; j < tbSize; j++) {
                    Long lastId = null;
                    query.setDbIndex(i + 1);
                    query.setTbIndex(j);
                    query.setSize(500);
                    for (;;) {
                        query.setLastId(lastId);
                        List<TempOrderBaking> orderIdList = tempOrderBakingStdDao.selectList(query);
                        if (CollectionUtils.isEmpty(orderIdList)) {
                            break;
                        }
                        executeBakingStd(orderIdList, i, j);
                        total += orderIdList.size();
                        logger.info("[bakingStdDoTransfer]lastId:{}, total:{}, i:{}, j:{}",
                                lastId, total, i, j);
                        if (orderIdList.size() < 500) {
                            break;
                        }
                        Result<String> redisData = redisManager.get("transfer_dinner_order_data_20240422");
                        if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                            return;
                        }
                        lastId = orderIdList.get(orderIdList.size() - 1).getId();
                    }
                }
            }
        } catch (Exception e) {
            logger.error("[bakingStdDoTransfer]failed!cause by:{}", e);
        }
    }

    private void executeBakingStd(List<TempOrderBaking> list, int i, int j) {
        while (workQueue.remainingCapacity() < 10) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executorService.submit(() -> {
            try {
                if (!CollectionUtils.isEmpty(list)) {
                    List<Long> orderIdList = list.stream().map(TempOrderBaking::getId).collect(Collectors.toList());
//                    commonManager.updateBizType(orderIdList, i, j);
                    List<String> orderNoList = list.stream().map(TempOrderBaking::getOrderNo).collect(Collectors.toList());
//                    commonManager.updateBizTypeForItem(orderNoList, i, j);
//                    commonManager.updateBizTypeForDiscount(orderNoList, i, j);
//                    commonManager.updatePayBizType(8, orderNoList, i, j);
                    newDataSourceRefundDao.updateBizType(8, orderNoList);
                    newDataSourceRefundItemDao.updateBiz(8, orderNoList);
                    newDataSourceOrderRefundDetailsDao.updateBiz(8, orderNoList);
//                    List<Order> orderList = commonManager.listOrderById(orderIdList, i, j);
                    for (TempOrderBaking tempOrder : list) {
                        newOrderDao.updateBizType8(tempOrder.getId(), tempOrder.getUserId());
                        newDataSourceOrderItemDao.updateBizType8(tempOrder.getOrderNo(), tempOrder.getUserId());
                        newDataSourceOrderPayDetailsDao.updateBizType8(tempOrder.getOrderNo(), tempOrder.getUserId());
                        newDataSourceOrderDiscountDao.updateBizType(8, tempOrder.getUserId(), tempOrder.getOrderNo());
                        Order order = newOrderDao.selectById(tempOrder.getId(), tempOrder.getUserId());
                        searchManager.indexOrder(order, CommonConstants.ES_NEW_INDEX_TOPIC);
                    }
                }
            } catch (Exception e) {
                logger.error("bakingStdDoTransfer[executeBakingStd]failed！cause by:{}", e);
            }
        });
    }

    @Override
    public void orderRepair() {
        for (String orderNo : ListConst.list) {
            OrderIndex index = orderIndexDao.selectOne(orderNo);
            if (index == null) {
                logger.error("orderRepair111,orderNo:{}", orderNo);
                continue;
            }
            int count = 0;
            Order order = orderDao.selectByOrderNo(index.getOrderNo(), index.getUserId());
            if (order != null) {
                Long id = order.getId();
                for (int i = 0; i < dbSize; i++) {
                    for (int j = 0; j < tbSize; j++) {
                        List<Order> orderList = commonManager.scanOrderRespExt(Lists.newArrayList(id), i, j);
                        if (!CollectionUtils.isEmpty(orderList)) {
                            if (!Objects.equals(order.getOrderNo(), orderList.get(0).getOrderNo())) {
                                try {
                                    find(index, order, id);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                count++;
                                logger.info("handleOrder, count:{}", count);
                                try {
                                    searchManager.indexOrder(orderList.get(0));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    
    

    @Override
    public void orderPayed() {
        int total = 0;
        OrderQuery query = new OrderQuery();
        query.setSize(500);
        Long lastId = null;
        for (;;) {
            query.setLastId(lastId);
            List<TempOrder> orderIdList = tempOrderDao.selectList(query);
            if (CollectionUtils.isEmpty(orderIdList)) {
                break;
            }
            execute333(orderIdList);
            total += orderIdList.size();
            logger.info("[orderPayed]lastId:{}, total:{}", lastId, total);
            if (orderIdList.size() < 500) {
                break;
            }
            Result<String> redisData = redisManager.get("orderPayed_12");
            if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                return;
            }
            lastId = orderIdList.get(orderIdList.size() - 1).getId();
        }
    }

    @Autowired
    private OrderOperationDao operationDao;
    
    private void execute333(List<TempOrder> list) {
        while (workQueue.remainingCapacity() < 10) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        executorService.submit(() -> {
            try {
                if (!CollectionUtils.isEmpty(list)) {
                    for (TempOrder tempOrder : list) {
                        OrderIndex orderIndex = orderIndexDao.selectOne(tempOrder.getOrderNo());
                        if(orderIndex != null){
                            Order order = orderDao.selectByOrderNo(orderIndex.getOrderNo(), orderIndex.getUserId());
                            if(order != null){
                                Order up = new Order();
                                up.setId(order.getId());
                                up.setUserId(order.getUserId());
                                if(order.getOrderSubType() == 504){
                                    up.setOrderSubType(0);
                                }
                                else if(order.getOrderSubType() == 505){
                                    up.setOrderSubType(1);
                                }
                                else if(order.getOrderSubType() == 506){
                                    up.setOrderSubType(2);
                                }

                                if(order.getPayType() == 101){
                                    up.setPayType(1);
                                }
                                else if(order.getPayType() == 102){
                                    up.setPayType(2);
                                }
                                else if(order.getPayType() == 103){
                                    up.setPayType(17);
                                }
                                orderDao.orderDataUpdate(up);
                            }
                        }

                    }
                }
            } catch (Exception e) {
                logger.error("[execute1]failed！cause by:{}", e);
            }
        });
    }

    private void reverseMappingExtKey(Order order) {
        Map<String, Object> extraMap = order.getExtraMap();
        if (CollectionUtils.isEmpty(extraMap)) {
            return;
        }
        List<String> removeKeys = new ArrayList<>();
        ResExtFieldKeyMapping.MAPPING.forEach((key, newKey) -> {
            if (extraMap.containsKey(key)) {
                extraMap.put(newKey, extraMap.get(key));
                removeKeys.add(key);
            }
        });
        if (!CollectionUtils.isEmpty(removeKeys)) {
            for (String removeKey : removeKeys) {
                extraMap.remove(removeKey);
            }
        }
        order.setExtraMap(extraMap);
    }

    private void find(OrderIndex index, Order order, Long id) throws Exception {
        boolean re = false;
        for (;;) {
            Long newId = id - ThreadLocalRandom.current().nextLong(900000000000L);
            for (int i = 0; i < dbSize; i++) {
                for (int j = 0; j < tbSize; j++) {
                    List<Order> orderList = commonManager.scanOrderRespExt(Lists.newArrayList(newId), i, j);
                    if (!CollectionUtils.isEmpty(orderList)) {
                        re = true;
                    }
                }
            }

            if (re == false) {
                int i = orderDao.updateId(id, order.getUserId(), newId);
                if (i == 1) {
                    index.setOrderId(newId);
                    orderIndexDao.update(index);

                    searchManager.deleteOrder(id, order.getSellerId());
                    Order order1 = orderDao.selectByOrderNo(order.getOrderNo(), order.getUserId());
                    searchManager.indexOrder(order1);
                }
                logger.info("findNewId, orderNo:{},oldId:{}, newId:{}", order.getOrderNo(), id, newId);
                break;
            }
        }
    }

    static List<Long> list11 = Lists.newArrayList();

    static {
        list11.add(49006L);
    }

    @Override
    public void updateCompleteStatus() {
        for (Long sellerId : list11) {
            try {
                int total = 0;
                OrderQuery query = new OrderQuery();
                for (int i = 0; i < dbSize; i++) {
                    for (int j = 0; j < tbSize; j++) {
                        Long lastId = null;
                        query.setDbIndex(i + 1);
                        query.setTbIndex(j);
                        query.setSize(200);
                        for (;;) {
                            query.setLastId(lastId);
                            List<TempOrder> orderIdList = tempOrderDao.selectList(query);
                            if (CollectionUtils.isEmpty(orderIdList)) {
                                break;
                            }

                            executeUpdateStatus(orderIdList, i, j);

                            total += orderIdList.size();
                            logger.info("[updateCompleteStatus]lastId:{}, sellerId:{}, total:{}, i:{}, j:{}",
                                    lastId, sellerId, total, i, j);
                            if (orderIdList.size() < 200) {
                                break;
                            }
                            Result<String> redisData = redisManager.get("updateCompleteStatus_20240520");
                            if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                                return;
                            }
                            lastId = orderIdList.get(orderIdList.size() - 1).getId();
                        }
                    }
                }
            } catch (Exception e) {
                logger.error("[dinnerOrder]failed!cause by:{}", e);
            }
        }
    }

    private void executeUpdateStatus(List<TempOrder> list, int i, int j) {
        while (workQueue.remainingCapacity() < 10) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        executorService.submit(() -> {
            try {
                if (!CollectionUtils.isEmpty(list)) {
                    List<Long> orderIdList = list.stream().map(TempOrder::getId).collect(Collectors.toList());
                    commonManager.updateOrderCompleteStatus(orderIdList, i, j);

                    List<Order> orderList = commonManager.listOrderById(orderIdList, i, j);
                    searchManager.indexOrder(orderList);
                }
            } catch (Exception e) {
                logger.error("[execute1]failed！cause by:{}", e);
            }
        });
    }

    private void executePull(List<BaseIndexOrder> list) {
        while (workQueue.remainingCapacity() < 10) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        executorService.submit(() -> {
            try {
                List<TempOrder> t = new ArrayList<>();
                for (BaseIndexOrder indexOrder : list) {
                    TempOrder t1 = new TempOrder();
                    t1.setId(indexOrder.getOrderId());
                    t1.setUserId(indexOrder.getUserId());
                    t1.setSellerId(indexOrder.getSellerId());
                    t1.setOrderNo(indexOrder.getOrderNo());
                    t1.setDbIndex(RoutingAlgorithm.routeDB(indexOrder.getUserId(), dbSize) + 1);
                    t1.setTbIndex(RoutingAlgorithm.routeTB(indexOrder.getUserId(), dbSize, tbSize));
                    t.add(t1);
                }
                tempOrderDao.insertList(t);
            } catch (Exception e) {
                logger.error("[executePull]failed！cause by:{}", e);
            }
        });
    }

    @Autowired
    private TempOrderBakingDao tempOrderBakingDao;

    private void executePullBaking(List<BaseIndexOrder> list) {
        while (workQueue.remainingCapacity() < 10) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        executorService.submit(() -> {
            try {
                List<TempOrderBaking> t = new ArrayList<>();
                for (BaseIndexOrder indexOrder : list) {
                    TempOrderBaking t1 = new TempOrderBaking();
                    t1.setId(indexOrder.getOrderId());
                    t1.setUserId(indexOrder.getUserId());
                    t1.setSellerId(indexOrder.getSellerId());
                    t1.setOrderNo(indexOrder.getOrderNo());
                    t1.setDbIndex(RoutingAlgorithm.routeDB(indexOrder.getUserId(), dbSize) + 1);
                    t1.setTbIndex(RoutingAlgorithm.routeTB(indexOrder.getUserId(), dbSize, tbSize));
                    t.add(t1);
                }
                tempOrderBakingDao.insertList(t);
            } catch (Exception e) {
                logger.error("[executePull]failed！cause by:{}", e);
            }
        });
    }


    private void executePullBakingStd(List<BaseIndexOrder> list) {
        while (workQueue.remainingCapacity() < 10) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        executorService.submit(() -> {
            try {
                List<TempOrderBaking> t = new ArrayList<>();
                for (BaseIndexOrder indexOrder : list) {
                    TempOrderBaking t1 = new TempOrderBaking();
                    t1.setId(indexOrder.getOrderId());
                    t1.setUserId(indexOrder.getUserId());
                    t1.setSellerId(indexOrder.getSellerId());
                    t1.setOrderNo(indexOrder.getOrderNo());
                    t1.setDbIndex(RoutingAlgorithm.routeDB(indexOrder.getUserId(), dbSize) + 1);
                    t1.setTbIndex(RoutingAlgorithm.routeTB(indexOrder.getUserId(), dbSize, tbSize));
                    t.add(t1);
                }
                tempOrderBakingStdDao.insertList(t);
            } catch (Exception e) {
                logger.error("[executePull]failed！cause by:{}", e);
            }
        });
    }

    private void executePullCatering(List<BaseIndexOrder> list) {
        while (workQueue.remainingCapacity() < 10) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        executorService.submit(() -> {
            try {
                List<TempOrder> t = new ArrayList<>();
                for (BaseIndexOrder indexOrder : list) {
                    TempOrder t1 = new TempOrder();
                    t1.setId(indexOrder.getOrderId());
                    t1.setUserId(indexOrder.getUserId());
                    t1.setSellerId(indexOrder.getSellerId());
                    t1.setOrderNo(indexOrder.getOrderNo());
                    t1.setDbIndex(RoutingAlgorithm.routeDB(indexOrder.getUserId(), dbSize) + 1);
                    t1.setTbIndex(RoutingAlgorithm.routeTB(indexOrder.getUserId(), dbSize, tbSize));
                    t.add(t1);
                }
                tempOrderCaterDao.insertList(t);
            } catch (Exception e) {
                logger.error("[executePull]failed！cause by:{}", e);
            }
        });
    }

    @Override
    public void doBakingJiFenTransfer() {
        try {
            int total = 0;
            int size = 200;
            OrderQuery query = new OrderQuery();
            for (int i = 0; i < dbSize; i++) {
                for (int j = 0; j < tbSize; j++) {
                    Long lastId = null;
                    query.setDbIndex(i + 1);
                    query.setTbIndex(j);
                    query.setSize(size);
                    for (;;) {
                        query.setLastId(lastId);
                        List<TempOrderBaking> orderIdList = tempOrderBakingDao.selectList(query);
                        if (CollectionUtils.isEmpty(orderIdList)) {
                            break;
                        }
                        execute88(orderIdList, i, j);
                        total += orderIdList.size();
                        logger.info("[doBakingJiFenTransfer]lastId:{}, total:{}, i:{}, j:{}",
                                lastId, total, i, j);
                        if (orderIdList.size() < size) {
                            break;
                        }
                        Result<String> redisData = redisManager.get("transfer_dinner_order_data_202488");
                        if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                            return;
                        }
                        lastId = orderIdList.get(orderIdList.size() - 1).getId();
                    }
                }
            }
        } catch (Exception e) {
            logger.error("[doBakingJiFenTransfer]failed!cause by:{}", e);
        }
    }

    private Integer getStatus(Integer status){
        Integer data = 0;
        switch (status){
            case 1:
                data = 10;
                break;
            case 2:
                data = 20;
                break;
            case 3:
                data = 20;
                break;
            case 4:
                data = 50;
                break;
            case 8:
                data = 70;
                break;
            default:
                data = status;
                break;
        }
        return data;
    }
    private Integer getRefundStatus(Integer status){
        Integer data = 0;
        switch (status){
            case 0:
                data = 10;
                break;
            case 1:
                data = 30;
                break;
            case 2:
                data = 60;
                break;
            case 3:
                data = 40;
                break;
            default:
                data = status;
                break;
        }
        return data;
    }

    private void execute88(List<TempOrderBaking> list, int i, int j) {
        while (workQueue.remainingCapacity() < 10) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        executorService.submit(() -> {
            try {
                if (!CollectionUtils.isEmpty(list)) {
                    List<Long> orderIdList = list.stream().map(TempOrderBaking::getId).collect(Collectors.toList());
                    List<Order> orderListForUpdate = commonManager.listOrderById(orderIdList, i, j);
                    for (Order order : orderListForUpdate) {
                        order.setStatus(getStatus(order.getStatus()));
                        order.setOrderType(20);
                        order.setOrderSubType(29);
                    }
                    commonManager.updateBizTypeBaking(orderListForUpdate, i, j);

//                    commonManager.updateBizType(orderIdList, i, j);

                    List<String> orderNoList = list.stream().map(TempOrderBaking::getOrderNo).collect(Collectors.toList());
                    commonManager.updateBizTypeForItem(orderNoList, i, j);
                    commonManager.updateBizTypeForDiscount(orderNoList, i, j);
                    commonManager.updatePayBizTypeBaking(8, orderNoList, i, j);

                    List<Refund> refundList = refundDao.selectByOrderNoList(orderNoList);
                    for (Refund refund : refundList) {
                        refund.setStatus(getRefundStatus(refund.getStatus()));
                    }
                    refundDao.updateBakingJiFen(refundList);

                    refundItemDao.updateBiz(8, orderNoList);
                    refundDetailsDao.updateBiz(8, orderNoList);


                    for(TempOrderBaking item : list){
                        Order order = orderDao.selectById(item.getId(), item.getUserId());
                        searchManager.indexOrder(order, CommonConstants.ES_NEW_ORDER_INDEX);
                    }
                }
            } catch (Exception e) {
                logger.error("[execute88]failed！cause by:{}", e);
            }
        });
    }
}













