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

import cn.qmai.data.encrypt.service.DataEncryptService;
import com.alibaba.fastjson.JSON;
import com.github.dozermapper.core.Mapper;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zm.order.tool.server.cipher.AesEncrypt;
import com.zm.order.tool.server.component.ShardingKeyGenerator;
import com.zm.order.tool.server.constants.*;
import com.zm.order.tool.server.dao.*;
import com.zm.order.tool.server.dto.BaseCreateOrderDTO;
import com.zm.order.tool.server.dto.OrderCreateDTO;
import com.zm.order.tool.server.dto.OrderOperateDTO;
import com.zm.order.tool.server.dto.OrderPayDetailsDTO;
import com.zm.order.tool.server.helper.OrderWriteServiceHelper;
import com.zm.order.tool.server.hint.HintOrderDao;
import com.zm.order.tool.server.manager.*;
import com.zm.order.tool.server.model.*;
import com.zm.order.tool.server.newdatasource.NewDataSourceOrderDao;
import com.zm.order.tool.server.newdatasource.NewDataSourceOrderItemDao;
import com.zm.order.tool.server.newdatasource.NewDataSourceOrderPayDetailsDao;
import com.zm.order.tool.server.newdatasource.NewDataSourceRefundDao;
import com.zm.order.tool.server.query.ItemBatchingQuery;
import com.zm.order.tool.server.query.LineUpRecordQuery;
import com.zm.order.tool.server.query.OrderItemCommentCountQuery;
import com.zm.order.tool.server.query.OrderQuery;
import com.zm.order.tool.server.request.*;
import com.zm.order.tool.server.service.OrderWriteService;
import com.zm.order.tool.server.tb.TbOrderDao;
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.ExceptionInfo;
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.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
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 OrderWriteServiceImpl
 * @date 2021/02/19 1:41 下午
 */
@Service
@SuppressWarnings("all")
public class OrderWriteServiceImpl implements OrderWriteService, InitializingBean {

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

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private OrderUserRelationDao orderUserRelationDao;

    @Autowired
    private OrderItemDao orderItemDao;

    @Autowired
    private OrderItemBatchingDao itemBatchingDao;

    @Autowired
    private OrderDiscountDao discountDao;

    @Autowired
    private OrderItemCommentDao itemCommentDao;

    @Autowired
    private OrderItemCommentCountDao itemCommentCountDao;

    @Autowired
    private RefundDao refundDao;

    @Autowired
    private RefundItemDao refundItemDao;

    @Autowired
    private OrderPayDetailsDao payDetailsDao;

    @Autowired
    private NewDataSourceOrderPayDetailsDao newPayDetailsDao;

    @Autowired
    private OrderAddrDao addrDao;

    @Autowired
    private CommonManager commonManager;

    @Autowired
    private OrderDataDao orderDataDao;

    @Autowired
    private RedisManager redisManager;

    private BlockingQueue workQueue;

    private ExecutorService executorService;

    @Autowired
    private AsyncMessageManager messageManager;

    @Autowired
    private SearchManager searchManager;

    @Autowired
    private OrderManager orderManager;

    @Autowired
    private Mapper mapper;

    @Autowired
    private ShardingKeyGenerator keyGenerator;

    @Autowired
    private OrderPayDetailsDao orderPayDetailsDao;
    @Autowired
    private OrderIndexDao orderIndexDao;
    @Autowired
    private OrderIdUserDao orderIdUserDao;
    @Autowired
    private PerformanceSelfTakeDao takeDao;
    @Autowired
    private OrderCommentDao orderCommentDao;
    @Autowired
    private OrderCommentCountDao orderCommentCountDao;
    @Autowired
    private OrderUserRelationDao relationDao;
    @Autowired
    private OrderNoDao orderNoDao;
    @Autowired
    private OrderNoRefundDao orderNoRefundDao;
    @Autowired
    private OrderLogsDao orderLogsDao;

    @Autowired
    private NewDataSourceOrderDao newOrderDao;
    private NewDataSourceOrderItemDao newDataSourceOrderItemDao;

    @Autowired
    private NewDataSourceRefundDao newRefundDao;

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

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

    /**
     * 多线程配置
     */
    @Override
    public void afterPropertiesSet() {
        workQueue = new ArrayBlockingQueue(32);
        executorService = new ThreadPoolExecutor(
                2,
                40,
                1,
                TimeUnit.MINUTES,
                workQueue,
                new NamedThreadFactory("update-order-item-thread"), new ThreadPoolExecutor.AbortPolicy());
    }

    @Override
    public Result updateOrderRefund(UpdateRefundsRequest request) {
        try {
            logger.info("updateOrderRefund[start],request:{}", request);

            if (StringUtils.isEmpty(request.getRefundNo())) {
                return Result.failureData("退款单号不能为空");
            }
            Refund refund = refundDao.selectByRefundNo(request.getRefundNo());
            if(Objects.isNull(refund)) {
                return Result.failureData("退款单不存在");
            }
            Refund update = helper.buildUpdateRefund(request, refund);
            if (refund.getMasterDataSource()  == 1) {
                newRefundDao.update(update);
            } else {
                refundDao.update(update);
            }
        } catch (Throwable e) {
            logger.error("updateOrderRefund[execute] failed!, cause by:{}", e);
            return Result.failureData("更新失败");
        }
        return Result.successNullData();
    }

    @Override
    public Result updateOrderRefundItem(UpdateRefundItemRequest request) {
        try {
            logger.info("updateOrderRefundItem[start],request:{}", request);
            if (StringUtils.isEmpty(request.getRefundNo())) {
                return Result.failureData("退款单号不能为空");
            }
            if (StringUtils.isEmpty(request.getId())) {
                return Result.failureData("主键不能为空");
            }
            Refund refund = refundDao.selectByRefundNo(request.getRefundNo());
            if(Objects.isNull(refund)) {
                return Result.failureData("退款单不存在");
            }
            RefundItem refundItem = refundItemDao.selectById(request.getId());
            if(Objects.isNull(refund)) {
                return Result.failureData("退款商品不存在");
            }
            RefundItem update = helper.buildUpdateRefundItem(request, refundItem);
            refundItemDao.update(update);
        } catch (Throwable e) {
            logger.error("updateOrderRefundItem[execute] failed!, cause by:{}", e);
            return Result.failureData("更新失败");
        }
        return Result.successNullData();
    }

    @Override
    public Result updateOrderItemInfo() {
        Result result = new Result();
        int count = 0;
        // 31天之前 每次只更新一天的订单数据
        Date beforeStartAt = DateUtils.before(new Date(), Calendar.DATE, 8);
        Date beforeEndAt = DateUtils.before(new Date(), Calendar.DATE, 7);
        OrderQuery orderQuery = buildOrderQuery(beforeStartAt, beforeEndAt);
        try {
            for (int i = 0; i < dbSize; i++) {
                for (int j = 0; j < tbSize; j++) {
                    Long lastId = null;
                    for (; ; ) {
                        orderQuery.setLastId(lastId);
                        List<Long> orderList = commonManager.scanOrderId(orderQuery, i, j);
                        if (CollectionUtils.isEmpty(orderList)) {
                            break;
                        }
                        updateItemInfoQueue(orderList, i, j);
                        count += orderList.size();
                        logger.info("[updateOrderItemInfo]已更新:{}条", count);
                        if (orderList.size() < 200) {
                            break;
                        }
                        lastId = orderList.get(orderList.size() - 1);
                        Result<String> redisData = redisManager.get("update_order_item_info_switch");
                        if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                            result.setStatus(true);
                            result.setData(lastId);
                            return result;
                        }
                    }
                }
            }
            result.setStatus(true);
        } catch (Exception e) {
            logger.error("OrderWriteServiceImpl[updateOrderItemInfo]failed!cause by:{}", e);
            result.setException(ExceptionConstants.SYSTEM_ERROR);
        }
        return result;
    }

    @Override
    public Result updateOrderItemInfoTemp() {
        Result result = new Result();
        int count = 0;
        try {
            // 更新7 - 31天的数据
            for (int m=7; m<=31; m++) {
                Date beforeStartAt = DateUtils.before(new Date(), Calendar.DATE, m+1);
                Date beforeEndAt = DateUtils.before(new Date(), Calendar.DATE, m);
                OrderQuery orderQuery = buildOrderQuery(beforeStartAt, beforeEndAt);
                for (int i = 0; i < dbSize; i++) {
                    for (int j = 0; j < tbSize; j++) {
                        Long lastId = null;
                        for (; ; ) {
                            orderQuery.setLastId(lastId);
                            List<Long> orderList = commonManager.scanOrderId(orderQuery, i, j);
                            if (CollectionUtils.isEmpty(orderList)) {
                                break;
                            }
                            updateItemInfoQueue(orderList, i, j);
                            count += orderList.size();
                            logger.info("[updateOrderItemInfo]已更新:{}条", count);
                            if (orderList.size() < 200) {
                                break;
                            }
                            lastId = orderList.get(orderList.size() - 1);
                            Result<String> redisData = redisManager.get("update_order_item_info_switch");
                            if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                                result.setStatus(true);
                                result.setData(lastId);
                                return result;
                            }
                        }
                    }
                }
            }
            result.setStatus(true);
        } catch (Exception e) {
            logger.error("OrderWriteServiceImpl[updateOrderItemInfo]failed!cause by:{}", e);
            result.setException(ExceptionConstants.SYSTEM_ERROR);
        }
        return result;
    }

    private void updateItemInfoQueue(List<Long> orderList, int i, int j) {
        while (workQueue.remainingCapacity() < 20) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executorService.submit(() -> {
            try {
                commonManager.batchUpdateOrderItemInfo(orderList, i, j);
            } catch (Exception e) {
                logger.error("[updateItemInfoQueue]failed！cause by:{}", e);
            }
        });
    }

    private OrderQuery buildOrderQuery(Date beforeStartAt, Date beforeEndAt) {
        OrderQuery orderQuery = new OrderQuery();
        orderQuery.setOrderAtStart(beforeStartAt);
        orderQuery.setOrderAtEnd(beforeEndAt);
        orderQuery.setSize(200);
//        orderQuery.setItemInfoFlag(1);
//        orderQuery.setOrderNo("D600B073E0C0517573");
        return orderQuery;
    }

    @Override
    public void fixOrderMergeFeature() {
        logger.info("fixOrderMergeFeature[start]");
        try {
            int lastId = 0;
            int size = 100;
            int count = 0;
            int indexNullCount = 0;
            for (;;) {
                List<OrderNo> orderNoList = orderNoDao.selectList(lastId);
                if (CollectionUtils.isEmpty(orderNoList)) {
                    break;
                }
                for (OrderNo orderNo : orderNoList) {
                    List<OrderLogs> orderLogsList = orderLogsDao.selectByOrderNo(orderNo.getOrderNo());
                    Map<String, Object> extra = new HashMap<>();
                    for (OrderLogs log : orderLogsList) {
                        if (Objects.isNull(log.getOldFeatures())) {
                            continue;
                        }
                        Map<String, Object> old = JSON.parseObject(log.getOldFeatures(), Map.class);
                        extra.putAll(old);
                    }
                    logger.info("fixOrderMergeFeature[orderParse],orderLogCount:{},orderNo:{}", orderLogsList.size(), orderNo.getOrderNo());
                    OrderIndex index = orderIndexDao.selectOne(orderNo.getOrderNo());
                    if (Objects.isNull(index)) {
                        indexNullCount++;
                        logger.info("fixOrderMergeFeature[indexNull],orderLogCount:{},orderNo:{}", orderLogsList.size(), orderNo.getOrderNo());
                        continue;
                    }
                    Order order = orderDao.selectByOrderNo(orderNo.getOrderNo(), index.getUserId());

                    Order update = new Order();
                    update.setId(order.getId());
                    update.setUserId(order.getUserId());
                    extra.putAll(order.getExtraMap());
                    update.setExtraMap(extra);
                    orderDao.updateFeatures(update);
                }
                count++;
                lastId = orderNoList.get(orderNoList.size() - 1).getId();
                logger.info("fixOrderMergeFeature[running],count:{},lastId:{}", count, lastId);
                if (orderNoList.size() < size) {
                    break;
                }
            }
            logger.info("fixOrderMergeFeature[end], indexNullCount:{}", indexNullCount);

        } catch (Throwable e) {
            logger.error("fixOrderMergeFeature[execute] failed!, cause by:{}", e);
        }
    }



    @Override
    public void fixOrderMergeFeatureSellerId() {
        logger.info("fixOrderMergeFeature[start]");
        try {
            int lastId = 0;
            int size = 100;
            int count = 0;
            int indexNullCount = 0;
            for (;;) {
                List<OrderNo> orderNoList = orderNoDao.selectList(lastId);
                if (CollectionUtils.isEmpty(orderNoList)) {
                    break;
                }
                for (OrderNo orderNo : orderNoList) {
                    List<OrderLogs> orderLogsList = orderLogsDao.selectByOrderNo(orderNo.getOrderNo());
                    logger.info("fixOrderMergeFeature[orderParse],orderLogCount:{},orderNo:{}", orderLogsList.size(), orderNo.getOrderNo());
                    OrderIndex index = orderIndexDao.selectOne(orderNo.getOrderNo());
                    if (Objects.isNull(index)) {
                        indexNullCount++;
                        logger.info("fixOrderMergeFeature[indexNull],orderLogCount:{},orderNo:{}", orderLogsList.size(), orderNo.getOrderNo());
                        continue;
                    }
                    Order order = orderDao.selectByOrderNo(orderNo.getOrderNo(), index.getUserId());
                    orderDao.updateStatus(order.getId(), order.getUserId(), 50);
                    searchManager.indexOrder(orderDao.selectById(order.getId(), order.getUserId()));
                }
                count++;
                lastId = orderNoList.get(orderNoList.size() - 1).getId();
                logger.info("fixOrderMergeFeature[running],count:{},lastId:{}", count, lastId);
                if (orderNoList.size() < size) {
                    break;
                }
            }
            logger.info("fixOrderMergeFeature[end], indexNullCount:{}", indexNullCount);

        } catch (Throwable e) {
            logger.error("fixOrderMergeFeature[execute] failed!, cause by:{}", e);
        }
    }



    @Override
    public void fixOrderMergeFeatureSellerIdRefund() {
        logger.info("fixOrderMergeFeatureSellerIdRefund[start]");
        try {
            int lastId = 0;
            int size = 100;
            int count = 0;
            int indexNullCount = 0;
            for (;;) {
                List<OrderNo> orderNoList = orderNoRefundDao.selectList(lastId);
                if (CollectionUtils.isEmpty(orderNoList)) {
                    break;
                }
                for (OrderNo orderNo : orderNoList) {
                    List<OrderLogs> orderLogsList = orderLogsDao.selectByOrderNo(orderNo.getOrderNo());
                    logger.info("fixOrderMergeFeatureSellerIdRefund[orderParse],orderLogCount:{},orderNo:{}", orderLogsList.size(), orderNo.getOrderNo());
                    OrderIndex index = orderIndexDao.selectOne(orderNo.getOrderNo());
                    if (Objects.isNull(index)) {
                        indexNullCount++;
                        logger.info("fixOrderMergeFeatureSellerIdRefund[indexNull],orderLogCount:{},orderNo:{}", orderLogsList.size(), orderNo.getOrderNo());
                        continue;
                    }
                    Order order = orderDao.selectByOrderNo(orderNo.getOrderNo(), index.getUserId());
                    orderDao.updateStatus(order.getId(), order.getUserId(), 70);
                    searchManager.indexOrder(orderDao.selectById(order.getId(), order.getUserId()));
                }
                count++;
                lastId = orderNoList.get(orderNoList.size() - 1).getId();
                logger.info("fixOrderMergeFeatureSellerIdRefund[running],count:{},lastId:{}", count, lastId);
                if (orderNoList.size() < size) {
                    break;
                }
            }
            logger.info("fixOrderMergeFeatureSellerIdRefund[end], indexNullCount:{}", indexNullCount);

        } catch (Throwable e) {
            logger.error("fixOrderMergeFeature[execute] failed!, cause by:{}", e);
        }
    }

//    @Autowired
//    private  ConfigCenterManager configCenterManager;
    @Override
    public void updateOrderByOrderNoListTemp(CreateOrderRequest request) {
        try {
//            boolean sellerUpgrade = configCenterManager.seekUpgradeConfig(request.getSellerId());
//            logger.info("bin_log_sync_seller_upgrade, sellerId:{},sellerUpgrade:{}", request.getSellerId(), sellerUpgrade);
//
//            if (sellerUpgrade) {
//                return;
//            }

//            List<String> list = ListConst14.list;
//            for (String orderNo : list) {
//                OrderIndex orderIndex = orderIndexDao.selectOne(orderNo);
//                Order order = orderDao.selectByOrderNo(orderNo, orderIndex.getUserId());
//                BusinessOrderUpdateRequest request1 = new BusinessOrderUpdateRequest();
//                request1.setOrderNo(orderNo);
//                Map<String, Object> map = new HashMap<>(10);
//                map.put("platformIsDiscount", 0);
//                map.put("merchantsDiscount", 0);
//                map.put("receiptAmount", CommonUtils.fenToYuan(order.getPayAmount()));
//                request1.setPayInfo(JSON.toJSONString(map));
//                request1.setBuyerRemarks("系统补单 【不要制作餐品】！！");
//                updateOrderByOrderNoList(request1);
//
//                List<OrderPayDetails> orderPayDetails = orderPayDetailsDao.selectByOrderNo(orderNo, orderIndex.getUserId());
//                if (!CollectionUtils.isEmpty(orderPayDetails)) {
//                    OrderPayDetails pay = orderPayDetails.get(0);
//                    BusinessOrderUpdatePayDetailsRequest payRequest = new BusinessOrderUpdatePayDetailsRequest();
//                    payRequest.setOrderNo(orderNo);
//                    payRequest.setPayDetailsId(pay.getId());
//                    payRequest.setAmount(order.getPayAmount());
//                    Map<String, Object> payMap = new HashMap<>(10);
//                    payMap.put("platformIsDiscount", 0);
//                    payMap.put("merchantsDiscount", 0);
//                    payRequest.setExtraMap(JSON.toJSONString(payMap));
//                    updateOrderPayByOrderNo(payRequest);
//                }
//            }
        } catch (Throwable e) {
            logger.error("updateOrderByOrderNoListTemp[execute] failed!, cause by:{}", e);
        }
    }

    @Override
    public Result updateOrderByOrderNoList(BusinessOrderUpdateRequest request) {
        try {

            if (StringUtils.isEmpty(request.getOrderNo())) {
                return Result.failureData("订单号不能为空");
            }
            List<String> orderNoList = new ArrayList<>();
            if (!StringUtils.isEmpty(request.getOrderNo())) {
                orderNoList.add(request.getOrderNo());
            }
            List<OrderIndex> orderIndexList = orderIndexDao.selectList(orderNoList);

            for (OrderIndex orderIndex : orderIndexList) {
                if (Objects.isNull(orderIndex)) {
                    continue;
                }
                List<OrderUserRelation> orderUserRelations = orderUserRelationDao.selectListByOrderNo(orderIndex.getOrderNo());
                if (CollectionUtils.isEmpty(orderUserRelations)) {
                    doUpdate(request, orderIndex.getUserId(), orderIndex.getOrderNo(), 0);
                } else {
                    for (OrderUserRelation orderUserRelation : orderUserRelations){
                        doUpdate(request, orderUserRelation.getUserId(), orderUserRelation.getOrderNo(), orderUserRelation.getIsRoot());
                    }
                }
            }
        } catch (Throwable e) {
            logger.error("updateOrderByOrderNoList[execute] failed!, cause by:{}", e);
            return Result.failureData(e);
        }
        return Result.successNullData();
    }

    private void doUpdate(BusinessOrderUpdateRequest request, Long userId, String orderNo, Integer isRoot){
        try {

            Order order = orderDao.selectByOrderNo(orderNo, userId);
            if (Objects.isNull(order)) {
                return;
            }
            //构建订单更新参数
            BusinessOrderUpdateModelRequest businessOrderUpdateRequest = buildUpdateOrderParams(request, order);

            if(!StringUtils.isEmpty(request.getPayDetailsListString())){
                List<CreateOrderPayDetailsRequest> payDetailsLists = JSON.parseArray(request.getPayDetailsListString(), CreateOrderPayDetailsRequest.class);
                request.setPayDetailsList(payDetailsLists);
            }
            //构建支付信息
            List<OrderPayDetails> payDetailsList = new ArrayList<>(10);
            if (!CollectionUtils.isEmpty(request.getPayDetailsList())) {
                List<OrderPayDetailsDTO> orderPayDetailsDTOList = createOrderPayDetailsRequestListToOrderPayDetailsDTOList(request.getPayDetailsList());
                payDetailsList = buildOrderPayDetails(orderPayDetailsDTOList, businessOrderUpdateRequest, order);
            }
            orderManager.updateOrder(businessOrderUpdateRequest, payDetailsList, order);
            if (Objects.nonNull(request.getSelfTakeCode())) {
                PerformanceSelfTake performanceSelfTake = new PerformanceSelfTake();
                performanceSelfTake.setUserId(userId);
                performanceSelfTake.setOrderNo(orderNo);
                performanceSelfTake.setSelfTakeCode(request.getSelfTakeCode());
                if (order.getMasterDataSource() == 1) {
                    takeDao.updateByOrderNo(performanceSelfTake);
                } else {
                    takeDao.updateByOrderNo(performanceSelfTake);
                }
            }
            if (isRoot == 0) {
                //同步ES
                if (order.getMasterDataSource() == 1) {
                    order = newOrderDao.selectByOrderNo(orderNo, userId);
                    searchManager.indexOrder(order, ES_NEW_INDEX_TOPIC);
                }else{
                    order = orderDao.selectByOrderNo(orderNo, userId);
                    searchManager.indexOrder(order, null);
                }
            }
        } catch (Throwable e) {
            logger.error("DelEsExpireDataTask[execute] failed!, cause by:{}", e);
        }
    }

    @Autowired
    private DataEncryptService encryptService;

    /**
     * 构建业务更新订单的参数
     *
     * @param orderIndex
     * @param request
     * @return businessOrderUpdateRequest
     * @date 2021/8/12 15:37
     **/
    private BusinessOrderUpdateModelRequest buildUpdateOrderParams(
                                                                   BusinessOrderUpdateRequest request,
                                                                   Order order) {
        BusinessOrderUpdateModelRequest businessOrderUpdateRequest = new BusinessOrderUpdateModelRequest();
        businessOrderUpdateRequest.setId(order.getId());
        businessOrderUpdateRequest.setUserId(order.getUserId());
        if (Objects.nonNull(request.getStatus())) {
            businessOrderUpdateRequest.setStatus(request.getStatus());
        }
        if (Objects.nonNull(request.getPayStatus())) {
            businessOrderUpdateRequest.setPayStatus(request.getPayStatus());
        }
        if (Objects.nonNull(request.getOrderType())) {
            businessOrderUpdateRequest.setOrderType(request.getOrderType());
        }
        if (Objects.nonNull(request.getOrderSubType())) {
            businessOrderUpdateRequest.setOrderSubType(request.getOrderSubType());
        }
        if (Objects.nonNull(request.getPayAt())) {
            businessOrderUpdateRequest.setPayAt(request.getPayAt());
        }
        if (Objects.nonNull(request.getPayType())) {
            businessOrderUpdateRequest.setPayType(request.getPayType());
        }
        if (Objects.nonNull(request.getPayer())) {
            businessOrderUpdateRequest.setPayer(request.getPayer());
        }
        if (Objects.nonNull(request.getPayNo())) {
            businessOrderUpdateRequest.setPayNo(request.getPayNo());
        }
        if (Objects.nonNull(request.getThirdPayNo())) {
            businessOrderUpdateRequest.setThirdPayNo(request.getThirdPayNo());
        }
        if (Objects.nonNull(request.getCompletedAt())) {
            businessOrderUpdateRequest.setCompletedAt(request.getCompletedAt());
        }
        buildUpdateOrderParams1(request, businessOrderUpdateRequest, order);
        return businessOrderUpdateRequest;
    }

    public void buildUpdateOrderParams1(BusinessOrderUpdateRequest request,
                                        BusinessOrderUpdateModelRequest businessOrderUpdateRequest,
                                        Order order) {
        if (Objects.nonNull(request.getPerformanceStatus())) {
            businessOrderUpdateRequest.setPerformanceStatus(request.getPerformanceStatus());
        }
        if (Objects.nonNull(request.getPerformanceType())) {
            businessOrderUpdateRequest.setPerformanceType(request.getPerformanceType());
        }
        if (Objects.nonNull(request.getBuyerRemarks())) {
            businessOrderUpdateRequest.setBuyerRemarks(request.getBuyerRemarks());
        }
        if (Objects.nonNull(request.getStoreId())) {
            businessOrderUpdateRequest.setStoreId(request.getStoreId());
        }
        if (Objects.nonNull(request.getTotalAmount())) {
            businessOrderUpdateRequest.setTotalAmount(request.getTotalAmount());
        }
        if (Objects.nonNull(request.getPackAmount())) {
            businessOrderUpdateRequest.setPackAmount(request.getPackAmount());
        }
        if (Objects.nonNull(request.getItemAmount())) {
            businessOrderUpdateRequest.setItemAmount(request.getItemAmount());
        }
        if (Objects.nonNull(request.getFreightAmount())) {
            businessOrderUpdateRequest.setFreightAmount(request.getFreightAmount());
        }
        if (Objects.nonNull(request.getDiscountAmount())) {
            businessOrderUpdateRequest.setDiscountAmount(request.getDiscountAmount());
        }
        if (Objects.nonNull(request.getActualAmount())) {
            businessOrderUpdateRequest.setActualAmount(request.getActualAmount());
        }
        if (Objects.nonNull(request.getPayAmount())) {
            businessOrderUpdateRequest.setPayAmount(request.getPayAmount());
        }
        if (Objects.nonNull(request.getPayType())) {
            businessOrderUpdateRequest.setPayType(request.getPayType());
        }
        if (Objects.nonNull(request.getStoreOrderNo())) {
            businessOrderUpdateRequest.setStoreOrderNo(request.getStoreOrderNo());
        }
        if (!StringUtils.isEmpty(request.getSellerRemarks())) {
            businessOrderUpdateRequest.setSellerRemarks(request.getSellerRemarks());
        }
        if (!StringUtils.isEmpty(request.getExtraMap())) {
            Map<String, Object> extra = order.getExtraMap();
            Map<String, Object> requestMap = JSON.parseObject(request.getExtraMap(), Map.class);
            // 扩展字段原数据没有的key 添加，没有的key 添加，不删除key
            extra.putAll(requestMap);
            businessOrderUpdateRequest.setExtraMap(extra);
            try {
                businessOrderUpdateRequest.setFeaturesCipher(encryptService.encrypt(businessOrderUpdateRequest.getFeatures()));
            } catch (JSQLParserException e) {
                e.printStackTrace();
            }
        }
        if (!StringUtils.isEmpty(request.getPayInfo())) {
            Map<String, Object> payInfoMap = JSON.parseObject(order.getPayInfo());
            Map<String, Object> requestMap = JSON.parseObject(request.getPayInfo(), Map.class);
            payInfoMap.putAll(requestMap);
            businessOrderUpdateRequest.setPayInfo(JSON.toJSONString(payInfoMap));
        }
    }

    protected List<OrderPayDetailsDTO> createOrderPayDetailsRequestListToOrderPayDetailsDTOList(List<CreateOrderPayDetailsRequest> list) {
        if (list == null) {
            return null;
        }
        List<OrderPayDetailsDTO> list1 = new ArrayList<OrderPayDetailsDTO>(list.size());
        for (CreateOrderPayDetailsRequest createOrderPayDetailsRequest : list) {
            list1.add(createOrderPayDetailsRequestToOrderPayDetailsDTO(createOrderPayDetailsRequest));
        }
        return list1;
    }

    protected OrderPayDetailsDTO createOrderPayDetailsRequestToOrderPayDetailsDTO(CreateOrderPayDetailsRequest createOrderPayDetailsRequest) {
        if (createOrderPayDetailsRequest == null) {
            return null;
        }
        OrderPayDetailsDTO orderPayDetailsDTO = new OrderPayDetailsDTO();
        orderPayDetailsDTO.setPayAt(createOrderPayDetailsRequest.getPayAt());
        orderPayDetailsDTO.setSellerId(createOrderPayDetailsRequest.getSellerId());
        orderPayDetailsDTO.setStoreId(createOrderPayDetailsRequest.getStoreId());
        orderPayDetailsDTO.setPayType(createOrderPayDetailsRequest.getPayType());
        orderPayDetailsDTO.setAmount(createOrderPayDetailsRequest.getAmount());
        orderPayDetailsDTO.setPayNo(createOrderPayDetailsRequest.getPayNo());
        orderPayDetailsDTO.setThirdPayNo(createOrderPayDetailsRequest.getThirdPayNo());
        Map<String, Object> map = createOrderPayDetailsRequest.getExtraMap();
        if (map != null) {
            orderPayDetailsDTO.setExtraMap(new HashMap<String, Object>(map));
        }
        return orderPayDetailsDTO;
    }

    public List<OrderPayDetails> buildOrderPayDetails(List<OrderPayDetailsDTO> payDetailsDTOList, BusinessOrderUpdateModelRequest request, Order order) {
        if (CollectionUtils.isEmpty(payDetailsDTOList)) {
            return Collections.EMPTY_LIST;
        }
        List<OrderPayDetails> payDetailsList = new ArrayList<>(payDetailsDTOList.size());
        List<InnerOrderPayDetails> innerOrderPayDetailsList = new ArrayList<>(payDetailsDTOList.size());
        for (OrderPayDetailsDTO payDetailDto : payDetailsDTOList) {
            OrderPayDetails payDetail = mapper.map(payDetailDto, OrderPayDetails.class);
            setPayDetailsParam(order, payDetail);
            payDetailsList.add(payDetail);
            innerOrderPayDetailsList.add(mapper.map(payDetail, InnerOrderPayDetails.class));
        }
        request.setPayDetailInfo(JSON.toJSONString(innerOrderPayDetailsList));
        return payDetailsList;
    }

    private void setPayDetailsParam(Order order, OrderPayDetails payDetail) {
        payDetail.setId(keyGenerator.generateSnowflakeNumKey());
        payDetail.setOrderNo(order.getOrderNo());
        payDetail.setUserId(order.getUserId());
        payDetail.setOrderAt(order.getOrderAt());
        payDetail.setSellerId(order.getSellerId());
        payDetail.setStoreId(order.getStoreId());
        payDetail.setOrderType(order.getOrderType());
        payDetail.setPerformanceType(order.getPerformanceType());
        payDetail.setBizType(order.getBizType());
        payDetail.setSource(Objects.nonNull(order.getSource()) ? order.getSource() : 0);
        if (StringUtils.isEmpty(payDetail.getPayNo())) {
            payDetail.setPayNo("");
        }
        if (StringUtils.isEmpty(payDetail.getThirdPayNo())) {
            payDetail.setThirdPayNo("");
        }
        if (Objects.isNull(payDetail.getStatus())) {
            payDetail.setStatus(0);
        }
    }

    @Override
    public Result createOrder(OrderCreateDTO orderCreateDTO) {
        Result<Long> result = new Result<>();
        try {
            // 1.参数校验
            ExceptionInfo exceptionInfo = helper.checkCreateOrderParam(orderCreateDTO);
            if (ExceptionConstants.OK != exceptionInfo) {
                result.setException(exceptionInfo);
                return result;
            }
            // 2. 处理业务逻辑
            // 2.1 幂等校验 根据订单号
            Result<OrderNoIndex> getOrderIndexResult = orderManager.getOrderNoIndex(orderCreateDTO.getOrderNo(), true);
            if (!getOrderIndexResult.isStatus()) {
                result.setException(getOrderIndexResult.exceptionInfo());
                return result;
            }
            OrderNoIndex orderNoIndex = getOrderIndexResult.getData();
            if (Objects.nonNull(orderNoIndex)) {
                result.setData(orderNoIndex.getOrderId());
                result.setStatus(true);
                return result;
            }
            // 2.2 数据拆解
            Order order = helper.buildOrder(orderCreateDTO);
            List<OrderDiscount> discountList = helper.buildOrderDisCountList(orderCreateDTO, order);
            List<OrderItem> itemList = helper.buildOrderItem(orderCreateDTO, order);
            OrderAddr orderAddr = helper.buildOrderAddr(orderCreateDTO, order);
            List<OrderItemBatching> itemBatchingList = helper.buildItemBatching(orderCreateDTO, itemList);
            List<OrderPayDetails> payDetailsList = helper.buildOrderPayDetails(orderCreateDTO, order);
            // 参数整合
            BaseCreateOrderDTO orderDTO = helper.buildOrderHolder(order, itemList, discountList, orderCreateDTO,
                    orderAddr, itemBatchingList, payDetailsList);
            // 2.3 持久化
            Long orderId = orderManager.createOrder(orderDTO);

            // 3.组装返回
            result.setData(orderId);
            result.setStatus(true);
        } catch (Throwable throwable) {
            logger.error("OrderWriteServiceImpl[createOrder] failed, request:{}, cause by:{}",
                    orderCreateDTO.toString(), Throwables.getStackTraceAsString(throwable));
            result.setException(ExceptionConstants.CREATE_ORDER_ERROR);
        }
        return result;
    }


    @Override
    public Result updateOrderItemByOrderNo(BusinessOrderUpdateRequest request) {
        try {
            if (StringUtils.isEmpty(request.getOrderNo())) {
                return Result.failureData("订单号不能为空");
            }
            if (StringUtils.isEmpty(request.getOrderItemId())) {
                return Result.failureData("订单商品id不能为空");
            }
            OrderIndex orderIndex = orderIndexDao.selectOne(request.getOrderNo());
            if (Objects.isNull(orderIndex)) {
                return Result.failureData("订单索引不存在");
            }
            Order order = orderDao.selectByOrderNo(orderIndex.getOrderNo(), orderIndex.getUserId());
            if (Objects.isNull(order)) {
                return Result.failureData("订单不存在");
            }
            //构建商品更新参数
            OrderItem orderItem = buildUpdateOrderItemParams(orderIndex, request);

            //更新订单商品快照
            List<OrderItem> orderItemList = orderItemDao.selectByOrderNo(request.getOrderNo(), orderIndex.getUserId());
            String itemInfo = order.getItemInfo();
            if (!Objects.equals("TL", itemInfo)) {
                List<InnerOrderItem> innerOrderItemList = ConvertUtils.convertList(orderItemList, InnerOrderItem.class);
                if (!CollectionUtils.isEmpty(innerOrderItemList)) {
                    order.setItemInfo(JSON.toJSONString(innerOrderItemList));
                }
            }
            if (order.getMasterDataSource() == 1) {
                newDataSourceOrderItemDao.updateItemSign(orderItem);
                newOrderDao.updateItemInfo(order);
                //同步ES
                order = newOrderDao.selectById(orderIndex.getOrderId(), orderIndex.getUserId());
                searchManager.indexOrder(order, ES_NEW_INDEX_TOPIC);
            }else{
                orderItemDao.updateItemSign(orderItem);
                orderDao.updateItemInfo(order);
                //同步ES
                order = orderDao.selectById(orderIndex.getOrderId(), orderIndex.getUserId());
                searchManager.indexOrder(order, null);
            }


        } catch (Throwable e) {
            logger.error("updateOrderByOrderNoList[execute] failed!, cause by:{}", e);
            return Result.failureData(e);
        }
        return Result.successNullData();
    }


    @Override
    public Result delOrderItemBatch(DelItemBatchRequest request) {
        try {
            if (StringUtils.isEmpty(request.getOrderNo())) {
                return Result.failureData("订单号不能为空");
            }
            if (StringUtils.isEmpty(request.getOrderItemBatchingId())) {
                return Result.failureData("订单商品加料id不能为空");
            }
            OrderIndex orderIndex = orderIndexDao.selectOne(request.getOrderNo());
            if (Objects.isNull(orderIndex)) {
                return Result.failureData("订单索引不存在");
            }
            Order order = orderDao.selectById(orderIndex.getOrderId(), orderIndex.getUserId());
            if (Objects.isNull(order)) {
                return Result.failureData("订单不存在");
            }
            OrderItemBatching orderItemBatching = itemBatchingDao.selectById(request.getOrderItemBatchingId(), order.getUserId());
            if (Objects.isNull(orderItemBatching)) {
                return Result.failureData("订单商品加料不存在");
            }

            List<Long> idList = Arrays.asList(request.getOrderItemBatchingId());
            itemBatchingDao.deletes(idList, order.getUserId(), 0);

            //构建商品更新参数
            ItemBatchingQuery query = new ItemBatchingQuery();
            query.setUserId(orderItemBatching.getUserId());
            query.setOrderItemId(orderItemBatching.getOrderItemId());
            query.setPageSize(100);
            query.setPageNo(1);
            List<OrderItemBatching> orderItemBatchings = itemBatchingDao.selectList(query);
            List<InnerOrderItemBatching> innerOrderItemBatchings = ConvertUtils.convertList(orderItemBatchings, InnerOrderItemBatching.class);

            OrderItem orderItem = new OrderItem();
            orderItem.setId(orderItemBatching.getOrderItemId());
            orderItem.setUserId(orderItemBatching.getUserId());
            if (innerOrderItemBatchings.size() > 10) {
                orderItem.setBatchingInfo("TL");
            } else {
                orderItem.setBatchingInfo(JSON.toJSONString(innerOrderItemBatchings));
            }
            orderItemDao.updateItemSign(orderItem);

            //更新订单商品快照
//            List<OrderItem> orderItemList = orderItemDao.selectByOrderNo(request.getOrderNo(), orderIndex.getUserId());
//            String itemInfo = order.getItemInfo();
//            if (!Objects.equals("TL", itemInfo)) {
//                List<InnerOrderItem> innerOrderItemList = ConvertUtils.convertList(orderItemList, InnerOrderItem.class);
//                if (!CollectionUtils.isEmpty(innerOrderItemList)) {
//                    order.setItemInfo(JSON.toJSONString(innerOrderItemList));
//                }
//            }
//            orderDao.updateItemInfo(order);

            //同步ES
            order = orderDao.selectById(orderIndex.getOrderId(), orderIndex.getUserId());
            searchManager.indexOrder(order, null);

        } catch (Throwable e) {
            logger.error("updateOrderByOrderNoList[execute] failed!, cause by:{}", e);
            return Result.failureData(e);
        }
        return Result.successNullData();
    }

    @Override
    public Result insertOrderItem(BusinessItemInsertRequest request) {
        try {
            if (StringUtils.isEmpty(request.getOrderNo())) {
                return Result.failureData("订单号不能为空");
            }
            OrderIndex orderIndex = orderIndexDao.selectOne(request.getOrderNo());
            if (Objects.isNull(orderIndex)) {
                return Result.failureData("订单索引不存在");
            }
            Order order = orderDao.selectById(orderIndex.getOrderId(), orderIndex.getUserId());
            if (Objects.isNull(order)) {
                return Result.failureData("订单不存在");
            }
            //构建商品更新参数
            List<OrderItem> list = new ArrayList<>();
            OrderItem orderItem = buildInsertOrderItemParams(orderIndex, request, order);
            list.add(orderItem);
            orderItemDao.inserts(list);

            //更新订单商品快照
            List<OrderItem> orderItemList = orderItemDao.selectByOrderNo(request.getOrderNo(), orderIndex.getUserId());
            String itemInfo = order.getItemInfo();
            if (!Objects.equals("TL", itemInfo)) {
                List<InnerOrderItem> innerOrderItemList = ConvertUtils.convertList(orderItemList, InnerOrderItem.class);
                if (innerOrderItemList.size() > 10) {
                    order.setItemInfo("TL");
                } else {
                    if (!CollectionUtils.isEmpty(innerOrderItemList)) {
                        order.setItemInfo(JSON.toJSONString(innerOrderItemList));
                    }
                }
            }
            orderDao.updateItemInfo(order);

            //同步ES
            order = orderDao.selectById(orderIndex.getOrderId(), orderIndex.getUserId());
            searchManager.indexOrder(order, null);

        } catch (Throwable e) {
            logger.error("updateOrderByOrderNoList[execute] failed!, cause by:{}", e);
            return Result.failureData(e);
        }
        return Result.successNullData();    }

    private OrderItem buildUpdateOrderItemParams(OrderIndex orderIndex, BusinessOrderUpdateRequest request) {
        OrderItem orderItem = new OrderItem();
        orderItem.setId(request.getOrderItemId());
        orderItem.setUserId(orderIndex.getUserId());
        if (Objects.nonNull(request.getNum())) {
            orderItem.setNum(request.getNum());
        }
        if (Objects.nonNull(request.getItemSign())) {
            orderItem.setItemSign(request.getItemSign());
        }
        if (Objects.nonNull(request.getIsDeleted())) {
            orderItem.setIsDeleted(request.getIsDeleted());
        }
        if (Objects.nonNull(request.getItemId())) {
            orderItem.setItemId(request.getItemId());
        }
        if (Objects.nonNull(request.getItemName())) {
            orderItem.setItemName(request.getItemName());
        }
        if (Objects.nonNull(request.getItemImage())) {
            orderItem.setItemImage(request.getItemImage());
        }
        if (Objects.nonNull(request.getItemBarcode())) {
            orderItem.setItemBarcode(request.getItemBarcode());
        }
        if (Objects.nonNull(request.getGoodsId())) {
            orderItem.setGoodsId(request.getGoodsId());
        }
        if (Objects.nonNull(request.getCostPrice())) {
            orderItem.setCostPrice(request.getCostPrice());
        }
        if (Objects.nonNull(request.getItemPrice())) {
            orderItem.setItemPrice(request.getItemPrice());
        }
        if (Objects.nonNull(request.getPaidAmount())) {
            orderItem.setPaidAmount(request.getPaidAmount());
        }
        if (Objects.nonNull(request.getDiscountAmount())) {
            orderItem.setDiscountAmount(request.getDiscountAmount());
        }
        if (Objects.nonNull(request.getExtraMap())) {
            orderItem.setDiscountAmount(request.getDiscountAmount());
        }
        if (Objects.nonNull(request.getIsGift())) {
            orderItem.setIsGift(request.getIsGift());
        }
        if (!StringUtils.isEmpty(request.getExtraMap())) {
            OrderItem item = orderItemDao.selectById(request.getOrderItemId(), orderIndex.getUserId());
            Map<String, Object> itemExtraMap = item.getExtraMap();
            Map<String, Object> requestMap = JSON.parseObject(request.getExtraMap(), Map.class);
            // 扩展字段原数据没有的key 添加，没有的key 添加，不删除key
            for (Map.Entry<String, Object> entry : requestMap.entrySet()) {
                itemExtraMap.put(entry.getKey(), entry.getValue());
            }
            orderItem.setExtraMap(itemExtraMap);
        }
        buildUpdateOrderItemParams1(orderIndex, request, orderItem);
        return orderItem;
    }
    private void buildUpdateOrderItemParams1(OrderIndex orderIndex, BusinessOrderUpdateRequest request, OrderItem orderItem){
        if (Objects.nonNull(request.getMarketPrice())) {
            orderItem.setMarketPrice(request.getMarketPrice());
        }
        if (Objects.nonNull(request.getPackAmount())) {
            orderItem.setPackAmount(request.getPackAmount());
        }
        if (Objects.nonNull(request.getProductNo())) {
            orderItem.setProductNo(request.getProductNo());
        }
        if (Objects.nonNull(request.getSellerBearAmount())) {
            orderItem.setSellerBearAmount(request.getSellerBearAmount());
        }
    }
    private OrderPayDetails buildUpdateOrderPayParams(OrderIndex orderIndex, BusinessOrderUpdatePayDetailsRequest request) {
        OrderPayDetails payDetails = new OrderPayDetails();
        payDetails.setId(request.getPayDetailsId());
        payDetails.setUserId(orderIndex.getUserId());
        if (Objects.nonNull(request.getPayNo())) {
            payDetails.setPayNo(request.getPayNo());
        }
        if (Objects.nonNull(request.getPayType())) {
            payDetails.setPayType(request.getPayType());
        }
        if (Objects.nonNull(request.getThirdPayNo())) {
            payDetails.setThirdPayNo(request.getThirdPayNo());
        }
        if (Objects.nonNull(request.getAmount())) {
            payDetails.setAmount(request.getAmount());
        }
        if (Objects.nonNull(request.getIsDeleted())) {
            payDetails.setIsDeleted(request.getIsDeleted());
        }
        if (!StringUtils.isEmpty(request.getExtraMap())) {
            OrderPayDetails item = payDetailsDao.selectOne(request.getPayDetailsId(), orderIndex.getUserId());
            Map<String, Object> itemExtraMap = item.getExtraMap();
            Map<String, Object> requestMap = JSON.parseObject(request.getExtraMap(), Map.class);
            // 扩展字段原数据没有的key 添加，没有的key 添加，不删除key
            for (Map.Entry<String, Object> entry : requestMap.entrySet()) {
                itemExtraMap.put(entry.getKey(), entry.getValue());
            }
            payDetails.setExtraMap(itemExtraMap);
        }
        return payDetails;
    }

    private OrderDiscount buildUpdateOrderDiscountParams(OrderIndex orderIndex, BusinessOrderUpdateDiscountRequest request) {
        OrderDiscount discount = new OrderDiscount();
        discount.setId(request.getDiscountId());
        discount.setUserId(orderIndex.getUserId());
        if (!StringUtils.isEmpty(request.getExtraMap())) {
            OrderDiscount orderDiscount = discountDao.selectOne(request.getDiscountId(), orderIndex.getUserId());
            if (Objects.nonNull(orderDiscount)) {
                Map<String, Object> itemExtraMap = orderDiscount.getExtraMap();
                Map<String, Object> requestMap = JSON.parseObject(request.getExtraMap(), Map.class);
                // 扩展字段原数据没有的key 添加，没有的key 添加，不删除key
                for (Map.Entry<String, Object> entry : requestMap.entrySet()) {
                    itemExtraMap.put(entry.getKey(), entry.getValue());
                }
                discount.setExtraMap(itemExtraMap);
            }
        }
        if(Objects.nonNull(request.getIsDeleted())){
            discount.setIsDeleted(request.getIsDeleted());
        }
        if(Objects.nonNull(request.getDiscountAmount())){
            discount.setDiscountAmount(request.getDiscountAmount());
        }
        if(!StringUtils.isEmpty(request.getDiscountText())){
            discount.setDiscountText(request.getDiscountText());
        }
        return discount;
    }

    @Override
    public Result delOrderComment(DelOrderCommentRequest request) {
        Result result = new Result();
        try {
            OrderComment orderComment = orderCommentDao.selectOne(request.getOrderNo(), request.getSellerId());
            if (Objects.nonNull(orderComment)) {
                orderCommentDao.deleteByOrderNo(request.getOrderNo(), request.getSellerId());
            }
            result.setStatus(true);
        } catch (Throwable e) {
            logger.error("DelEsExpireDataTask[delOrderComment] failed!, cause by:{}", e);
            result.setStatus(false);
        }
        return result;
    }

    @Override
    public Result delDuplicateOrderComment(DelOrderCommentRequest request) {
        if (Objects.isNull(request.getOrderNo())) {
            return Result.failureData("订单号不能为空");
        }
        if (Objects.isNull(request.getSellerId())) {
            return Result.failureData("sellerId不能为空");
        }
        Result result = new Result();
        try {
            List<OrderComment> orderCommentList = orderCommentDao.selectByOrderNo(request.getOrderNo(), request.getSellerId());
            if (orderCommentList.size() < 2) {
                return result;
            }
            Long storeId = 0L;
            List<OrderComment> orderCommentDelList = new ArrayList<>(orderCommentList.size() - 1);
            List<Long> orderCommentIds = new ArrayList<>(orderCommentList.size() - 1);
            for (int i = 0; i < orderCommentList.size(); i++) {
                if (i == 0) {
                    continue;
                }
                orderCommentDelList.add(orderCommentList.get(i));
                orderCommentIds.add(orderCommentList.get(i).getId());
                storeId = orderCommentList.get(i).getStoreId();
            }
            orderCommentDao.delete(orderCommentIds, request.getSellerId());
            OrderCommentCount orderCommentCount = orderCommentCountDao.selectOne(request.getSellerId(), storeId);
            if(Objects.nonNull(orderCommentCount)){
                for(OrderComment orderComment : orderCommentDelList){
                    helper.buildUpdateCommentCountForDel(orderCommentCount, orderComment);
                    orderCommentCountDao.update(orderCommentCount);
                }
            }

            result.setStatus(true);
        } catch (Throwable e) {
            logger.error("DelEsExpireDataTask[delOrderComment] failed!, cause by:{}", e);
            result.setStatus(false);
        }
        return result;
    }

    @Override
    public Result updateAddrOrderNo(BusinessOrderUpdateAddrRequest request) {
        try {
            if (StringUtils.isEmpty(request.getOrderNo())) {
                return Result.failureData("订单号不能为空");
            }
            OrderIndex orderIndex = orderIndexDao.selectOne(request.getOrderNo());
            if (Objects.isNull(orderIndex)) {
                return Result.failureData("订单索引不存在");
            }
            Order order = orderDao.selectById(orderIndex.getOrderId(), orderIndex.getUserId());
            if (Objects.isNull(order)) {
                return Result.failureData("订单不存在");
            }
            OrderAddr addr = addrDao.selectByOrderNo(order.getOrderNo(), order.getUserId());
            if (Objects.isNull(addr)) {
                return Result.failureData("订单地址不存在");
            }
            OrderAddr orderAddr = mapper.map(request, OrderAddr.class);
            orderAddr.setUserId(order.getUserId());
            if(!StringUtils.isEmpty(orderAddr.getAcceptName())){
                orderAddr.setAcceptNameCipher(AesEncrypt.encrypt(orderAddr.getAcceptName()));
            }
            if(!StringUtils.isEmpty(orderAddr.getDoorNumber())){
                orderAddr.setDoorNumberCipher(AesEncrypt.encrypt(orderAddr.getDoorNumber()));
            }
            if(!StringUtils.isEmpty(orderAddr.getStreet())){
                orderAddr.setStreetCipher(AesEncrypt.encrypt(orderAddr.getStreet()));
            }
            addrDao.updateAddrInfo(orderAddr);

            //更新订单快照
            OrderAddr orderAddrNew = addrDao.selectByOrderNo(order.getOrderNo(), order.getUserId());
            InnerOrderAddr innerOrderAddr = mapper.map(orderAddrNew, InnerOrderAddr.class);
            if (!StringUtils.isEmpty(innerOrderAddr.getStreet())) {
                innerOrderAddr.setStreet(AesEncrypt.encrypt(innerOrderAddr.getStreet()));
                innerOrderAddr.setEncipher(1);
            }
            if (!StringUtils.isEmpty(innerOrderAddr.getAcceptName())) {
                innerOrderAddr.setAcceptName(AesEncrypt.encrypt(innerOrderAddr.getAcceptName()));
                innerOrderAddr.setEncipher(1);
            }
            if (!StringUtils.isEmpty(innerOrderAddr.getMobile())) {
                innerOrderAddr.setMobile(AesEncrypt.encrypt(innerOrderAddr.getMobile()));
                innerOrderAddr.setEncipher(1);
            }
            if (!StringUtils.isEmpty(innerOrderAddr.getLng())) {
                innerOrderAddr.setLng(AesEncrypt.encrypt(innerOrderAddr.getLng()));
            }
            if (!StringUtils.isEmpty(innerOrderAddr.getLat())) {
                innerOrderAddr.setLat(AesEncrypt.encrypt(innerOrderAddr.getLat()));
            }

            Order update = new Order();
            update.setId(order.getId());
            update.setOrderNo(order.getOrderNo());
            update.setUserId(order.getUserId());
            update.setAddrInfo(JSON.toJSONString(innerOrderAddr));
            orderDao.updateAddrInfo(update);

            //同步ES
            order = orderDao.selectById(orderIndex.getOrderId(), orderIndex.getUserId());
            searchManager.indexOrder(order, null);

        } catch (Throwable e) {
            logger.error("OrderWriteServiceImpl[updateAddrOrderNo] failed!, cause by:{}", e);
            return Result.failureData(e);
        }
        return Result.successNullData();
    }

    @Override
    public Result updateOrderPayByOrderNo(BusinessOrderUpdatePayDetailsRequest request) {
        try {
            if (StringUtils.isEmpty(request.getOrderNo())) {
                return Result.failureData("订单号不能为空");
            }
            if (StringUtils.isEmpty(request.getPayDetailsId())) {
                return Result.failureData("订单支付明细id不能为空");
            }
            OrderIndex orderIndex = orderIndexDao.selectOne(request.getOrderNo());
            if (Objects.isNull(orderIndex)) {
                return Result.failureData("订单索引不存在");
            }
            Order order = orderDao.selectById(orderIndex.getOrderId(), orderIndex.getUserId());

            //构建支付明细更新参数
            OrderPayDetails orderPayDetails = buildUpdateOrderPayParams(orderIndex, request);
            List<OrderPayDetails> orderPayDetailsList;
            if (order.getMasterDataSource() == 1 ) {
                newPayDetailsDao.update(orderPayDetails);
                orderPayDetailsList = newPayDetailsDao.selectByOrderNo(request.getOrderNo(), orderIndex.getUserId());
            }else{
                payDetailsDao.update(orderPayDetails);
                orderPayDetailsList = payDetailsDao.selectByOrderNo(request.getOrderNo(), orderIndex.getUserId());
            }
            //更新订单支付快照
            String payDetailInfo = order.getPayDetailInfo();
            if (!Objects.equals("PF", payDetailInfo)) {
                List<InnerOrderPayDetails> innerPayList = ConvertUtils.convertList(orderPayDetailsList, InnerOrderPayDetails.class);
                if (!CollectionUtils.isEmpty(innerPayList)) {
                    order.setPayDetailInfo(JSON.toJSONString(innerPayList));
                }
            }
            if (order.getMasterDataSource() == 1 ) {
                newOrderDao.updatePayDetailInfo(order);
                //同步ES
                order = newOrderDao.selectById(orderIndex.getOrderId(), orderIndex.getUserId());
                searchManager.indexOrder(order, ES_NEW_INDEX_TOPIC);
            } else {
                orderDao.updatePayDetailInfo(order);
                //同步ES
                order = orderDao.selectById(orderIndex.getOrderId(), orderIndex.getUserId());
                searchManager.indexOrder(order, null);
            }



        } catch (Throwable e) {
            logger.error("OrderWriteServiceImpl[updateOrderPayByOrderNo] failed!, cause by:{}", e);
            return Result.failureData(e);
        }
        return Result.successNullData();
    }

    @Override
    public Result addOrderPayByOrderNo(BusinessAddPayDetailsRequest request) {
        try {
            if (StringUtils.isEmpty(request.getOrderNo())) {
                return Result.failureData("订单号不能为空");
            }
            if (StringUtils.isEmpty(request.getUserId())) {
                return Result.failureData("用户id不能为空");
            }
            Order order = orderDao.selectByOrderNo(request.getOrderNo(), request.getUserId());
            if (Objects.isNull(order)) {
                return Result.failureData("订单不存在");
            }

            //构建支付明细更新参数
            OrderPayDetails orderPayDetails = mapper.map(request, OrderPayDetails.class);
            orderPayDetails.setId(keyGenerator.generateSnowflakeNumKey());
            orderPayDetails.setOrderType(order.getOrderType());
            orderPayDetails.setSource(order.getSource());
            orderPayDetails.setPerformanceType(order.getPerformanceType());
            orderPayDetails.setPayAt(order.getPayAt());
            orderPayDetails.setSellerId(order.getSellerId());
            orderPayDetails.setStoreId(order.getStoreId());
            orderPayDetails.setOrderAt(order.getOrderAt());
            payDetailsDao.insert(orderPayDetails);


            //更新订单支付快照
            List<OrderPayDetails> orderPayDetailsList = payDetailsDao.selectByOrderNo(request.getOrderNo(), order.getUserId());
            String payDetailInfo = order.getPayDetailInfo();
            if (!Objects.equals("PF", payDetailInfo)) {
                List<InnerOrderPayDetails> innerPayList = ConvertUtils.convertList(orderPayDetailsList, InnerOrderPayDetails.class);
                if (!CollectionUtils.isEmpty(innerPayList)) {
                    order.setPayDetailInfo(JSON.toJSONString(innerPayList));
                }
                if (innerPayList.size() > 10) {
                    order.setPayDetailInfo("PF");
                }
            }
            orderDao.updatePayDetailInfo(order);
            //同步ES
            order = orderDao.selectById(order.getId(), order.getUserId());
            searchManager.indexOrder(order, null);

        } catch (Throwable e) {
            logger.error("OrderWriteServiceImpl[addOrderPayByOrderNo] failed!, cause by:{}", e);
            return Result.failureData(e);
        }
        return Result.successNullData();
    }

    @Override
    public Result<List<Order>> orderBaseList(OrderBaseListRequest request) {
        Result result = new Result();
        try {
            if (CollectionUtils.isEmpty(request.getOrderNoList())) {
                return Result.failureData("订单号不能为空");
            }
            if (request.getOrderNoList().size() > 50) {
                return Result.failureData("数量不能超过50");
            }
            if (CollectionUtils.isEmpty(request.getUserIdList())) {
                return Result.failureData("用户id不能为空");
            }
            if (request.getUserIdList().size() > 50) {
                return Result.failureData("数量不能超过50");
            }
            OrderQuery query = new OrderQuery();
            query.setOrderNoList(request.getOrderNoList());
            query.setUserIdList(request.getUserIdList());
            List<Order> orderList = orderDao.selectListByOrderNosUserIds(query);
            for (Order order : orderList) {
                List<OrderItem> orderItemList = orderItemDao.selectByOrderNo(order.getOrderNo(), order.getUserId());
                order.setItemList(orderItemList);
            }
            if (CollectionUtils.isEmpty(orderList)) {
                return Result.successData(Collections.emptyList());
            }
            result.setData(orderList);
            result.setStatus(true);
        } catch (Throwable e) {
            logger.error("OrderWriteServiceImpl[addOrderPayByOrderNo] failed!, cause by:{}", e);
            return Result.failureData(e);
        }
        return result;
    }


    @Override
    public Result delOrderPayByOrderNo(BusinessOrderUpdatePayDetailsRequest request) {
        try {
            if (StringUtils.isEmpty(request.getOrderNo())) {
                return Result.failureData("订单号不能为空");
            }
            if (StringUtils.isEmpty(request.getPayDetailsId())) {
                return Result.failureData("订单支付明细id不能为空");
            }
            OrderIndex orderIndex = orderIndexDao.selectOne(request.getOrderNo());
            if (Objects.isNull(orderIndex)) {
                return Result.failureData("订单索引不存在");
            }
            Order order = orderDao.selectById(orderIndex.getOrderId(), orderIndex.getUserId());

            //删除支付明细更新参数
            Long userId = orderIndex.getUserId();
            if (Objects.nonNull(request.getUserId())) {
                userId = request.getUserId();
            }
            payDetailsDao.delete(request.getPayDetailsId(), userId);

            //更新订单支付快照
            List<OrderPayDetails> orderPayDetailsList = payDetailsDao.selectByOrderNo(request.getOrderNo(), orderIndex.getUserId());
            String payDetailInfo = order.getPayDetailInfo();
            if (!Objects.equals("PF", payDetailInfo)) {
                List<InnerOrderPayDetails> innerPayList = ConvertUtils.convertList(orderPayDetailsList, InnerOrderPayDetails.class);
                if (!CollectionUtils.isEmpty(innerPayList)) {
                    order.setPayDetailInfo(JSON.toJSONString(innerPayList));
                }
            }
            orderDao.updatePayDetailInfo(order);

            //同步ES
            order = orderDao.selectById(orderIndex.getOrderId(), orderIndex.getUserId());
            searchManager.indexOrder(order, null);

            //同步子订单信息
            OrderOperateDTO operateDTO = new OrderOperateDTO();
            operateDTO.setOrderNo(request.getOrderNo());
            operateDTO.setUserId(orderIndex.getUserId());
            operateDTO.setOperateInfo(Maps.newHashMap());
            messageManager.sendSyncSubOrdersMessage(operateDTO);

        } catch (Throwable e) {
            logger.error("OrderWriteServiceImpl[updateOrderPayByOrderNo] failed!, cause by:{}", e);
            return Result.failureData(e);
        }
        return Result.successNullData();
    }

    @Override
    public void syncSubOrder(){
        logger.info("syncSubOrder[start]{}");

        for (String orderNo : ListConst18.list) {
            OrderIndex orderIndex = orderIndexDao.selectOne(orderNo);
            OrderOperateDTO operateDTO = new OrderOperateDTO();
            operateDTO.setOrderNo(orderNo);
            operateDTO.setUserId(orderIndex.getUserId());
            operateDTO.setOperateInfo(Maps.newHashMap());
            messageManager.sendSyncSubOrdersMessage(operateDTO);
        }
        logger.info("syncSubOrder[end]{}");

    }

    @Override
    public void updateOrderPay() {
        try {
            List<OrderIdUser> orderIdUserList = orderIdUserDao.selectList(0L);
            int count = 0;
            for (OrderIdUser orderIdUser : orderIdUserList) {
                BusinessOrderUpdatePayDetailsRequest request = mapper.map(orderIdUser, BusinessOrderUpdatePayDetailsRequest.class);
                updateOrderPayByOrderNo(request);
                count++;
            }
            logger.error("OrderWriteServiceImpl[count]{}", count);

        } catch (Throwable e) {
            logger.error("OrderWriteServiceImpl[delOrderPayByOrderNo] failed!, cause by:{}", e);
            return;
        }
        return;
    }

    @Override
    public void updateOrderAmount() {
        for (String orderNo : ListConst.list) {
            String[] split = orderNo.split("-");
            BusinessOrderUpdatePayDetailsRequest req = new BusinessOrderUpdatePayDetailsRequest();
            OrderIndex index = orderIndexDao.selectOne(split[0]);
            if (index != null) {
                Order order = orderDao.selectByOrderNo(index.getOrderNo(), index.getUserId());
                if (order != null) {
                    List<OrderPayDetails> payDetails =
                        orderPayDetailsDao.selectByOrderNo(index.getOrderNo(), index.getUserId());
                    Order u = new Order();
                    u.setId(order.getId());
                    u.setUserId(order.getUserId());
                    if (!CollectionUtils.isEmpty(payDetails)) {
                        u.setPayDetailInfo(
                            JSON.toJSONString(ConvertUtils.convertList(payDetails, InnerOrderPayDetails.class)));
                    }
//                    u.setStatus(20);
//                    u.setPayStatus(1);
//                    u.setPayType(Integer.valueOf(split[3]));
//                    u.setPayNo(split[4]);
//                    u.setThirdPayNo(split[5]);
//                    u.setPayAt(new Date(split[6]));
                    if (order.getMasterDataSource() == null || Objects.equals(0, order.getMasterDataSource())) {
                        orderDao.update(u);
                        try {
                            searchManager.indexOrder(orderDao.selectByOrderNo(index.getOrderNo(), index.getUserId()));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        newOrderDao.update(u);
                        try {
                            searchManager.indexOrder(orderDao.selectByOrderNo(index.getOrderNo(), index.getUserId()),
                                ES_NEW_INDEX_TOPIC);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                }
            }
        }
    }

    @Override
    public void updateOrderPayType() {
        int count = 0;
        for (String orderNo : ListConst.list) {
            BusinessOrderUpdatePayDetailsRequest req = new BusinessOrderUpdatePayDetailsRequest();
            OrderIndex index = orderIndexDao.selectOne(orderNo);
            if (index != null) {
                Order order = orderDao.selectByOrderNo(index.getOrderNo(), index.getUserId());
                BusinessOrderUpdateRequest request = new BusinessOrderUpdateRequest();
                request.setOrderNo(orderNo);
                request.setPayType(4);
                updateOrderByOrderNoList(request);
//                if (order != null) {
//                    List<OrderPayDetails> payDetails = orderPayDetailsDao.selectByOrderNo(index.getOrderNo(), index.getUserId());
//                    if (!CollectionUtils.isEmpty(payDetails)) {
//                        if (payDetails.size() == 1) {
//                            req.setOrderNo(orderNo);
//                            req.setPayDetailsId(payDetails.get(0).getId());
//                            req.setPayType(16);
//                            updateOrderPayByOrderNo(req);
//                            count++;
//                        } else {
//                            logger.error("[ORDER_PAY_DETAIL_GT_1]orderNo:{}", orderNo);
//                        }
//                    }
//                }
            }
            logger.info("updateOrderPayType,orderNo:{}, count:{}", orderNo, count);
        }
    }

    @Override
    public void commentMessage() {
        int count = 0;
        try {
            for (String orderNo : ListConst2.list) {
                count = pushMessage(count, orderNo);
            }
            for (String orderNo : ListConst3.list) {
                count = pushMessage(count, orderNo);
            }
            for (String orderNo : ListConst4.list) {
                count = pushMessage(count, orderNo);
            }
        }catch (Exception e){

        }
    }

    private int pushMessage(int count, String orderNo) throws InterruptedException {
        OrderIndex index = orderIndexDao.selectOne(orderNo);
        if (index != null) {
            Order order = orderDao.selectByOrderNo(index.getOrderNo(), index.getUserId());
            messageManager.sendCommentMessage(mapper.map(order, OrderCommentMessage.class));
            count++;
            logger.info("commentMessage count:{}", count);
            Thread.sleep(500);
        }
        return count;
    }

    @Override
    public void updatePayDetailAmount() {
        int count = 0;
        for (HashMap<String,Object> map : ListConstMap.list) {
            Long id = Long.valueOf(map.get("id").toString());
            String orderNo = map.get("orderNo").toString();
            logger.info("updatePayDetailAmount id:{};orderNo:{}", id, orderNo);

            OrderIndex index = orderIndexDao.selectOne(orderNo);
            if (index != null) {
                Order order = orderDao.selectByOrderNo(index.getOrderNo(), index.getUserId());
                if (order != null) {
                    OrderPayDetails payDetail = orderPayDetailsDao.selectById(
                            orderNo,
                            index.getUserId(),
                            id);
                    if (Objects.nonNull(payDetail)) {
                        Map<String, Object> extraMap = payDetail.getExtraMap();
                        if(Objects.nonNull(extraMap.get("payAmount"))){
                            BigDecimal payAmount = new BigDecimal(extraMap.get("payAmount").toString());
                            payAmount = payAmount.multiply(new BigDecimal(100));
                            extraMap.put("payAmount", payAmount);
                            payDetail.setExtraMap(extraMap);
                            //更新
                            orderPayDetailsDao.updateExtra(payDetail);

                            //更新订单支付快照
                            List<OrderPayDetails> orderPayDetailsList = payDetailsDao.selectByOrderNo(orderNo, index.getUserId());
                            String payDetailInfo = order.getPayDetailInfo();
                            if (!Objects.equals("PF", payDetailInfo)) {
                                List<InnerOrderPayDetails> innerPayList = ConvertUtils.convertList(orderPayDetailsList, InnerOrderPayDetails.class);
                                if (!CollectionUtils.isEmpty(innerPayList)) {
                                    order.setPayDetailInfo(JSON.toJSONString(innerPayList));
                                }
                            }
                            orderDao.updatePayDetailInfo(order);
                            count++;
                        }
                    }
                }
            }
        }
        logger.info("updatePayDetailAmount count:{}", count);
    }

    @Override
    public Result deleteOrderByOrderNo(BusinessOrderUpdateRequest request) {
        Result result = new Result();
        try {
            if (StringUtils.isEmpty(request.getOrderNo())) {
                return Result.failureData("订单号不能为空");
            }
            OrderIndex orderIndex = orderIndexDao.selectOne(request.getOrderNo());
            if (Objects.isNull(orderIndex)) {
                return Result.failureData("订单索引不存在");
            }
            Order order = orderDao.selectById(orderIndex.getOrderId(), orderIndex.getUserId());
            if (Objects.isNull(order)) {
                return Result.failureData("订单不存在");
            }
            final int deleted = -1;
            //删订单
            orderDao.delete(orderIndex.getOrderId(), orderIndex.getUserId(), deleted);
            //删商品
            List<OrderItem> itemList = orderItemDao.selectByOrderNo(request.getOrderNo(), orderIndex.getUserId());
            if (!CollectionUtils.isEmpty(itemList)) {
                List<Long> itemIdList = itemList.stream().map(OrderItem::getId).collect(Collectors.toList());
                orderItemDao.deletes(itemIdList, orderIndex.getUserId(), deleted);
            }

            //删退款
            List<Refund> refundList = refundDao.selectByOrderNo(request.getOrderNo());
            if (!CollectionUtils.isEmpty(refundList)) {
                List<Long> refundIdList = refundList.stream().map(Refund::getId).collect(Collectors.toList());
                refundDao.deleteByIdList(refundIdList, deleted);
            }

            //删支付明细
            payDetailsDao.deleteByOrderNo(request.getOrderNo(), orderIndex.getUserId());
            //删优惠
            discountDao.deleteByOrderNo(request.getOrderNo(), orderIndex.getUserId());
            //同步ES
            order = orderDao.selectById(orderIndex.getOrderId(), orderIndex.getUserId());
            searchManager.indexOrder(order, null);

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

    @Override
    public Result deleteOrderByOrderNoTemp() {
        List<String> list = ListConst12.list;
        int count = 0;
        for (String orderNo : list) {
            BusinessOrderUpdateRequest request = new BusinessOrderUpdateRequest();
            request.setOrderNo(orderNo);
            Result result = deleteOrderByOrderNo(request);
            count ++;
            logger.info("deleteOrderByOrderNoTemp result:{},orderNo:{},count:{}", result, orderNo, count);

        }
        return null;
    }


    @Autowired
    private IdOrderNoDao idOrderNoDao;

    @Override
    public Result delOrderFromTempDB() {
        Result result = new Result();
        try {
            int count = 0;
            int size = 200;
            final Integer bizType = 8;
            Long lastId = null;
            for (; ; ) {
                List<IdOrderNo> idOrderList = idOrderNoDao.selectListByIdSize(lastId, size);
                if (CollectionUtils.isEmpty(idOrderList)) {
                    break;
                }
                for (IdOrderNo item : idOrderList) {
                    BusinessOrderUpdateRequest request = new BusinessOrderUpdateRequest();
                    request.setOrderNo(item.getOrderNo());
                    Result result1 = deleteOrderByOrderNo(request);
                }
                lastId = idOrderList.get(idOrderList.size() - 1).getId();
                logger.info("delOrderFromTempDB[running] ,count:{}, lastId:{}", count, lastId);
                if (idOrderList.size() < size) {
                    break;
                }
            }
            logger.info("delOrderFromTempDB[end],count:{}, lastId:{}", count, lastId);

            result.setStatus(true);
        } catch (Throwable e) {
            logger.error("delOrderFromTempDB failed!, cause by:{}", e);
            result.setException(com.zm.order.tool.server.service.ExceptionConstants.SYSTEM_ERROR);
        }
        return result;
    }


    @Override
    public void itemUpdateTemp() {
        List<String> list = ListConst13.list;
        int count = 0;
        for (String orderNo : list) {
            OrderIndex orderIndex = orderIndexDao.selectOne(orderNo);
            if (Objects.isNull(orderIndex)) {
                continue;
            }
            List<OrderItem> orderItemList = orderItemDao.selectByOrderNo(orderNo, orderIndex.getUserId());
            for (OrderItem item : orderItemList) {
                if(Objects.equals(item.getItemSign(), "08030239")){
                    BusinessOrderUpdateRequest request = new BusinessOrderUpdateRequest();
                    request.setOrderNo(orderNo);
                    request.setItemSign("830239");
                    request.setOrderItemId(item.getId());
                    Result result = updateOrderItemByOrderNo(request);
                    count ++;
                    logger.info("itemUpdateTemp result:{},orderNo:{},count:{}", result, orderNo, count);
                }
            }

        }
    }


    private OrderItem buildInsertOrderItemParams(OrderIndex orderIndex, BusinessItemInsertRequest request, Order order) {
        OrderItem orderItem = mapper.map(request, OrderItem.class);
        orderItem.setId(keyGenerator.generateSnowflakeNumKey());
        orderItem.setBizType(order.getBizType());
        orderItem.setUserId(orderIndex.getUserId());
        if (Objects.isNull(orderItem.getMarketPrice())) {
            orderItem.setMarketPrice(0);
        }
        if (Objects.isNull(orderItem.getCostPrice())) {
            orderItem.setCostPrice(0);
        }
        if (Objects.isNull(orderItem.getMemberPrice())) {
            orderItem.setMemberPrice(0);
        }
        if (Objects.isNull(orderItem.getItemPrice())) {
            orderItem.setItemPrice(0);
        }
        if (Objects.isNull(orderItem.getNum())) {
            orderItem.setNum(new BigDecimal(0));
        }
        if (Objects.isNull(orderItem.getDiscountAmount())) {
            orderItem.setDiscountAmount(0);
        }
        if (Objects.isNull(orderItem.getPackAmount())) {
            orderItem.setPackAmount(0);
        }
        if (Objects.isNull(orderItem.getGoodsId())) {
            orderItem.setGoodsId(0L);
        }
        if (Objects.isNull(orderItem.getActivityId())) {
            orderItem.setActivityId(0L);
        }
        if (Objects.isNull(orderItem.getIsTimeDiscount())) {
            orderItem.setIsTimeDiscount(0);
        }
        if (Objects.isNull(orderItem.getIsGift())) {
            orderItem.setIsGift(0);
        }
        if (Objects.isNull(orderItem.getUserId())) {
            orderItem.setUserId(0L);
        }
        if (Objects.isNull(orderItem.getStatus())) {
            orderItem.setStatus(0);
        }
        if (Objects.isNull(orderItem.getOrderAt())) {
            orderItem.setOrderAt(new Date());
        }
        if (Objects.isNull(orderItem.getItemType())) {
            orderItem.setItemType(0);
        }
        if (Objects.isNull(orderItem.getPaidAmount())) {
            orderItem.setPaidAmount(0);
        }
        return orderItem;
    }


    @Autowired
    private TbOrderDao tbOrderDao;

    @Override
    public void sellerDataAnalysis() {
        Map<Long, String> target = new HashMap<>(2048);
        long now = 1655308800000L;

        OrderQuery query = new OrderQuery();
//        query.setOrderAtEnd(new Date(1654012799000L));
//        query.setOrderAtStart(new Date(1653926400000L));
        query.setSize(100);
        query.setOrderByFlag(1);

        final String tag = "--";

        logger.info("[TARGET]targetSeller:{}", target);
    }

    static List<Integer> l = new ArrayList<>();

    static {
        l.add(0);
        l.add(1);
        l.add(2);
        l.add(3);
        l.add(4);
        l.add(5);
        l.add(6);
        l.add(7);
        l.add(8);
        l.add(9);
        l.add(10);
        l.add(11);
        l.add(12);
        l.add(13);
        l.add(14);
        l.add(15);
        l.add(16);
    }

    @Override
    public void syncOrderToElasticsearch() {
        try {
            int count = 0;
            OrderQuery query = getOrderQuery();
            for (int i = 0; i < dbSize; i++) {
                for (int j = 0; j < tbSize; j++) {
                    Long lastId = null;
                    for (;;) {
                        query.setLastId(lastId);
                        List<Order> orderList = commonManager.scanOrder(query, i, j);
                        if (CollectionUtils.isEmpty(orderList)) {
                            break;
                        }
                        List<Order> newList = filterOrder(orderList);
                        executeTransfer(newList);
                        count += newList.size();
                        logger.info("syncOrderToElasticsearch:{}条, lastId:{}, i:{}, j:{}",
                                count, orderList.get(orderList.size() - 1).getId(), i, j);
                        lastId = orderList.get(orderList.size() - 1).getId();
                        if (orderList.size() < 200) {
                            break;
                        }
                        Result<String> redisData = redisManager.get("sync_order_to_es_new");
                        if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                            System.exit(-1);
                        }
                    }

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

    @Override
    public void syncOrderToElasticsearch0() {
        try {
            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 (Objects.equals(1, order.getOrderSubType())) {
                            OrderUserRelation relation = relationDao.selectRoot(order.getOrderNo());
                            if (relation == null) {
                                try {
                                    searchManager.indexOrder(order, null);
                                    count++;
                                    logger.info("syncOrderDataList_count:{}", count);
                                    continue;
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                            if (Objects.equals(order.getUserId(), relation.getUserId())) {
                                try {
                                    searchManager.indexOrder(order, null);
                                    count++;
                                    logger.info("syncOrderDataList_count:{}", count);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        } else {
                            try {
                                searchManager.indexOrder(order, null);
                                count++;
                                logger.info("syncOrderDataList_count:{}", count);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("syncOrderToElasticsearch0 failed! cause by:{}", e);
        }
    }

    @Autowired
    private OrderNoUserDao userDao;

    @Override
    public void deleteEsData() {
        int count = 0;
        Long lastId = null;
        for (;;) {
            List<OrderNoUser> list = userDao.selectList(lastId);
            if (CollectionUtils.isEmpty(list)) {
                return;
            }
            List<Order> newList = new ArrayList<>();
            for (OrderNoUser noUser : list) {
                OrderUserRelation relation = relationDao.selectByOrderNo(noUser.getOrderNo(), noUser.getUserId());
                if (relation != null && Objects.equals(0, relation.getIsRoot())) {
                    Order order = orderDao.selectByOrderNo(noUser.getOrderNo(), noUser.getUserId());
                    newList.add(order);
                }
            }
            executeTransfer0(newList);
            count++;
            logger.info("delete_es order:{}", count);
            lastId = list.get(list.size() - 1).getId();
        }
    }

    private void executeTransfer0(List<Order> newList) {
        while (workQueue.remainingCapacity() < 20) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executorService.submit(() -> {
            try {
                if (!CollectionUtils.isEmpty(newList)) {
                    searchManager.indexOrder(newList);
                }
            } catch (Exception e) {
                logger.error("[executeTransfer]failed！cause by:{}", e);
            }
        });
    }

    private void executeTransfer(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 {
                searchManager.indexOrder(orderList);
            } catch (Exception e) {
                logger.error("[executeTransfer]failed！cause by:{}", e);
            }
        });
    }

    private OrderQuery getOrderQuery() {
        OrderQuery query = new OrderQuery();
        query.setSize(200);
        query.setSortFlag(1);
        query.setUpdatedAtEnd(new Date(1668441600000L));
        query.setUpdatedAtStart(new Date(1667232000000L));
        return query;
    }

    private static List<Integer> subtype = Lists.newArrayList(1, 2, 3);

    private List<Order> filterOrder(List<Order> orderList) {
        List<Order> newList = new ArrayList<>();
        for (Order order : orderList) {
            if (subtype.contains(order.getOrderSubType())) {
                OrderUserRelation relation = relationDao.selectRoot(order.getOrderNo());
                if (relation == null) {
                    newList.add(order);
                    continue;
                }
                if (Objects.equals(order.getUserId(), relation.getUserId())) {
                    newList.add(order);
                    continue;
                }
            } else {
                newList.add(order);
            }
        }
        return newList;
    }


    @Override
    public Result realDeleteOrderByOrderNo(BusinessOrderUpdateRequest request) {
        Result result = new Result();
        try {
            if (StringUtils.isEmpty(request.getOrderNo())) {
                return Result.failureData("订单号不能为空");
            }
            OrderIndex orderIndex = orderIndexDao.selectOne(request.getOrderNo());
            if (Objects.isNull(orderIndex)) {
                return Result.failureData("订单索引不存在");
            }
            Order order = orderDao.selectById(orderIndex.getOrderId(), orderIndex.getUserId());
            if (Objects.isNull(order)) {
                return Result.failureData("订单不存在");
            }
            //删订单
            orderDao.realDelete(orderIndex.getOrderId(), orderIndex.getUserId());
            //删商品
            List<OrderItem> itemList = orderItemDao.selectByOrderNo(request.getOrderNo(), orderIndex.getUserId());
            if (!CollectionUtils.isEmpty(itemList)) {
                List<Long> itemIdList = itemList.stream().map(OrderItem::getId).collect(Collectors.toList());
                orderItemDao.realDeletes(itemIdList, orderIndex.getUserId());
            }
            //删优惠
            discountDao.deleteTemp(request.getOrderNo(), orderIndex.getUserId());
            //删支付明细
            payDetailsDao.realDeleteByOrderNo(request.getOrderNo(), orderIndex.getUserId());
            //删退款
            refundDao.deleteTemp(request.getOrderNo(), orderIndex.getUserId());

            //删ES
            searchManager.deleteOrder(orderIndex.getOrderId(), order.getSellerId());

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


    @Override
    public Result updateOrderDiscountByOrderNo(BusinessOrderUpdateDiscountRequest request) {
        try {
            if (StringUtils.isEmpty(request.getOrderNo())) {
                return Result.failureData("订单号不能为空");
            }
            if (StringUtils.isEmpty(request.getDiscountId())) {
                return Result.failureData("订单优惠id不能为空");
            }
            OrderIndex orderIndex = orderIndexDao.selectOne(request.getOrderNo());
            if (Objects.isNull(orderIndex)) {
                return Result.failureData("订单索引不存在");
            }
            Order order = orderDao.selectById(orderIndex.getOrderId(), orderIndex.getUserId());

            //构建优惠更新参数
            OrderDiscount orderDiscount = buildUpdateOrderDiscountParams(orderIndex, request);
            discountDao.updateTwo(orderDiscount);

            //更新订单优惠快照
            String discountInfo = order.getDiscountInfo();
            if (!Objects.equals("DF", discountInfo)) {
                List<OrderDiscount> orderDiscountList = discountDao.selectByOrderNo(request.getOrderNo(), orderIndex.getUserId());

                List<InnerOrderDiscount> list = ConvertUtils.convertList(orderDiscountList, InnerOrderDiscount.class);
                if (!CollectionUtils.isEmpty(list)) {
                    order.setDiscountInfo(JSON.toJSONString(list));
                }
                orderDao.updateDiscountInfo(order);
            }
            //同步ES
            order = orderDao.selectById(orderIndex.getOrderId(), orderIndex.getUserId());
            searchManager.indexOrder(order, null);

        } catch (Throwable e) {
            logger.error("OrderWriteServiceImpl[updateOrderPayByOrderNo] failed!, cause by:{}", e);
            return Result.failureData(e);
        }
        return Result.successNullData();
    }

    @Override
    public void updateCommentCount(UpdateCommentCountRequest request) {
        try {
            Long sellerId = 214179L;
            ItemCommentQuery query = new ItemCommentQuery();
            query.setSellerId(sellerId);
            query.setCommentScoreList(Arrays.asList(1,2,3));
            List<OrderItemComment> list = itemCommentDao.selectCountFix(query);
            logger.info("OrderWriteServiceImpl[updateCommentCount] query:{}, list:{}", query, list);
            if (CollectionUtils.isEmpty(list)) {
                return;
            }
            Map<Long, List<OrderItemComment>> storeMap = list.stream().collect(Collectors.groupingBy(OrderItemComment::getStoreId));
            logger.info("OrderWriteServiceImpl[updateCommentCount] , storeMap:{}", storeMap);
            Iterator<Map.Entry<Long, List<OrderItemComment>>> it = storeMap.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<Long, List<OrderItemComment>> next = it.next();
                Long storeId = next.getKey();
                List<OrderItemComment> commentList = next.getValue();
                Map<Long, List<OrderItemComment>> goodsMap = commentList.stream().collect(Collectors.groupingBy(OrderItemComment::getGoodsId));
                logger.info("OrderWriteServiceImpl[updateCommentCount] , goodsMap:{}", goodsMap);
                Iterator<Map.Entry<Long, List<OrderItemComment>>> itGoods = goodsMap.entrySet().iterator();
                while (itGoods.hasNext()) {
                    Map.Entry<Long, List<OrderItemComment>> nextGoods = itGoods.next();
                    Long goodsId = nextGoods.getKey();
                    List<OrderItemComment> goodsList = nextGoods.getValue();
                    logger.info("OrderWriteServiceImpl[updateCommentCount] , goodsId:{}, goodsList:{}", goodsId, goodsList);

                    OrderItemCommentCountQuery countQuery = new OrderItemCommentCountQuery();
                    countQuery.setSellerId(sellerId);
                    countQuery.setGoodsId(goodsId);
                    countQuery.setStoreId(storeId);
                    OrderItemCommentCount orderItemCommentCount = itemCommentCountDao.selectOne(countQuery);
                    OrderItemCommentCount update = new OrderItemCommentCount();
                    update.setId(orderItemCommentCount.getId());
                    for (OrderItemComment  itemComment : goodsList) {
                        if (itemComment.getCommentScore().equals(1)) {
                            update.setScore1Count(itemComment.getTempCount());
                        }
                        if (itemComment.getCommentScore().equals(2)) {
                            update.setScore2Count(itemComment.getTempCount());
                        }
                        if (itemComment.getCommentScore().equals(3)) {
                            update.setScore3Count(itemComment.getTempCount());
                        }
                    }
                    logger.info("OrderWriteServiceImpl[updateCommentCount] , goodsId:{}, update:{}", goodsId, update);
                    itemCommentCountDao.update(update);
                }
            }


        } catch (Throwable e) {
            logger.error("DelEsExpireDataTask[updateCommentCount] failed!, cause by:{}", e);
        }
    }

    @Override
    public void updateItem() {
        try {
            int count = 0;
            for (String s : ListConst.list) {
                OrderIndex orderIndex = orderIndexDao.selectOne(s);
                if (orderIndex != null) {
                    List<OrderItem> items = orderItemDao.selectByOrderNo(orderIndex.getOrderNo(), orderIndex.getUserId());
                    if (!CollectionUtils.isEmpty(items)) {
                        for (OrderItem item : items) {
                            if (item.getGoodsId() == null  || item.getGoodsId() == 0L || StringUtils.isEmpty(item.getItemSign())) {
                                OrderItem update = new OrderItem();
                                update.setId(item.getId());
                                update.setUserId(item.getUserId());
                                if (item.getGoodsId() == null || item.getGoodsId() == 0L) {
                                    update.setGoodsId(1234L);
                                }
                                if (StringUtils.isEmpty(item.getItemSign())) {
                                    update.setItemSign("123");
                                }
                                orderItemDao.update(update);
                                count++;
                                logger.info("[handle_item]count:{}", count);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("[updateItem]cause by:{}", e);
        }
    }

    @Autowired
    private TempOrderDao tempOrderDao;

    private Date getEndAt() {
        Calendar calendar = Calendar.getInstance();
        if (LocalTime.now().isAfter(LocalTime.parse("22:30"))) {
            Date d = DateUtils.getStartDate(DateUtils.next(new Date(), Calendar.DAY_OF_YEAR, 1));
            calendar.setTime(d);
            calendar.add(Calendar.HOUR_OF_DAY, 6);
            return calendar.getTime();
        }
        if (LocalTime.now().isBefore(LocalTime.parse("07:00"))) {
            Date d = DateUtils.getStartDate(new Date());
            calendar.setTime(d);
            calendar.add(Calendar.HOUR_OF_DAY, 6);
            return calendar.getTime();
        }
        return null;
    }

    @Override
    public void customPay() {
        Date endAt = getEndAt();
        OrderQuery query = new OrderQuery();
        int count = 0;
        for (int i = 0; i < dbSize; i++) {
            for (int j = 0; j < tbSize; j++) {
                query.setDbIndex(i+1);
                query.setTbIndex(j);
                Long lastId = null;
                query.setSize(500);
                for (;;) {
                    query.setLastId(lastId);
                    List<TempOrder> tempOrderList = tempOrderDao.selectList(query);
                    if (CollectionUtils.isEmpty(tempOrderList)) {
                        break;
                    }
                    execute999(tempOrderList);

                    count += tempOrderList.size();
                    logger.info("Custom pay by baking, count:{}", count);
                    if (tempOrderList.size() < 500) {
                        break;
                    }
                    if (new Date().after(endAt)) {
                        logger.info("[time_end]shut down");
                        return;
                    }
                    lastId = tempOrderList.get(tempOrderList.size() - 1).getId();
                }
            }
        }
    }
    
    @Autowired
    private OrderRefundDetailsDao refundDetailsDao;

    @Override
    public void encryptOrder() {
        try {
            Date shutdown = getEndAt();
            
            if (shutdown != null) {
                logger.info("showdown time:{}", shutdown.getTime());
            }

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            // 历史数据截止到2023-12-31之前的都没刷
            // 从2024-01-01刷的
            String start = "2023-08-01";
            for (;;) {
                Calendar calendar = getCalendar0(start);
                start = sdf.format(calendar.getTime());

                for (int i = 0; i < dbSize; i++) {
                    for (int j = 0; j < tbSize; j++) {
                        execute996(DateUtils.getStartDate(calendar.getTime()), DateUtils.getEndDate(calendar.getTime()),
                            i, j);

                        logger.info("encryptOrder, start:{}, i:{}, j:{}", start, i, j);

                        Result<String> redisData = redisManager.get("encryptOrder_key_003");
                        if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                            logger.info("[encryptOrder]shut down！start:{}", start);
                            return;
                        }
                        if (new Date().after(shutdown)) {
                            logger.info("[time_end]shut down！start:{}", start);
                            return;
                        }
                    }
                }
                if (calendar.getTime().after(new Date(1704124800000L))) {
                    logger.info("[time_end]time the end！start:{}", start);
                    break;
                }
            }
            logger.info("[encryptOrder]execute end.");
        } catch (Exception e) {
            logger.error("[encryptOrder]failed！cause by:{}", e);
        }
    }

    @Override
    public void encryptRefund() {

    }

    private Calendar getCalendar0(String start) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = null;
        try {
            parse = sf.parse(start);
        } catch (ParseException ex) {
            ex.printStackTrace();
        }
        Calendar c = Calendar.getInstance();
        c.setTime(parse);
        c.add(Calendar.DAY_OF_MONTH, 1);
        return c;
    }

    @Override
    public void encryptOrderJolibee() {
        try {
            int count = 0;
            OrderQuery orderQuery = new OrderQuery();
            orderQuery.setSize(200);
            orderQuery.setSellerId(216966L);
            for (int i = 0; i < dbSize; i++) {
                for (int j = 0; j < tbSize; j++) {
                    Long lastId = null;
                    for (;;) {
                        orderQuery.setLastId(lastId);
                        List<Long> idList = commonManager.scanOrderId(orderQuery, i, j);
                        if (CollectionUtils.isEmpty(idList)) {
                            break;
                        }
                        List<Order> orderList = commonManager.listOrderById(idList, i, j);

                        executeJolibee(orderList, i, j);

                        if (idList.size() < 200) {
                            break;
                        }
                        Result<String> redisData = redisManager.get("encryptOrderJolibee_1");
                        if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                            logger.info("[encryptOrder]shut down！");
                            return;
                        }
                    }
                }
            }
            logger.info("[encryptOrder]execute end.");
        } catch (Exception e) {
            logger.error("[encryptOrder]failed！cause by:{}", e);
        }
    }

    private void executeJolibee(List<Order> orderList, 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 {
                List<Order> l = new ArrayList<>();
                for (Order order : orderList) {
                    if (Objects.equals(1, order.getMasterDataSource())) {
                        l.add(order);
                    }
                }
                newHintManager.updateEncryptbyId(l.stream().map(Order::getId).collect(Collectors.toList()), i, j);
            } catch (Exception e) {
                logger.error("[executeJolibee]failed！cause by:{}", e);
            }
        });
    }

    @Autowired
    private HintOrderDao hintOrderDao;

    @Autowired
    private NewHintManager newHintManager;

    private void execute996(Date start, Date end, 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 {
                long s = System.currentTimeMillis();
                commonManager.updateEncrypt(start, end, i, j);
                logger.info("Encrypt order time:{}", System.currentTimeMillis() - s);
            } catch (Exception e) {
                logger.error("[execute996]failed！cause by:{}", e);
            }
        });
    }

    @Override
    public void checkEncryptOrder() {
        try {
            Date shutdown = getEndAt();

            if (shutdown != null) {
                logger.info("check showdown time:{}", shutdown.getTime());
            }

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String start = "2020-01-01";
            for (;;) {
                Calendar calendar = getCalendar0(start);
                start = sdf.format(calendar.getTime());

                for (int i = 0; i < dbSize; i++) {
                    for (int j = 0; j < tbSize; j++) {
                        execute997(DateUtils.getStartDate(calendar.getTime()), DateUtils.getEndDate(calendar.getTime()),
                                i, j);

                        logger.info("checkEncryptOrder, start:{}, i:{}, j:{}", start, i, j);

                        Result<String> redisData = redisManager.get("checkEncryptOrder_key_001");
                        if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                            logger.info("[checkEncryptOrder]shut down！start:{}", start);
                            return;
                        }
                        if (new Date().after(shutdown)) {
                            logger.info("[check_time_end]shut down！start:{}", start);
                            return;
                        }
                    }
                }
                if (calendar.getTime().after(new Date(1730390400000L))) {
                    logger.info("[check_time_end]time the end！start:{}", start);
                    break;
                }
            }
            logger.info("[checkEncryptOrder]execute end.");
        } catch (Exception e) {
            logger.error("[checkEncryptOrder]failed！cause by:{}", e);
        }
    }

    private void execute997(Date start, Date end, 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 {
                long s = System.currentTimeMillis();
                OrderQuery query = new OrderQuery();
                query.setOrderAtStart(start);
                query.setOrderAtEnd(end);
                query.setPageNo(1);
                query.setPageSize(1);
                List<Order> orderList = commonManager.scanOrder(query, i, j);

                String decrypt = encryptService.decrypt(orderList.get(0).getFeaturesCipher());
                if (!StringUtils.isEmpty(orderList.get(0).getPerformanceInfoCipher())) {
                    String decrypt1 = encryptService.decrypt(orderList.get(0).getPerformanceInfoCipher());
                }

                logger.info("check encrypt order time:{}, data:{}, decrypt:{}, decrypt1:{}",
                        System.currentTimeMillis() - s,
                        JSON.toJSONString(orderList), decrypt, orderList.get(0).getPerformanceInfoCipher());
            } catch (Exception e) {
                logger.error("[checkEncryptOrder]failed！i:{}, j:{}, start:{}, cause by:{}", i , j, start, e);
            }
        });
    }

    private void execute999(List<TempOrder> list) {
        while (workQueue.remainingCapacity() < 20) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(400);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executorService.submit(() -> {
            try {
                list.forEach(each -> {
                    Order order = orderDao.selectRespStatus(each.getOrderNo(), each.getUserId());
                    if(order != null){
                        if (order.getPayType() == 8) {
                            List<OrderPayDetails> payDetails =
                                    orderPayDetailsDao.selectByOrderNo(each.getOrderNo(), each.getUserId());
                            if (!CollectionUtils.isEmpty(payDetails)) {
                                payDetails.forEach(e -> {
                                    if (e.getPayType() > 10002) {
                                        // pay_type > 10002 的数据修改成 标记支付
                                        orderPayDetailsDao.updatePayType(13, e.getUserId(), e.getId());
                                    }
                                });

                                List<OrderPayDetails> detailsList =
                                        orderPayDetailsDao.selectByOrderNo(each.getOrderNo(), each.getUserId());
                                Order update = new Order();
                                update.setId(order.getId());
                                update.setUserId(order.getUserId());
                                update.setPayDetailInfo(
                                        JSON.toJSONString(ConvertUtils.convertList(detailsList, InnerOrderPayDetails.class)));
                                orderDao.updatePayDetail(update);

                                List<Refund> refunds = refundDao.selectByOrderNo(each.getOrderNo());
                                if (!CollectionUtils.isEmpty(refunds)) {
                                    refunds.forEach(e -> {
                                        if (e.getPayType() > 10002) {
                                            e.setPayType(13);
                                            refundDao.updatePayType(e);
                                        }

                                        List<OrderRefundDetails> rdList =
                                                refundDetailsDao.selectByRefundNo(e.getRefundNo());
                                        if (!CollectionUtils.isEmpty(rdList)) {
                                            rdList.forEach(e1 -> {
                                                if (e1.getPayType() > 10002) {
                                                    e1.setPayType(13);
                                                    refundDetailsDao.updatePayType(e1);
                                                }
                                            });
                                        }

                                        List<OrderRefundDetails> rdList1 =
                                                refundDetailsDao.selectByRefundNo(e.getRefundNo());
                                        Refund u = new Refund();
                                        u.setId(e.getId());
                                        u.setRefundDetailInfo(
                                                JSON.toJSONString(ConvertUtils.convertList(rdList1, InnerRefundDetail.class)));
                                        refundDao.updateRefundDetail(u);
                                    });
                                }
                            }
                        }
                        if (order.getPayType() > 13) {
                            // 把orders/order_pay_details/退款单/退款明细表表 pay_type > 10002 的数据修改成 标记支付
                            List<OrderPayDetails> payDetails =
                                    orderPayDetailsDao.selectByOrderNo(each.getOrderNo(), each.getUserId());
                            if (!CollectionUtils.isEmpty(payDetails)) {
                                payDetails.forEach(e -> {
                                    if (e.getPayType() > 10002) {
                                        // pay_type > 10002 的数据修改成 标记支付
                                        orderPayDetailsDao.updatePayType(13, e.getUserId(), e.getId());
                                    }
                                });

                                List<OrderPayDetails> detailsList =
                                        orderPayDetailsDao.selectByOrderNo(each.getOrderNo(), each.getUserId());
                                Order update = new Order();
                                update.setId(order.getId());
                                update.setUserId(order.getUserId());
                                update.setPayType(13);
                                update.setPayDetailInfo(
                                        JSON.toJSONString(ConvertUtils.convertList(detailsList, InnerOrderPayDetails.class)));
                                orderDao.updatePayDetail(update);

                                try {
                                    searchManager.indexOrder(orderDao.selectByOrderNo(each.getOrderNo(), each.getUserId()));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                                List<Refund> refunds = refundDao.selectByOrderNo(each.getOrderNo());
                                if (!CollectionUtils.isEmpty(refunds)) {
                                    refunds.forEach(e -> {
                                        if (e.getPayType() > 10002) {
                                            e.setPayType(13);
                                            refundDao.updatePayType(e);
                                        }

                                        List<OrderRefundDetails> rdList =
                                                refundDetailsDao.selectByRefundNo(e.getRefundNo());
                                        if (!CollectionUtils.isEmpty(rdList)) {
                                            rdList.forEach(e1 -> {
                                                if (e1.getPayType() > 10002) {
                                                    e1.setPayType(13);
                                                    refundDetailsDao.updatePayType(e1);
                                                }
                                            });
                                        }

                                        List<OrderRefundDetails> rdList1 =
                                                refundDetailsDao.selectByRefundNo(e.getRefundNo());
                                        Refund u = new Refund();
                                        u.setId(e.getId());
                                        u.setRefundDetailInfo(
                                                JSON.toJSONString(ConvertUtils.convertList(rdList1, InnerRefundDetail.class)));
                                        refundDao.updateRefundDetail(u);
                                    });

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

    @Autowired
    private TemporaryServiceImpl temporaryService;

    private static List<Long> TestSellerIds = new ArrayList<>(10);
    static {
        TestSellerIds.add(213023L);
        TestSellerIds.add(203788L);
    }

    private int getHour () {
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY); // 24小时制
        return hour;
    }

    @Override
    public Result delTestOrder(DelTestOrderRequest request) {
        if (Objects.isNull(request.getSellerId())) {
            return Result.failureData("商家id不能为空");
        }
        if (Objects.isNull(request.getOrderAtStart())) {
            return Result.failureData("下单开始时间不能为空");
        }
        if (Objects.isNull(request.getOrderAtEnd())) {
            return Result.failureData("下单结束时间不能为空");
        }
        // 白名单验证
        if(!TestSellerIds.contains(request.getSellerId())){
            return Result.failureData("非指定测试品牌，请勿操作");
        }
        //执行时间验证 0点到6点
        if(getHour() > 6){
            return Result.failureData("当前时间不可执行，可执行时间（0点-6点）");
        }
        Result result = new Result<>();
        int count = 0;
        OrderQuery orderQuery = new OrderQuery();
        orderQuery.setSellerId(request.getSellerId());
        orderQuery.setSize(200);
        orderQuery.setOrderAtStart(request.getOrderAtStart());
        orderQuery.setOrderAtEnd(request.getOrderAtEnd());
        logger.info("delTestOrder[start], request:{}", request);
        try {
            for (int i = 0; i < dbSize; i++) {
                for (int j = 0; j < tbSize; j++) {
                    Long lastId = null;
                    for (;;) {
                        orderQuery.setLastId(lastId);
                        List<Long> idList = commonManager.scanOrderId(orderQuery, i, j);
                        if (CollectionUtils.isEmpty(idList)) {
                            break;
                        }
                        List<Order> orderList = commonManager.listOrderById(idList, i, j);
                        temporaryService.doExecDelTestOrder(orderList, i, j);
                        count += orderList.size();
                        logger.info("delTestOrder[running]:{}条, lastId:{}", count, lastId);
                        Thread.sleep(20);
                        if (orderList.size() < 200) {
                            break;
                        }
                        lastId = orderList.get(orderList.size() - 1).getId();
                        Result<String> redisData = redisManager.get("delete_order_key_02");
                        if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                            result.setStatus(true);
                            result.setData(lastId);
                            return result;
                        }
                    }
                }
            }
            logger.info("delTestOrder[end], request:{}, count:{}", request, count);
            result.setStatus(true);
        } catch (Exception e) {
            logger.error("[delTestOrder]failed!cause by:{}", e);
            result.setException(com.zm.order.tool.server.service.ExceptionConstants.SYSTEM_ERROR);
        }
        return result;
    }

    @Autowired
    private LineUpRecordDao lineUpRecordDao;
    @Autowired
    private LineUpRecordsCountDao countDao;

    @Override
    public Result fixLineUpCount(FixLineUpCountRequest request) {
        Result result = new Result();
        try {
            String orderNo = request.getOrderNo();
            Long sellerId = request.getSellerId();
            Long storeId = request.getStoreId();
            if (
                    Objects.isNull(orderNo)
                    &&
                    (Objects.isNull(sellerId) || Objects.isNull(storeId))
            ) {
                return Result.failureData("商家id和订单号不能都为空");
            }
            if(Objects.nonNull(orderNo)) {
                OrderIndex orderIndex = orderIndexDao.selectOne(orderNo);
                Order order = orderDao.selectByOrderNo(orderNo, orderIndex.getUserId());
                sellerId = order.getSellerId();
                storeId = order.getStoreId();
            }
            LineUpRecordQuery query = new LineUpRecordQuery();
            query.setSellerId(sellerId);
            query.setStoreId(storeId);
            query.setPayAtStart(DateUtils.getStartDate(new Date()));
            query.setPayAtEnd(DateUtils.getEndDate(new Date()));
            //总排队数量
            logger.info("fixLineUpCount,LineUpRecordQuery:{}", query);
            LineUpCount lineUpCount = lineUpRecordDao.countOrder(query);
            logger.info("fixLineUpCount,lineUpCount:{}", lineUpCount);
            LineUpRecordsCount count = countDao.selectOne(sellerId, storeId, DateUtils.getStartDateM(new Date()));
            logger.info("fixLineUpCount,count:{}", count);
            count.setQueueOrderCount(lineUpCount.getOrderNum());
            count.setQueueGoodsCount(lineUpCount.getGoodsNum());

            //结束排队数量
            query.setIsDeleted(1);
            LineUpCount lineUpCountOver = lineUpRecordDao.countOrder(query);
            count.setDequeueOrderCount(lineUpCountOver.getOrderNum());
            count.setDequeueGoodsCount(lineUpCountOver.getGoodsNum());

            logger.info("fixLineUpCount, request:{}, count:{}", request, count);
            countDao.update(count);
            return Result.successNullData();
        } catch (Throwable e) {
            logger.error("fixLineUpCount[fixLineUpCount] failed!, cause by:{}", e);
            return Result.failureData(e);
        }
    }




    @Override
    public Result updateNewOrderByOrderNo(BusinessOrderUpdateRequest request) {
        try {
            String orderNo = request.getOrderNo();
            if (StringUtils.isEmpty(orderNo)) {
                return Result.failureData("订单号不能为空");
            }
            OrderIndex orderIndex = orderIndexDao.selectOne(orderNo);

            if (Objects.isNull(orderIndex)) {
                return Result.failureData("订单索引不存在");
            }
            Order order = new Order();
            order.setId(orderIndex.getOrderId());
            order.setUserId(orderIndex.getUserId());
            newOrderDao.update(order);
            searchManager.indexOrder(newOrderDao.selectByOrderNo(orderIndex.getOrderNo(), orderIndex.getUserId()), ES_NEW_INDEX_TOPIC);
            newPayDetailsDao.updateUpdatedAt2(orderNo, orderIndex.getUserId());
        } catch (Throwable e) {
            logger.error("updateNewOrderByOrderNo[execute] failed!, cause by:{}", e);
            return Result.failureData(e);
        }
        return Result.successNullData();
    }


    @Override
    public Result updateNewOrderByOrderNoTemp() {
        try {
            int count = 0;
            for (String orderNo : ListConst21.list) {
                OrderIndex index = orderIndexDao.selectOne(orderNo);
                if (index != null) {
                    Order order = newOrderDao.selectByOrderNo(index.getOrderNo(), index.getUserId());
                    if (Objects.nonNull(order)) {
                        if (Objects.equals(1, order.getMasterDataSource())) {
                            // 更新主单
                            BusinessOrderUpdateRequest request = new BusinessOrderUpdateRequest();
                            request.setOrderNo(order.getOrderNo());
                            updateNewOrderByOrderNo(request);

                            // 更新子单
                            List<OrderUserRelation> relationList = relationDao.selectListByOrderNo(order.getOrderNo());
                            if (!CollectionUtils.isEmpty(relationList)) {
                                for (OrderUserRelation relation : relationList) {
                                    if (Objects.equals(1, relation.getIsRoot())) {
                                        Order order1 =
                                            newOrderDao.selectByOrderNo(relation.getOrderNo(), relation.getUserId());
                                        if (order1 != null) {
                                            newOrderDao.updateUpdated(order1.getId(), order1.getUserId());
                                        }
                                    }
                                }
                            }
                            count++;
                        }

                    }
                }
            }
            logger.info("updateNewOrderByOrderNoTemp count:{}", count);
        } catch (Throwable e) {
            logger.error("updateNewOrderByOrderNoTemp[execute] failed!, cause by:{}", e);
            return Result.failureData(e);
        }
        return Result.successNullData();
    }

}




















