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

import com.alibaba.fastjson.JSON;
import com.github.dozermapper.core.Mapper;
import com.zm.order.tool.server.component.ShardingKeyGenerator;
import com.zm.order.tool.server.constants.ListConst15;
import com.zm.order.tool.server.constants.ListConst16;
import com.zm.order.tool.server.constants.ListConst17;
import com.zm.order.tool.server.dao.*;
import com.zm.order.tool.server.dto.SearchOrderDTO;
import com.zm.order.tool.server.manager.*;
import com.zm.order.tool.server.message.BatchSyncEsMessage;
import com.zm.order.tool.server.model.*;
import com.zm.order.tool.server.query.*;
import com.zm.order.tool.server.request.OrderMergeRequest;
import com.zm.order.tool.server.request.OrderOperateRequest;
import com.zm.order.tool.server.service.ExceptionConstants;
import com.zm.order.tool.server.service.TempOrderService;
import com.zm.order.tool.server.tb.TbOrderDao;
import com.zm.order.tool.server.tempdb.*;
import com.zm.order.tool.server.utils.DateUtils;
import com.zm.util.dto.Result;
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.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author zhuxiaofeng
 * @date 2021/9/15 14:36
 */
@Component
public class TempOrderServiceImpl implements TempOrderService, InitializingBean {

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

    @Autowired
    private Mapper mapper;

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private InnerApiManager innerApiManager;

    @Autowired
    private OrderItemDao orderItemDao;

    @Autowired
    private RefundItemDao refundItemDao;

    @Autowired
    private OrderOperationDao operationDao;

    @Autowired
    private RedisManager redisManager;

    @Autowired
    private CommonManager commonManager;

    @Autowired
    private OrderPushLogsDao pushLogsDao;

    @Autowired
    private OrderDiscountDao discountDao;

    @Autowired
    private OrderPayDetailsDao payDao;

    @Autowired
    private OrderRefundDetailsDao detailsDao;

    @Autowired
    private JuiceOrderDao juiceOrderDao;

    @Autowired
    private OrderT97Dao t97Dao;

    @Autowired
    private BaoZhuDao baoZhuDao;

    @Autowired
    private OrderItemDao itemDao;

    @Autowired
    private OrderAddrDao addrDao;

    @Autowired
    private OrderIndexDao indexDao;

    @Autowired
    private SearchManager searchManager;

    @Autowired
    private AsyncMessageManager messageManager;

    @Autowired
    private OrderNoUserDao orderNoUserDao;

    @Autowired
    private ShardingKeyGenerator generator;

    private BigDecimal oneHundred = new BigDecimal(100);

    @Autowired
    private TbOrderDao tbOrderDao;

    @Autowired
    private IdOrderNoDao idOrderNoDao;

    @Autowired
    private RefundDao refundDao;

    @Autowired
    private OrderPayDetailsDao payDetailsDao;

    @Autowired
    private TempOrderOperationDao tempOrderOperationDao;
    @Autowired
    private ShardingKeyGenerator shardingKeyGenerator;

    @Override
    public void doHandle() {
        try {
            List<String> list = ListConst15.list;
            for (String orderNo : list) {
                OrderIndex orderIndex = indexDao.selectOne(orderNo);
                if (Objects.isNull(orderIndex)) {
                    continue;
                }
                Order order = orderDao.selectByOrderNo(orderIndex.getOrderNo(), orderIndex.getUserId());

                OrderAddr orderAddr = addrDao.selectByOrderNo(orderIndex.getOrderNo(), orderIndex.getUserId());
                orderAddr.setStreet(orderAddr.getStreet().replaceAll("\\r\\n|\\r|\\n", " "));
                orderAddr.setAcceptName(orderAddr.getAcceptName().replaceAll("\\r\\n|\\r|\\n", " "));
                orderAddr.setDoorNumber(orderAddr.getDoorNumber().replaceAll("\\r\\n|\\r|\\n", " "));
                addrDao.updateAddr(orderAddr);
                order.setAddrInfo(JSON.toJSONString(orderAddr));
                orderDao.updateAddrInfo(order);
                searchManager.indexOrder(order, null);
            }
        } catch (Throwable e) {
            logger.error("TempOrderServiceImplSync[syncEnd] failed!, cause by:{}", e);
        }
    }

    @Override
    public Result syncEs() {
        Result result = new Result();
        try {
            OrderQuery orderQuery = new OrderQuery();
            Long lastId = 0L;
            int count = 0;
            for (; ; ) {
                List<OrderNoUser> orderNoUserList = orderNoUserDao.selectList(lastId);
                if (CollectionUtils.isEmpty(orderNoUserList)) {
                    break;
                }
                lastId = orderNoUserList.get(orderNoUserList.size() - 1).getId();
                count += orderNoUserList.size();

                List<Long> userIdList = orderNoUserList.stream().map(OrderNoUser::getUserId).
                        collect(Collectors.toList());
                List<Long> orderIdList = orderNoUserList.stream().map(OrderNoUser::getOrderId).
                        collect(Collectors.toList());
                orderQuery.setUserIdList(userIdList);
                orderQuery.setIdList(orderIdList);
                List<Order> orderList = orderDao.selectListByOrderNosUserIds(orderQuery);
                if (CollectionUtils.isEmpty(orderList)) {
                    continue;
                }
                searchManager.indexOrder(orderList);
                logger.info("TempOrderServiceImplSync:count：{}, lastId:{}", count, lastId);
                if (orderNoUserList.size() < 200) {
                    break;
                }
            }
            logger.info("TempOrderServiceImplSync:syncEnd:累计扫描：{}", count);
            result.setStatus(true);
        } catch (Throwable e) {
            result.setException(ExceptionConstants.SYSTEM_ERROR);
            logger.error("TempOrderServiceImplSync[syncEnd] failed!, cause by:{}", e);
        }
        return result;
    }


    @Value("${order.cancel.notice.catering.tag}")
    private String orderCancelTag;

    @Value("${order.complete.notice.catering.tag}")
    private String orderCompleteTag;

    @Override
    public Result pushMsg() {
        Result result = new Result();
        try {
            OrderQuery orderQuery = new OrderQuery();
            Long lastId = 0L;
            int count = 0;
            int cancelCount = 0;
            int completeCount = 0;
            for (; ; ) {
                List<OrderNoUser> orderNoUserList = orderNoUserDao.selectList(lastId);
                logger.info("pushMsg:orderNoUserListCount：{}, lastId:{}", orderNoUserList.size(), lastId);
                if (CollectionUtils.isEmpty(orderNoUserList)) {
                    break;
                }
                lastId = orderNoUserList.get(orderNoUserList.size() - 1).getId();
                count += orderNoUserList.size();

                List<Long> userIdList = orderNoUserList.stream().map(OrderNoUser::getUserId).
                        collect(Collectors.toList());
                List<Long> orderIdList = orderNoUserList.stream().map(OrderNoUser::getOrderId).
                        collect(Collectors.toList());
                orderQuery.setUserIdList(userIdList);
                orderQuery.setIdList(orderIdList);
                List<Order> orderList = orderDao.selectListByOrderNosUserIds(orderQuery);
                if (CollectionUtils.isEmpty(orderList)) {
                    continue;
                }
                for (Order order : orderList) {
                    Map<String, Object> extraMap = order.getExtraMap();
                    // 取消消息
                    if (Objects.equals(10, order.getStatus())) {
                        //autoCancelAt 小于当前时间
                        if (Objects.nonNull(extraMap.get("autoCancelAt"))) {
                            String autoCancelAt = extraMap.get("autoCancelAt").toString();
                            Long cancelAt = Long.valueOf(autoCancelAt);
                            long nowTime = System.currentTimeMillis();
                            if (nowTime > cancelAt) {
                                cancelCount++;
                                messageManager.sendOrderCancelNoticeMessage(order, orderCancelTag);
                                logger.info("pushMsg[cancel]:orderNo:{},cancelCount:{}", order.getOrderNo(), cancelCount);
                            }
                        }
                    }
                    // 完成消息
                    if (Objects.equals(20, order.getStatus()) || Objects.equals(30, order.getStatus()) || Objects.equals(40, order.getStatus())) {
                        if (Objects.equals(1, order.getPayStatus())) {
                            // autoCompleteAt 小于当前时间
                            if (Objects.nonNull(extraMap.get("autoCompleteAt"))) {
                                String autoCompleteAt = extraMap.get("autoCompleteAt").toString();
                                Long completeAt = Long.valueOf(autoCompleteAt);
                                long nowTime = System.currentTimeMillis();
                                if (nowTime > completeAt) {
                                    completeCount++;
                                    messageManager.sendOrderCompleteNoticeMessage(order, orderCompleteTag);
                                    logger.info("pushMsg[complete]:orderNo:{},cancelCount:{}", order.getOrderNo(), completeCount);
                                }
                            }
                        }
                    }
                }

                logger.info("TempOrderServiceImplSync[pushMsg]:count：{}, lastId:{}", count, lastId);
                if (orderNoUserList.size() < 200) {
                    break;
                }
            }
            logger.info("TempOrderServiceImplSync:syncEnd:累计扫描：{}", count);
            result.setStatus(true);
        } catch (Throwable e) {
            result.setException(ExceptionConstants.SYSTEM_ERROR);
            logger.error("TempOrderServiceImplSync[syncEnd] failed!, cause by:{}", e);
        }
        return result;
    }


    @Value("${order.cancel.notice.baking.tag}")
    private String orderCancelTagBaking;

    @Override
    public Result pushMsgBaking() {
        Result result = new Result();
        try {
            OrderQuery orderQuery = new OrderQuery();
            Long lastId = 0L;
            int count = 0;
            int cancelCount = 0;
            int completeCount = 0;
            for (; ; ) {
                List<OrderNoUser> orderNoUserList = orderNoUserDao.selectList(lastId);
                logger.info("pushMsgBaking:orderNoUserListCount：{}, lastId:{}", orderNoUserList.size(), lastId);
                if (CollectionUtils.isEmpty(orderNoUserList)) {
                    break;
                }
                lastId = orderNoUserList.get(orderNoUserList.size() - 1).getId();
                count += orderNoUserList.size();

                List<Long> userIdList = orderNoUserList.stream().map(OrderNoUser::getUserId).
                        collect(Collectors.toList());
                List<Long> orderIdList = orderNoUserList.stream().map(OrderNoUser::getOrderId).
                        collect(Collectors.toList());
                orderQuery.setUserIdList(userIdList);
                orderQuery.setIdList(orderIdList);
                List<Order> orderList = orderDao.selectListByOrderNosUserIds(orderQuery);
                if (CollectionUtils.isEmpty(orderList)) {
                    continue;
                }
                for (Order order : orderList) {
                    // 取消消息
                    messageManager.sendOrderCancelNoticeMessage(order, orderCancelTagBaking);
                    logger.info("pushMsgBaking[cancel]:orderNo:{},cancelCount:{}", order.getOrderNo(), cancelCount);
                }
                logger.info("TempOrderServiceImplSync[pushMsgBaking]:count：{}, lastId:{}", count, lastId);
                if (orderNoUserList.size() < 200) {
                    break;
                }
            }
            logger.info("TempOrderServiceImplSync:syncEnd:累计扫描：{}", count);
            result.setStatus(true);
        } catch (Throwable e) {
            result.setException(ExceptionConstants.SYSTEM_ERROR);
            logger.error("TempOrderServiceImplSync[syncEnd] failed!, cause by:{}", e);
        }
        return result;
    }

    @Override
    public Result update() {
        Result result = new Result();
        try {
            OrderQuery orderQuery = new OrderQuery();
            Long lastId = 0L;
            int count = 0;
            for (; ; ) {
                List<OrderNoUser> orderNoUserList = orderNoUserDao.selectList(lastId);
                if (CollectionUtils.isEmpty(orderNoUserList)) {
                    break;
                }
                lastId = orderNoUserList.get(orderNoUserList.size() - 1).getId();
                count += orderNoUserList.size();

                List<Long> userIdList = orderNoUserList.stream().map(OrderNoUser::getUserId).
                        collect(Collectors.toList());
                List<Long> orderIdList = orderNoUserList.stream().map(OrderNoUser::getOrderId).
                        collect(Collectors.toList());
                orderQuery.setUserIdList(userIdList);
                orderQuery.setIdList(orderIdList);
                List<Order> orderList = orderDao.selectListByOrderNosUserIds(orderQuery);
                if (CollectionUtils.isEmpty(orderList)) {
                    continue;
                }
                for (Order order : orderList) {
                    order.setStatus(8);
                }
                orderDao.updateByIdsUserIds(orderQuery);
                searchManager.indexOrder(orderList);
                logger.info("TempOrderServiceImplUpdate:count：{}, lastId:{}", count, lastId);
                if (orderNoUserList.size() < 200) {
                    break;
                }
            }
            logger.info("TempOrderServiceImplUpdate:end:累计扫描：{}", count);
            result.setStatus(true);
        } catch (Throwable e) {
            result.setException(ExceptionConstants.SYSTEM_ERROR);
            logger.error("TempOrderServiceImplSync[update] failed!, cause by:{}", e);
        }
        return result;
    }

    @Override
    public void afterPropertiesSet() throws Exception {

    }


    @Override
    public Result delete() {
        Result result = new Result();
        try {
            OrderQuery orderQuery = new OrderQuery();
            Long lastId = 0L;
            int count = 0;
            for (; ; ) {
                List<OrderNoUser> orderNoUserList = orderNoUserDao.selectList(lastId);
                if (CollectionUtils.isEmpty(orderNoUserList)) {
                    break;
                }
                lastId = orderNoUserList.get(orderNoUserList.size() - 1).getId();
                count += orderNoUserList.size();

                List<Long> userIdList = orderNoUserList.stream().map(OrderNoUser::getUserId).
                        collect(Collectors.toList());
                List<Long> orderIdList = orderNoUserList.stream().map(OrderNoUser::getOrderId).
                        collect(Collectors.toList());
                orderQuery.setUserIdList(userIdList);
                orderQuery.setIdList(orderIdList);
                List<Order> orderList = orderDao.selectListByOrderNosUserIds(orderQuery);
                if (CollectionUtils.isEmpty(orderList)) {
                    continue;
                }

                for (Order order : orderList) {
                    if (order != null) {
                        order.setIsDeleted(-1);
                        orderDao.updateDeleted(order);
                        try {
                            searchManager.indexOrder(order, null);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                logger.info("TempOrderServiceImplDelete:count：{}, lastId:{}", count, lastId);
                if (orderNoUserList.size() < 200) {
                    break;
                }
            }
            logger.info("TempOrderServiceImplDelete:end:累计扫描：{}", count);
            result.setStatus(true);
        } catch (Throwable e) {
            result.setException(ExceptionConstants.SYSTEM_ERROR);
            logger.error("TempOrderServiceImplSync[update] failed!, cause by:{}", e);
        }
        return result;
    }

    @Override
    public void delJuiceOrder() {
        try {
            Long lastId = null;
            int size = 200;
            int count = 0;
            int orderCount = 0;
            for (; ; ) {
                List<JuiceOrder> list = juiceOrderDao.selectList(lastId, size);
                if (CollectionUtils.isEmpty(list)) {
                    break;
                }
                List<String> orderNoList = list.stream().map(JuiceOrder::getOrderNo).collect(Collectors.toList());
                List<Long> userIdList = list.stream().map(JuiceOrder::getUserId).collect(Collectors.toList());
                OrderQuery query = new OrderQuery();
                query.setUserIdList(userIdList);
                query.setOrderNoList(orderNoList);
                List<Order> orderList = orderDao.selectListByOrderNosUserIds(query);
                if (!CollectionUtils.isEmpty(orderList)) {
                    for (Order order : orderList) {
                        searchManager.deleteOrder(order.getId(), order.getSellerId());
                    }
                }
                orderDao.deleteByOrderNos(orderNoList, userIdList);
                orderItemDao.deleteByOrderNos(orderNoList, userIdList);
                payDetailsDao.deleteByOrderNos(orderNoList, userIdList);
                indexDao.realDeleteByOrderNoUserId(orderNoList, userIdList);
                lastId = list.get(list.size() - 1).getId();
                count = count + list.size();
                logger.info("juiceOrder,count:{},lastId:{}, orderCount:{}", count, lastId, orderCount);
                if (list.size() < size) {
                    break;
                }
            }
        } catch (Throwable e) {
            logger.error("TempOrderServiceImplSync[update] failed!, cause by:{}", e);
        }
    }

    /**
     * pro
     */
    private Long sellerId = 213553L;
//    /**
//     * beta
//     */
//    private Long sellerId = 11337L;

    @Override
    public void juiceOrder() {
        try {

            Long lastId = null;
            int size = 200;
            int count = 0;
            int orderCount = 0;
            for (; ; ) {
                List<JuiceOrder> list = juiceOrderDao.selectList(lastId, size);
                if (CollectionUtils.isEmpty(list)) {
                    break;
                }
                List<Order> orderList = new ArrayList<>(size);
                List<OrderItem> itemList = new ArrayList<>(size);
                List<OrderPayDetails> payList = new ArrayList<>(size);

                List<String> orderNoList = list.stream().map(JuiceOrder::getOrderNo).collect(Collectors.toList());
                List<Long> userIdList = list.stream().map(JuiceOrder::getUserId).collect(Collectors.toList());
                orderNoList.removeAll(Collections.singleton(null));
                userIdList.removeAll(Collections.singleton(null));
                OrderQuery query = new OrderQuery();
                if (CollectionUtils.isEmpty(userIdList)) {
                    continue;
                }
                query.setOrderNoList(orderNoList);
                query.setUserIdList(userIdList);
                // 订单可能已存在
                List<Order> orderExistList = orderDao.selectListByOrderNosUserIds(query);
                //数据库已有的订单号列表
                List<String> orderNoExistList = orderExistList.stream().map(Order::getOrderNo).collect(Collectors.toList());
                Map<String, Order> orderNoMap = orderExistList.stream().collect(Collectors.toMap(Order::getOrderNo, Function.identity()));
                Map<String, Order> orderNoInsertMap = new HashMap<>(size);
                for (JuiceOrder item : list) {
                    // 用户id 不存在 或者 订单号不存在 ： 不迁移
                    if (Objects.isNull(item.getUserId()) || Objects.isNull(item.getOrderNo())) {
                        continue;
                    }
                    //订单已存在数据库：更新商品快照，加商品
                    if (Objects.nonNull(orderNoMap.get(item.getOrderNo()))) {
                        // insert商品，更新订单商品快照
                        buildItem(itemList, item, orderNoMap);
                        logger.info("juiceOrder[orderExist],count:{},lastId:{},orderNo:{}", count, lastId, item.getOrderNo());
                    } else {
                        OrderItem orderItem = buildItem(itemList, item);
                        // 前面构建过订单，更新itemInfo
                        if (Objects.nonNull(orderNoInsertMap.get(item.getOrderNo()))) {
                            Order order = orderNoInsertMap.get(item.getOrderNo());
                            if (!Objects.equals(ITEM_FLAG, order.getItemInfo())) {
                                List<InnerOrderItem> innerOrderItems = JSON.parseArray(order.getItemInfo(), InnerOrderItem.class);
                                InnerOrderItem inner = mapper.map(orderItem, InnerOrderItem.class);
                                innerOrderItems.add(inner);
                                if (innerOrderItems.size() > MAX_ITEM_SIZE) {
                                    order.setItemInfo(ITEM_FLAG);
                                } else {
                                    order.setItemInfo(JSON.toJSONString(innerOrderItems));
                                }
                            }
                            logger.info("juiceOrder[reBuildOrderItemInfo],count:{},lastId:{},orderNo:{}, orderItem:{}", count, lastId, item.getOrderNo(), orderItem);
                        } else {
                            //不存在新建
                            Order order = buildOrder(orderList, item);
                            InnerOrderItem innerOrderItem = mapper.map(orderItem, InnerOrderItem.class);
                            order.setItemInfo(JSON.toJSONString(Arrays.asList(innerOrderItem)));
                            buildPayDetail(payList, item, order);
                            orderNoInsertMap.put(item.getOrderNo(), order);
                            logger.info("juiceOrder[createNew],count:{},lastId:{},orderNo:{}, orderItem:{}", count, lastId, item.getOrderNo(), orderItem);
                        }
                    }
                }
                List<BatchSyncEsMessage> messageList = new ArrayList<>(size);

                //循环更新已存在订单
                if (!CollectionUtils.isEmpty(orderNoMap)) {
                    for (Order order : orderNoMap.values()) {
                        orderDao.updateItemAndDiscount(order);
                        messageList.add(buildMessage(order));
                    }
                }
                List<OrderIndex> indexList = new ArrayList<>(size);

                //批量新增订单
                if (!CollectionUtils.isEmpty(orderNoInsertMap)) {
                    for (Order order : orderNoInsertMap.values()) {
                        orderList.add(order);
                        messageList.add(buildMessage(order));
                        OrderIndex index = new OrderIndex();
                        index.setOrderNo(order.getOrderNo());
                        index.setOrderId(order.getId());
                        index.setUserId(order.getUserId());
                        index.setBizType(order.getBizType());
                        index.setId(generator.generateSnowflakeNumKey());
                        indexList.add(index);
                    }
                    orderDao.insertList(orderList);
                    orderCount += orderList.size();
                }
                // 新增订单索引
                if (!CollectionUtils.isEmpty(indexList)) {
                    indexDao.insertList(indexList);
                }
                //批量新增商品
                if (!CollectionUtils.isEmpty(itemList)) {
                    orderItemDao.inserts(itemList);
                }
                //批量新增支付明细
                if (!CollectionUtils.isEmpty(payList)) {
                    payDao.insertList(payList);
                }
                //同步ES
                List<BatchSyncEsMessage> pushList = new ArrayList<>(size);
                buildPushMessage(messageList, pushList);
                messageManager.sendBatchSyncMessage(pushList);

                lastId = list.get(list.size() - 1).getId();
                count = count + list.size();
                logger.info("juiceOrder,count:{},lastId:{}, orderCount:{}", count, lastId, orderCount);
                if (list.size() < size) {
                    break;
                }
            }
        } catch (Throwable e) {
            logger.error("juiceOrder[execute] failed!, cause by:{}", e);
        }
    }

    private void buildPushMessage(List<BatchSyncEsMessage> messageList, List<BatchSyncEsMessage> pushList) {
        if (!CollectionUtils.isEmpty(messageList)) {
            for (BatchSyncEsMessage message : messageList) {
                pushList.add(message);
            }
        }
    }

    /**
     * 限定数量
     */
    public static final Integer MAX_ITEM_SIZE = 10;

    /**
     * 商品上限标记
     */
    public static final String ITEM_FLAG = "TL";

    public Order buildOrder(List<Order> orderList, JuiceOrder juiceOrder) {
        Order order = new Order();
        order.setId(generator.generateSnowflakeNumKey());
        order.setOrderNo(juiceOrder.getOrderNo());
        order.setUserId(juiceOrder.getUserId());
        order.setTotalAmount(Double.valueOf(juiceOrder.getTotalAmount().multiply(oneHundred).toString()).intValue());

        order.setBizSubType(0);
        order.setDiscountAmount(0);
        order.setPackAmount(0);
        order.setFreightAmount(0);
        order.setChangeAmount(0);
        order.setPayModel(0);
        order.setIsAlone(0);
        order.setPayStatus(1);
        order.setInvoiceType(0);
        order.setAfterSaleStatus(0);
        order.setReceiveStatus(0);
        order.setPerformanceStatus(0);
        order.setCommentStatus(0);
        order.setPerformanceType(0);
        order.setIsReceipt(0);
        order.setIsImmediatePerformance(0);
        order.setSourceNo("");
        order.setBizType(5);
        order.setOrderType(1);
        order.setFromSystem(0);
        order.setOrderSubType(0);
        order.setSource(1);
        order.setStatus(50);
        order.setPayType(1);
        //用户端删除
        order.setIsDeleted(1);
        order.setAddrId(0);
        order.setSyncFlag(0);
        order.setVersion(1);
        order.setPayFlag(1);
        order.setPayer(juiceOrder.getUserId());
        order.setActualAmount(order.getTotalAmount());
        order.setPayAmount(order.getTotalAmount());
        order.setItemAmount(order.getTotalAmount());
        if (Objects.nonNull(juiceOrder.getPayNo())) {
            order.setPayNo(juiceOrder.getPayNo());
            order.setThirdPayNo(juiceOrder.getPayNo());
        }
        if (Objects.nonNull(juiceOrder.getSellerRemark())) {
            order.setSellerRemarks(juiceOrder.getSellerRemark());
        }
        if (Objects.nonNull(juiceOrder.getMobile())) {
            order.setMobile(juiceOrder.getMobile());
        }
        order.setSellerId(sellerId);
        if (Objects.nonNull(juiceOrder.getStoreId())) {
            order.setStoreId(juiceOrder.getStoreId());
        }

        order.setOrderAt(juiceOrder.getOrderAt());
        order.setCreatedAt(juiceOrder.getOrderAt());
        order.setPayAt(juiceOrder.getOrderAt());
        order.setCompletedAt(juiceOrder.getOrderAt());
        order.setUpdatedAt(new Date());
        Map<String, Object> map = new HashMap();
        map.put("historyOrder", 1);
        if (!StringUtils.isEmpty(juiceOrder.getBillNo())) {
            map.put("billNo", juiceOrder.getBillNo());
        }
        order.setExtraMap(map);
        return order;
    }

    private void buildItem(List<OrderItem> itemList, JuiceOrder juiceOrder, Map<String, Order> orderNoMap) {
        OrderItem orderItem = buildItemValue(itemList, juiceOrder);
        Order order = orderNoMap.get(juiceOrder.getOrderNo());
        if (Objects.nonNull(order)) {
            String itemInfo = order.getItemInfo();
            if (!Objects.equals(ITEM_FLAG, itemInfo)) {
                List<InnerOrderItem> innerOrderItems = JSON.parseArray(itemInfo, InnerOrderItem.class);
                InnerOrderItem inner = mapper.map(orderItem, InnerOrderItem.class);
                innerOrderItems.add(inner);
                if (innerOrderItems.size() > MAX_ITEM_SIZE) {
                    order.setItemInfo(ITEM_FLAG);
                } else {
                    order.setItemInfo(JSON.toJSONString(innerOrderItems));
                }
            }
        }
        orderNoMap.put(juiceOrder.getOrderNo(), order);
    }

    private OrderItem buildItem(List<OrderItem> itemList, JuiceOrder juiceOrder) {
        OrderItem orderItem = buildItemValue(itemList, juiceOrder);
        return orderItem;
    }

    private OrderItem buildItemValue(List<OrderItem> itemList, JuiceOrder juiceOrder) {
        OrderItem item = new OrderItem();
        item.setId(generator.generateSnowflakeNumKey());
        item.setBizType(5);
        item.setUserId(juiceOrder.getUserId());
        item.setOrderNo(juiceOrder.getOrderNo());
        item.setItemId("-1");
        if (StringUtils.isEmpty(juiceOrder.getItemName())) {
            item.setItemName("历史消费商品");
        } else {
            item.setItemName(juiceOrder.getItemName());
        }
        if (Objects.nonNull(juiceOrder.getItemNum())) {
            item.setNum(juiceOrder.getItemNum());
        } else {
            item.setNum(new BigDecimal(1));
        }
        if (Objects.nonNull(juiceOrder.getPrice())) {
            BigDecimal multiply = juiceOrder.getPrice().multiply(new BigDecimal(100));
            item.setItemPrice(Double.valueOf(multiply.toString()).intValue());
        } else {
            item.setItemPrice(0);
        }
        item.setItemImage("https://images.qmai.cn/s11337/2022/06/06/bac99f84415e453e6e.png");
        item.setItemSpec(null);
        item.setItemUnit("");
        item.setBrandSign("");
        item.setMarketPrice(0);
        item.setCostPrice(0);
        item.setMemberPrice(0);
        item.setDiscountAmount(0);
        item.setPackAmount(0);
        item.setfCode("");
        item.setStatus(0);
        item.setFeatures(null);
        item.setGoodsId(0L);
        item.setActivityId(0L);
        item.setIsTimeDiscount(0);
        item.setOrderAt(juiceOrder.getOrderAt());
        item.setProductNo("");
        item.setIsGift(0);
        item.setSellerId(sellerId);
        item.setItemType(0);
        item.setOwnerId(0L);
        item.setBatchingInfo("");
        itemList.add(item);
        return item;
    }


//    private void buildDiscount(List<OrderDiscount> list, JuiceOrder juiceOrder, Order order) {
//        Integer discountAmount = Integer.valueOf(juiceOrder.getDiscountAmount().multiply(oneHundred).toString());
//        if (discountAmount <= 0) {
//            return;
//        }
//        OrderDiscount discount = new OrderDiscount();
//        discount.setId(generator.generateSnowflakeNumKey());
//        discount.setBizType(5);
//        discount.setUserId(juiceOrder.getUserId());
//        discount.setOrderNo(juiceOrder.getOrderNo());
//        discount.setItemId("-1");
//        discount.setDiscountLevel(0);
//        discount.setDiscountId("-1");
//        discount.setDiscountType(2);
//        discount.setDiscountName("");
//        discount.setDiscountSummary("");
//        discount.setDiscountAmount(discountAmount);
//        discount.setFeatures("");
//        list.add(discount);
//        order.setDiscountInfo(JSON.toJSONString(list));
//    }

    private void buildPayDetail(List<OrderPayDetails> list, JuiceOrder juiceOrder, Order order) {
        Integer payAmount = Double.valueOf(juiceOrder.getTotalAmount().multiply(oneHundred).toString()).intValue();
        if (payAmount <= 0) {
            return;
        }
        OrderPayDetails payDetails = new OrderPayDetails();
        payDetails.setId(generator.generateSnowflakeNumKey());
        payDetails.setOrderNo(juiceOrder.getOrderNo());
        payDetails.setUserId(juiceOrder.getUserId());
        payDetails.setAmount(payAmount);
        payDetails.setPayType(1);
        payDetails.setStoreId(juiceOrder.getStoreId());
        payDetails.setSellerId(sellerId);
        payDetails.setOrderAt(juiceOrder.getOrderAt());
        payDetails.setPayAt(juiceOrder.getOrderAt());
        payDetails.setOrderType(1);
        payDetails.setSource(1);
        payDetails.setPayNo(juiceOrder.getPayNo());
        payDetails.setThirdPayNo("");
        list.add(payDetails);
        String payDetailInfo = JSON.toJSONString(Arrays.asList(mapper.map(payDetails, InnerOrderPayDetails.class)));
        order.setPayDetailInfo(payDetailInfo);
    }

//    private void buildRefund(List<Refund> list, JuiceOrder juiceOrder) {
//        Refund refund = new Refund();
//        refund.setId(generator.generateSnowflakeNumKey());
//        refund.setOrderNo(juiceOrder.getOrderNo());
//        refund.setSellerId(juiceOrder.getSellerId());
//        refund.setStoreId(juiceOrder.getStoreId());
//        refund.setUserId(juiceOrder.getUserId());
//        refund.setBizType(5);
//        refund.setCreatedAt(juiceOrder.getCreatedAt());
//        refund.setApplyAt(juiceOrder.getCreatedAt());
//        refund.setDealAt(juiceOrder.getCreatedAt());
//        refund.setPayType(1);
//        refund.setMobile(juiceOrder.getMobile());
//        refund.setUpdatedAt(new Date());
//        refund.setSource(1);
//        refund.setOrderType(1);
//        refund.setAmount(0);
//        refund.setRefundNo("");
//        refund.setStatus(1);
//    }

    public final int size = 500;

    public void buildSyncTemp(OrderQuery query) {
        query.setSize(size);
//        Long maxId = 742517635719147522L;
//        query.setMaxId(maxId);
    }


    @Override
    public Result syncTemp1() {
        Result result = new Result();
        try {
            OrderQuery query = new OrderQuery();
            //2022-09-28 22:09:23
            query.setOrderAtStart(new Date(1609430400000L));
            //2022-09-29 10:13:26
            query.setOrderAtEnd(new Date(1641225600000L));
            query.setSellerId(204178L);
            buildSyncTemp(query);
            doSyncTemp(query, 1);
            result.setStatus(true);
        } catch (Throwable e) {
            logger.error("syncSplByTime[syncTemp1] failed!, cause by:{}", e);
            result.setException(ExceptionConstants.SYSTEM_ERROR);
        }
        return result;
    }


    public void doSyncTemp(OrderQuery query, int i) {
        final int size = 500;
        int count = 0;
        Long lastId = null;
//        query.setBizType(5);
        query.setOrderById(1);
        for (; ; ) {
            query.setLastId(lastId);
            List<Order> orderList = tbOrderDao.selectList(query);
            if (CollectionUtils.isEmpty(orderList)) {
                logger.info("syncSplByTime[syncSplByTime]-break-empty-{} count:{}, lastId:{}, query:{}", i, count, lastId, query);
                break;
            }
            List<OrderNoUser> list = new ArrayList<>(orderList.size());
            for (Order order : orderList) {
                OrderNoUser orderNoUser = new OrderNoUser();
                orderNoUser.setOrderNo(order.getOrderNo());
                orderNoUser.setOrderId(order.getId());
                orderNoUser.setUserId(order.getUserId());
                list.add(orderNoUser);
            }
            lastId = orderList.get(orderList.size() - 1).getId();
            if (!CollectionUtils.isEmpty(list)) {
                //批量插入
                orderNoUserDao.insertList(list);
            }
            count += orderList.size();
            logger.info("syncSplByTime[syncSplByTime]-{} count:{}, lastId:{}", i, count, lastId);
            if (orderList.size() < size) {
                logger.info("syncSplByTime[syncSplByTime]-break-less-{} count:{}, lastId:{}, query:{}", i, count, lastId, query);
                break;
            }
        }
        logger.info("syncSplByTime[syncSplByTime][end]-{} count:{}, lastId:{}", i, count, lastId);
    }


    @Override
    public Result tempSyncEs() {
        Result result = new Result();
        try {
            Long lastId = null;
            int count = 0;
            for (; ; ) {
                List<BatchSyncEsMessage> messageList = new ArrayList<>(500);
                List<OrderNoUser> orderNoUserList = orderNoUserDao.selectList(lastId);
                if (CollectionUtils.isEmpty(orderNoUserList)) {
                    break;
                }
                List<Long> idList = orderNoUserList.stream().map(OrderNoUser::getOrderId).collect(Collectors.toList());
                List<Long> userIdList = orderNoUserList.stream().map(OrderNoUser::getUserId).collect(Collectors.toList());
                OrderQuery query = new OrderQuery();
                query.setIdList(idList);
                query.setUserIdList(userIdList);
                List<Order> orderList = orderDao.selectListByOrderNosUserIds(query);
                for (Order order : orderList) {
                    messageList.add(buildMessage(order));
                }
                count += orderList.size();
                messageManager.sendBatchSyncMessage(messageList);
                lastId = orderNoUserList.get(orderNoUserList.size() - 1).getId();
                logger.info("tempSyncEs[running]-count:{},lastId:{}", count, lastId);
                if (orderNoUserList.size() < 500) {
                    break;
                }
            }
            logger.info("tempSyncEs[end]-count:{},lastId:{}", count, lastId);
            result.setStatus(true);
        } catch (Throwable e) {
            logger.error("tempSyncEs[execute] failed!, cause by:{}", e);
            result.setException(ExceptionConstants.SYSTEM_ERROR);
        }
        return result;
    }

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

    @Override
    public void selectOrderOperate(OrderOperateRequest request) {
        final int size = 100;
        int count = 0;
        Long lastId = 0L;
        OrderQuery query = new OrderQuery();
        query.setSize(size);
        query.setSellerId(213553L);
        query.setOrderTypeList(Arrays.asList(1, 2, 3));
        //2022-06-15 6月15到7月15
        query.setOrderAtStart(request.getOrderAtStart());
        query.setOrderAtEnd(request.getOrderAtEnd());
        query.setOrderById(1);
        for (; ; ) {
            query.setLastId(lastId);
            List<Order> orderList = tbOrderDao.selectList(query);
            if (CollectionUtils.isEmpty(orderList)) {
                logger.info("selectOrderOperate-empty count:{}, lastId:{}", count, lastId);
                break;
            }
            for (Order order : orderList) {
                List<OrderOperation> orderOperations = operationDao.selectByOrderNo(order.getOrderNo());
                if (CollectionUtils.isEmpty(orderOperations)) {
                    continue;
                }
                //批量插入tidb
                List<TempOrderOperation> list = new ArrayList<>();
                for (OrderOperation operation : orderOperations) {
                    TempOrderOperation tempOrderOperation = mapper.map(operation, TempOrderOperation.class);
                    tempOrderOperation.setId(shardingKeyGenerator.generateSnowflakeNumKey());
                    tempOrderOperation.setSellerId(order.getSellerId());
                    tempOrderOperation.setStoreId(order.getStoreId());
                    list.add(tempOrderOperation);
                }
                tempOrderOperationDao.insertList(list);
            }

            lastId = orderList.get(orderList.size() - 1).getId();
            count += orderList.size();
            logger.info("selectOrderOperate-running count:{}, lastId:{}", count, lastId);
            if (orderList.size() < size) {
                break;
            }
        }
        logger.info("selectOrderOperate-end count:{}, lastId:{}", count, lastId);
    }


    @Override
    public void selectDelOrderToTb() {
        logger.info("selectDelOrderToTb[start]");
        final int size = 500;
        int count = 0;
        Long lastId = 0L;
        OrderQuery query = new OrderQuery();
        query.setSize(size);
//        query.setSellerIdList(Arrays.asList(213951L, 206198L, 201424L, 216306L));
        query.setSellerIdList(Arrays.asList(219683L));
//        query.setOrderType(14);
//        query.setBizTypeList(Arrays.asList(5, 6));
//        query.setStoreId(172039L);
        query.setOrderAtStart(new Date(1728576000000L));
        query.setOrderAtEnd(new Date(1731599999000L));
        query.setOrderById(1);
        for (; ; ) {
            query.setLastId(lastId);
            List<Order> orderList = tbOrderDao.selectList(query);
            if (CollectionUtils.isEmpty(orderList)) {
                logger.info("selectDelOrderToTb[empty] count:{}, lastId:{}", count, lastId);
                break;
            }
            List<IdOrderNo> list = new ArrayList<>(size);
            for (Order order : orderList) {
                IdOrderNo idOrderNo = new IdOrderNo();
                idOrderNo.setOrderNo(order.getOrderNo());
                idOrderNo.setOrderId(order.getId());
                idOrderNo.setUserId(order.getUserId());
                idOrderNo.setStoreId(order.getStoreId());
                idOrderNo.setSellerId(order.getSellerId());
                idOrderNo.setOrderType(order.getOrderType());
                idOrderNo.setOrderAt(order.getOrderAt());
                list.add(idOrderNo);
            }
            idOrderNoDao.insertList(list);
            lastId = orderList.get(orderList.size() - 1).getId();
            count += orderList.size();
            logger.info("selectDelOrderToTb[running] count:{}, lastId:{}", count, lastId);
            if (orderList.size() < size) {
                break;
            }
        }
        logger.info("selectDelOrderToTb-end count:{}, lastId:{}", count, lastId);
    }


    @Override
    public void delOrderToTb() {
        final int size = 200;
        int count = 0;
        Long lastId = 9295200L;
        for (; ; ) {
            List<IdOrderNo> idOrderNoList = idOrderNoDao.selectListById(lastId);
            if (CollectionUtils.isEmpty(idOrderNoList)) {
                logger.info("delOrderToTb-empty count:{}, lastId:{}", count, lastId);
                break;
            }
            List<Long> userIdList = new ArrayList<>(size);
            List<Long> orderIdList = new ArrayList<>(size);
            List<String> orderNoList = new ArrayList<>(size);

            for (IdOrderNo idOrderNo : idOrderNoList) {
                userIdList.add(idOrderNo.getUserId());
                orderIdList.add(idOrderNo.getOrderId());
                orderNoList.add(idOrderNo.getOrderNo());
            }
            orderDao.deleteByIdUserId(orderIdList, userIdList);
            itemDao.realDeleteByOrderNoUserId(orderNoList, userIdList);
            indexDao.realDeleteByOrderNoUserId(orderNoList, userIdList);

            lastId = idOrderNoList.get(idOrderNoList.size() - 1).getId();
            count += idOrderNoList.size();
            logger.info("delOrderToTb-running count:{}, lastId:{}", count, lastId);
            if (idOrderNoList.size() < size) {
                break;
            }
        }
        logger.info("delOrderToTb-end count:{}, lastId:{}", count, lastId);
    }


    @Override
    public void insertOrderIndex(String orderNo) {
        try {
            SearchOrderQuery query = new SearchOrderQuery();
            query.setOrderNo(orderNo);
            SearchOrderDTO searchOrderDTO = searchManager.searchOrder(query);
            List<BaseIndexOrder> orderList = searchOrderDTO.getOrderList();
            if (CollectionUtils.isEmpty(orderList)) {
                return;
            }
            BaseIndexOrder indexOrder = orderList.get(0);
            Order order = orderDao.selectByOrderNo(indexOrder.getOrderNo(), indexOrder.getUserId());
            if (Objects.isNull(order)) {
                return;
            }
            OrderIndex index = new OrderIndex();
            index.setId(shardingKeyGenerator.generateSnowflakeNumKey());
            index.setOrderNo(orderNo);
            index.setOrderId(order.getId());
            index.setUserId(order.getUserId());
            index.setBizType(order.getBizType());
            index.setIsDeleted(0);
            indexDao.insert(index);
        } catch (Throwable e) {
            logger.error("insertOrderIndex[execute] failed!, cause by:{}", e);
        }

    }

    @Override
    public void delOrderRefund() {
        List<Long> list = ListConst16.list;
        refundDao.realDelete(list);
    }

    @Autowired
    private PerformanceSelfTakeDao takeDao;

    @Override
    public void realDelOrder() {
        int count = 0;
        for (String orderNo : ListConst17.list) {
            OrderIndex orderIndex = indexDao.selectOne(orderNo);
            if (Objects.isNull(orderIndex)) {
                logger.info("realDelOrder-empty orderNo:{}", orderNo);
                continue;
            }
            Order order = orderDao.selectByOrderNo(orderIndex.getOrderNo(), orderIndex.getUserId());
            if (order == null) {
                continue;
            }
            List<String> orderNoList = Arrays.asList(orderNo);
            List<Long> userIdList = Arrays.asList(orderIndex.getUserId());

            orderDao.realDelete(orderIndex.getOrderId(), orderIndex.getUserId());
            itemDao.realDeleteByOrderNoUserId(orderNoList, userIdList);
            indexDao.realDeleteByOrderNoUserId(orderNoList, userIdList);

            discountDao.deleteTemp(orderNo, orderIndex.getUserId());
            payDetailsDao.realDeleteByOrderNo(orderNo, orderIndex.getUserId());
            takeDao.realDeleteByOrderNo(orderNo, orderIndex.getUserId());
            searchManager.deleteOrder(orderIndex.getOrderId(), order.getSellerId());
            count++;
        }
        logger.info("realDelOrder-end count:{}", count);
    }

    @Override
    public void realDelOrderByTb() {

        final int size = 200;
        int count = 0;
        Long lastId = 0L;
        for (; ; ) {
            List<IdOrderNo> idOrderNoList = idOrderNoDao.selectListById(lastId);
            if (CollectionUtils.isEmpty(idOrderNoList)) {
                logger.info("delOrderToTb-empty count:{}, lastId:{}", count, lastId);
                break;
            }
            for (IdOrderNo idOrderNo : idOrderNoList) {
                String orderNo = idOrderNo.getOrderNo();
                OrderIndex orderIndex = indexDao.selectOne(orderNo);
                if (Objects.isNull(orderIndex)) {
                    orderIndex = new OrderIndex();
                    orderIndex.setOrderId(idOrderNo.getOrderId());
                    orderIndex.setUserId(idOrderNo.getUserId());
                    orderIndex.setOrderNo(idOrderNo.getOrderNo());
                }

                Order order = orderDao.selectByOrderNo(orderIndex.getOrderNo(), orderIndex.getUserId());
                if(order == null){
                    continue;
                }

                List<String> orderNoList = Arrays.asList(orderNo);
                List<Long> userIdList = Arrays.asList(orderIndex.getUserId());

                orderDao.realDelete(orderIndex.getOrderId(), orderIndex.getUserId());
                itemDao.realDeleteByOrderNoUserId(orderNoList, userIdList);
                indexDao.realDeleteByOrderNoUserId(orderNoList, userIdList);

                discountDao.deleteTemp(orderNo, orderIndex.getUserId());
                payDetailsDao.realDeleteByOrderNo(orderNo, orderIndex.getUserId());
                searchManager.deleteOrder(orderIndex.getOrderId(), order.getSellerId());
                count++;
            }
            logger.info("realDelOrder-end count:{}", count);

            lastId = idOrderNoList.get(idOrderNoList.size() - 1).getId();
            count += idOrderNoList.size();
            logger.info("delOrderToTb-running count:{}, lastId:{}", count, lastId);
            if (idOrderNoList.size() < size) {
                break;
            }
        }
    }

    @Override
    public void orderMerge(OrderMergeRequest request) {
        try {
            Map<String, Object> map = new HashMap();
            //手机号
            map.put("phone", request.getPhone());
            //历史用户ID
            map.put("id", request.getId());
            //新用户ID
            map.put("customerId", request.getCustomerId());
            Boolean aBoolean = innerApiManager.orderMerge(map);
            logger.info("orderMerge, result:{}, request:{}", aBoolean, map);

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

    @Override
    public void selectTidbToTemp() {
        try {
            OrderQuery query = new OrderQuery();
            query.setSellerId(203695L);
            // 从开始刷数据  2022-10-18 00:00:00
            Long startLong = 1617206400000L;
            // 2022-10-20 00:00:00
            Long endLong = 1635696000000L;
            int num = 1;
            Long lastId = null;

            // 分时段处理，每天一个时段
            for (Long i = startLong; i < endLong; i = i + 86400000L) {
                Date start = new Date(i);
                Date end = new Date(i + 86400000L);
                query.setOrderAtStart(start);
                query.setOrderAtEnd(end);
                doSelectTidbToTemp(query, num, lastId);
                logger.info("selectTidbToTemp[selectTidbToTemp] start:{}", start);
                num++;
            }

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

    public void doSelectTidbToTemp(OrderQuery query, int i, Long lastId) {
        final int size = 500;
        int count = 0;
        query.setSize(size);
//        query.setBizTypeList(Arrays.asList(4,5));
        query.setOrderById(1);
//        query.setLikeScrm(1);
        for (; ; ) {
            query.setLastId(lastId);
            List<Order> orderList = tbOrderDao.selectList(query);
            if (CollectionUtils.isEmpty(orderList)) {
                logger.info("syncSplByTime[syncSplByTime]-break-empty-{} count:{}, lastId:{}, query:{}", i, count, lastId, query);
                break;
            }
            List<OrderNoUser> list = new ArrayList<>(orderList.size());
            for (Order order : orderList) {
                OrderNoUser orderNoUser = new OrderNoUser();
                orderNoUser.setOrderNo(order.getOrderNo());
                orderNoUser.setOrderId(order.getId());
                orderNoUser.setUserId(order.getUserId());
                list.add(orderNoUser);
            }
            lastId = orderList.get(orderList.size() - 1).getId();
            if (!CollectionUtils.isEmpty(list)) {
                //批量插入
                orderNoUserDao.insertList(list);
            }
            count += orderList.size();
            logger.info("syncSplByTime[syncSplByTime]-{} count:{}, lastId:{}", i, count, lastId);
            if (orderList.size() < size) {
                logger.info("syncSplByTime[syncSplByTime]-break-less-{} count:{}, lastId:{}, query:{}", i, count, lastId, query);
                break;
            }
        }
        logger.info("syncSplByTime[syncSplByTime][end]-{} count:{}, lastId:{}", i, count, lastId);
    }


    @Override
    public void syncTempOrderToEs() {
        // 临时库订单同步ES
        final int size = 200;
        int count = 0;
        Long lastId = 0L;
        for (; ; ) {
            List<OrderNoUser> orderNoUserList = orderNoUserDao.selectList(lastId);
            if (CollectionUtils.isEmpty(orderNoUserList)) {
                logger.info("syncTempOrderToEs-empty count:{}, lastId:{}", count, lastId);
                break;
            }
            List<Long> userIdList = new ArrayList<>(size);
            List<Long> orderIdList = new ArrayList<>(size);
            List<String> orderNoList = new ArrayList<>(size);

            for (OrderNoUser idOrderNo : orderNoUserList) {
                userIdList.add(idOrderNo.getUserId());
                orderIdList.add(idOrderNo.getOrderId());
                orderNoList.add(idOrderNo.getOrderNo());
            }
            OrderQuery query = new OrderQuery();
            query.setUserIdList(userIdList);
            query.setIdList(orderIdList);
            List<Order> orderList = orderDao.selectListByOrderNosUserIds(query);

            List<BatchSyncEsMessage> messageList = new ArrayList<>(size);

            if (!CollectionUtils.isEmpty(orderList)) {
                for (Order order : orderList) {
                    messageList.add(buildMessage(order));
                }
            }
            messageManager.sendBatchSyncMessage(messageList);

            lastId = orderNoUserList.get(orderNoUserList.size() - 1).getId();
            count += orderNoUserList.size();
            logger.info("syncTempOrderToEs-running count:{}, lastId:{}", count, lastId);
            if (orderNoUserList.size() < size) {
                break;
            }
        }
        logger.info("syncTempOrderToEs-end count:{}, lastId:{}", count, lastId);
    }

    public static void main(String[] args) {
        Date current = new Date();
        System.out.println(DateUtils.getStartDate(DateUtils.before(current, Calendar.DAY_OF_YEAR, 90)));
    }

    final int deleteSize = 200;
    final int stopHour = 5;

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

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

    private int getHour () {
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY); // 24小时制
        return hour;
    }
    /**
     * 删除90天之前的订单操作日志
     * order_operations :
     *  分片key: order_no
     *  index :
     *      order_no
     *      updated_at
     */

    private int fixDeletedSize = 100000;
    @Override
    public Result deleteOrderOperations() {
        int count = 0;
        Date current = new Date();
        // 获取90天之前的日期
        Date endDate = DateUtils.getStartDate(DateUtils.before(current, Calendar.DAY_OF_YEAR, 180));
        try {
            logger.info("deleteOrderOperations[start], endDate:{}", endDate);
            OrderOperationQuery query = new OrderOperationQuery();
            query.setSize(fixDeletedSize);
            query.setUpdatedAtEnd(endDate);
            for (int i = 0; i < dbSize; i++) {
                for (int j = 0; j < tbSize; j++) {
                    for (; ; ) {
                        int deleteRows = commonManager.deleteOrderOperationSize(query, i, j);
                        count += deleteRows;
                        logger.info("deleteOrderOperations[running], i:{}, j:{}, count:{}，deleteRows：{}", i, j, count, deleteRows);
                        if (deleteRows < fixDeletedSize) {
                            break;
                        }
                        Thread.sleep(100);
                        if (getHour() == stopHour) {
                            logger.info("deleteOrderOperations[stopHour], i:{}, j:{}, count:{}, getHour:{}", i, j, count, getHour());
                            return Result.successNullData();
                        }
                        Result<String> redisData = redisManager.get("delete_order_operations");
                        if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                            return Result.successNullData();
                        }
                    }
                }
            }
            logger.info("deleteOrderOperations[end], count:{}", count);
        } catch (Exception e) {
            logger.error("[deleteOrderOperations] failed! cause by:{}", e);
            return Result.failureData(ExceptionConstants.SYSTEM_ERROR);
        }
        return Result.successNullData();
    }


    private int updateUpdatedAtSize = 1000;
    @Override
    public Result updateUpdatedAt() {
        int count = 0;
        Date startDate = new Date(1721293200000L);
        Date endDate = new Date(1721322000000L);
        try {
            logger.info("updateUpdatedAt[start], endDate:{}", endDate);
            OrderOperationQuery query = new OrderOperationQuery();
            query.setSize(updateUpdatedAtSize);
            query.setUpdatedAtStart(startDate);
            query.setUpdatedAtEnd(endDate);
            for (int i = 0; i < dbSize; i++) {
                for (int j = 0; j < tbSize; j++) {
                    for (; ; ) {
                        int deleteRows = commonManager.updateOrderUpdatedAt(query, i, j);
                        count += deleteRows;
                        logger.info("updateUpdatedAt[running], i:{}, j:{}, count:{}，deleteRows：{}", i, j, count, deleteRows);
                        if (deleteRows < updateUpdatedAtSize) {
                            break;
                        }
                        Thread.sleep(10);
                        Result<String> redisData = redisManager.get("delete_order_operations");
                        if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                            return Result.successNullData();
                        }
                    }
                }
            }
            logger.info("updateUpdatedAt[end], count:{}", count);
        } catch (Exception e) {
            logger.error("[updateUpdatedAt] failed! cause by:{}", e);
            return Result.failureData(ExceptionConstants.SYSTEM_ERROR);
        }
        return Result.successNullData();
    }

    @Override
    public Result deleteOrderPushLog() {
        int count = 0;
        Date current = new Date();
        // 获取30天之前的日期
        Date endDate = DateUtils.getStartDate(DateUtils.before(current, Calendar.DAY_OF_YEAR, 31));
        try {
            logger.info("deletePushLogs[start], endDate:{}", endDate);
            OrderOperationQuery query = new OrderOperationQuery();
            query.setSize(fixDeletedSize);
            query.setUpdatedAtEnd(endDate);
            for (int i = 0; i < dbSize; i++) {
                for (int j = 0; j < tbSize; j++) {
                    for (; ; ) {
                        int deleteRows = commonManager.deleteOrderPushLogsSize(query, i, j);
                        count += deleteRows;
                        logger.info("deletePushLogs[running], i:{}, j:{}, count:{}，deleteRows：{}", i, j, count, deleteRows);
                        if (deleteRows < fixDeletedSize) {
                            break;
                        }
                        Thread.sleep(100);
                        if (getHour() == stopHour) {
                            logger.info("deletePushLogs[stopHour], i:{}, j:{}, count:{}, getHour:{}", i, j, count, getHour());
                            return Result.successNullData();
                        }
                        Result<String> redisData = redisManager.get("delete_order_operations");
                        if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                            return Result.successNullData();
                        }
                    }
                }
            }
            logger.info("deletePushLogs[end], count:{}", count);
        } catch (Exception e) {
            logger.error("[deletePushLogs] failed! cause by:{}", e);
            return Result.failureData(ExceptionConstants.SYSTEM_ERROR);
        }
        return Result.successNullData();
    }



    /**
     * test
     */
//    private Long T97sellerId = 11409L;

    /**
     * pro
     */
    private Long T97sellerId = 214870L;

    @Override
    public void transferOrderT97() {
        try {
            logger.info("transferOrderT97[start]");
            Long lastId = null;
            int size = 200;
            int count = 0;
            int orderCount = 0;
            int refundFlag = 0;
            for (; ; ) {
                List<OrderT97> list = t97Dao.selectList(lastId, size, refundFlag);
                if (CollectionUtils.isEmpty(list)) {
                    break;
                }
                List<Order> orderList = new ArrayList<>(size);
                List<OrderItem> itemList = new ArrayList<>(size);
                List<OrderPayDetails> payList = new ArrayList<>(size);
                List<OrderDiscount> discountList = new ArrayList<>(size);

                List<String> orderNoList = list.stream().map(OrderT97::getOrderNo).collect(Collectors.toList());
                List<Long> userIdList = list.stream().map(OrderT97::getUserId).collect(Collectors.toList());
                orderNoList.removeAll(Collections.singleton(null));
                userIdList.removeAll(Collections.singleton(null));
                OrderQuery query = new OrderQuery();
                if (CollectionUtils.isEmpty(userIdList)) {
                    continue;
                }
                query.setOrderNoList(orderNoList);
                query.setUserIdList(userIdList);
                // 订单可能已存在
                List<Order> orderExistList = orderDao.selectListByOrderNosUserIds(query);

                //优惠是否存在
                OrderDiscountQuery discountQuery = new OrderDiscountQuery();
                discountQuery.setUserIdList(userIdList);
                discountQuery.setOrderNoList(orderNoList);
                List<OrderDiscount> discountExistList = discountDao.selectListByUserIds(discountQuery);
                Map<String, OrderDiscount> discountExistMap = discountExistList.stream().collect(Collectors.toMap(OrderDiscount::getOrderNo, Function.identity()));

                //支付是否存在
                OrderPayDetailsQuery payDetailsQuery = new OrderPayDetailsQuery();
                payDetailsQuery.setUserIdList(userIdList);
                payDetailsQuery.setOrderNoList(orderNoList);
                List<OrderPayDetails> payExistList = payDao.selectList(payDetailsQuery);
                Map<String, OrderPayDetails> payExistMap = payExistList.stream().collect(Collectors.toMap(OrderPayDetails::getOrderNo, Function.identity()));

                //数据库已有的订单号列表
                List<String> orderNoExistList = orderExistList.stream().map(Order::getOrderNo).collect(Collectors.toList());
                Map<String, Order> orderNoMap = orderExistList.stream().collect(Collectors.toMap(Order::getOrderNo, Function.identity()));
                Map<String, Order> orderNoInsertMap = new HashMap<>(size);

                for (OrderT97 item : list) {
                    //订单号不存在 ： 不迁移
                    if (Objects.isNull(item.getOrderNo())) {
                        continue;
                    }
                    //订单已存在数据库：更新商品快照，加商品, 更新优惠金额、总金额
                    if (Objects.nonNull(orderNoMap.get(item.getOrderNo()))) {
                        // insert商品，更新订单商品快照
                        buildT97Item(itemList, item, orderNoMap);
                        logger.info("transferOrderT97[orderExist],count:{},lastId:{},orderNo:{}", count, lastId, item.getOrderNo());
                    } else {
                        //订单不存在数据库，新构建
                        OrderItem orderItem = buildT97Item(itemList, item);
                        // 本次200条循环前面构建过订单， 更新itemInfo  更新优惠金额、总金额,支付金额
                        if (Objects.nonNull(orderNoInsertMap.get(item.getOrderNo()))) {
                            Order order = orderNoInsertMap.get(item.getOrderNo());
                            if (!Objects.equals(ITEM_FLAG, order.getItemInfo())) {
                                List<InnerOrderItem> innerOrderItems = JSON.parseArray(order.getItemInfo(), InnerOrderItem.class);
                                InnerOrderItem inner = mapper.map(orderItem, InnerOrderItem.class);
                                innerOrderItems.add(inner);
                                if (innerOrderItems.size() > MAX_ITEM_SIZE) {
                                    order.setItemInfo(ITEM_FLAG);
                                } else {
                                    order.setItemInfo(JSON.toJSONString(innerOrderItems));
                                }
                            }

                            BigDecimal multiplyDiscount = item.getDiscountAmount().multiply(new BigDecimal(100));
                            Integer discountAmount = Double.valueOf(multiplyDiscount.toString()).intValue();
                            order.setDiscountAmount(order.getDiscountAmount() + discountAmount);

                            int intItemAmount = 0;
                            if (Objects.nonNull(item.getItemPrice())) {
                                BigDecimal multiply = item.getItemPrice().multiply(new BigDecimal(100));
                                intItemAmount = (Double.valueOf(multiply.toString()).intValue());
                            }
                            order.setPayAmount(order.getPayAmount() + intItemAmount);
                            order.setActualAmount(order.getActualAmount() + intItemAmount);
                            order.setTotalAmount(order.getTotalAmount() + discountAmount + intItemAmount);
                            order.setItemAmount(order.getItemAmount() + discountAmount + intItemAmount);
                            
                            logger.info("transferOrderT97[reBuildOrderItemInfo],count:{},lastId:{},orderNo:{}", count, lastId, item.getOrderNo());
                            orderNoInsertMap.put(item.getOrderNo(), order);

                        } else {
                            //前面没构建过： 新构建订单
                            Order order = buildT97Order(orderList, item);
                            InnerOrderItem innerOrderItem = mapper.map(orderItem, InnerOrderItem.class);
                            order.setItemInfo(JSON.toJSONString(Arrays.asList(innerOrderItem)));
//                            buildT97PayDetail(payList, item, order);
                            orderNoInsertMap.put(item.getOrderNo(), order);
                            logger.info("transferOrderT97[createNew],count:{},lastId:{},orderNo:{}", count, lastId, item.getOrderNo());
                        }
                    }
                }
                List<BatchSyncEsMessage> messageList = new ArrayList<>(size);

                //循环更新已存在订单
                if (!CollectionUtils.isEmpty(orderNoMap)) {
                    for (Order order : orderNoMap.values()) {
                        buildT97DiscountInfo(discountExistMap, order, discountList);
                        buildT97PayInfo(payExistMap, order, payList);
                        orderDao.updateItemAndDiscount(order);
                        messageList.add(buildMessage(order));
                    }
                }
                List<OrderIndex> indexList = new ArrayList<>(size);

                //批量新增订单
                if (!CollectionUtils.isEmpty(orderNoInsertMap)) {
                    for (Order order : orderNoInsertMap.values()) {
                        buildT97DiscountInfo(discountExistMap, order, discountList);
                        buildT97PayInfo(payExistMap, order, payList);
                        orderList.add(order);
                        messageList.add(buildMessage(order));
                        OrderIndex index = new OrderIndex();
                        index.setOrderNo(order.getOrderNo());
                        index.setOrderId(order.getId());
                        index.setUserId(order.getUserId());
                        index.setBizType(order.getBizType());
                        index.setId(generator.generateSnowflakeNumKey());
                        indexList.add(index);
                    }
                    orderDao.insertList(orderList);
                    orderCount += orderList.size();
                }
                //循环更新已存在优惠
                if (!CollectionUtils.isEmpty(discountExistMap)) {
                    for (OrderDiscount discount : discountExistMap.values()) {
                        discountDao.updateDiscountAmountTwo(discount);
                    }
                }
                //循环更新已存在支付
                if (!CollectionUtils.isEmpty(payExistMap)) {
                    for (OrderPayDetails payDetails : payExistMap.values()) {
                        payDao.updateAmount(payDetails);
                    }
                }
                // 新增订单索引
                if (!CollectionUtils.isEmpty(indexList)) {
                    indexDao.insertList(indexList);
                }
                //批量新增商品
                if (!CollectionUtils.isEmpty(itemList)) {
                    orderItemDao.inserts(itemList);
                }
                //批量新增支付明细
                if (!CollectionUtils.isEmpty(payList)) {
                    payDao.insertList(payList);
                }
                //批量新增优惠
                if (!CollectionUtils.isEmpty(discountList)) {
                    discountDao.inserts(discountList);
                }
                //同步ES
                List<BatchSyncEsMessage> pushList = new ArrayList<>(size);
                buildPushMessage(messageList, pushList);
                messageManager.sendBatchSyncMessage(pushList);

                lastId = list.get(list.size() - 1).getId();
                count = count + list.size();
                logger.info("transferOrderT97[for-end],count:{},lastId:{}, orderCount:{}", count, lastId, orderCount);
                if (list.size() < size) {
                    break;
                }
            }
            logger.info("transferOrderT97[end],count:{},lastId:{}, orderCount:{}", count, lastId, orderCount);

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

    private void buildT97DiscountInfo( Map<String, OrderDiscount> discountExistMap, Order order, List<OrderDiscount> discountList){
        Integer discountAmount = order.getDiscountAmount();
        if (discountAmount <= 0) {
            return;
        }
        //更新discountAmount
        if(discountExistMap.containsKey(order.getOrderNo())){
            discountExistMap.get(order.getOrderNo()).setDiscountAmount(discountAmount);
            order.setDiscountInfo(JSON.toJSONString(Arrays.asList(mapper.map(discountExistMap.get(order.getOrderNo()), InnerOrderDiscount.class))));
        } else {
            //构建新优惠
            buildT97Discount(discountList, order);
        }
    }


    private void buildT97PayInfo( Map<String, OrderPayDetails> payExistMap, Order order, List<OrderPayDetails> payList){
        Integer payAmount = order.getPayAmount();
        if (payAmount <= 0) {
            return;
        }
        if (!order.getPayStatus().equals(1)) {
            return;
        }
        //更新payAmount
        if(payExistMap.containsKey(order.getOrderNo())){
            payExistMap.get(order.getOrderNo()).setAmount(payAmount);
            order.setPayDetailInfo(JSON.toJSONString(Arrays.asList(mapper.map(payExistMap.get(order.getOrderNo()), InnerOrderPayDetails.class))));
        } else {
            //构建新优惠
            buildT97Pay(payList, order);
        }
    }

    private void buildT97Pay(List<OrderPayDetails> list, Order order) {
        OrderPayDetails payDetails = new OrderPayDetails();
        payDetails.setId(generator.generateSnowflakeNumKey());
        payDetails.setOrderNo(order.getOrderNo());
        payDetails.setUserId(order.getUserId());
        payDetails.setAmount(order.getPayAmount());
        payDetails.setPayType(order.getPayType());
        payDetails.setStoreId(order.getStoreId());
        payDetails.setSellerId(T97sellerId);
        payDetails.setOrderAt(order.getOrderAt());
        payDetails.setPayAt(order.getCompletedAt());
        payDetails.setOrderType(order.getOrderType());
        payDetails.setSource(order.getSource());
        payDetails.setStatus(0);
        payDetails.setPayNo("");
        payDetails.setThirdPayNo("");
        list.add(payDetails);
        String payDetailInfo = JSON.toJSONString(Arrays.asList(mapper.map(payDetails, InnerOrderPayDetails.class)));
        order.setPayDetailInfo(payDetailInfo);
    }


    private void buildT97Item(List<OrderItem> itemList, OrderT97 juiceOrder, Map<String, Order> orderNoMap) {
        OrderItem orderItem = buildT97ItemValue(itemList, juiceOrder);
        Order order = orderNoMap.get(juiceOrder.getOrderNo());
        if (Objects.nonNull(order)) {
            String itemInfo = order.getItemInfo();
            if (!Objects.equals(ITEM_FLAG, itemInfo)) {
                List<InnerOrderItem> innerOrderItems = JSON.parseArray(itemInfo, InnerOrderItem.class);
                InnerOrderItem inner = mapper.map(orderItem, InnerOrderItem.class);
                innerOrderItems.add(inner);
                if (innerOrderItems.size() > MAX_ITEM_SIZE) {
                    order.setItemInfo(ITEM_FLAG);
                } else {
                    order.setItemInfo(JSON.toJSONString(innerOrderItems));
                }
            }
            //订单总金额累加 + 实付 + 每一笔的优惠
            int intDiscountAmount = 0;
            if (Objects.nonNull(juiceOrder.getDiscountAmount())) {
                BigDecimal multiply = juiceOrder.getDiscountAmount().multiply(new BigDecimal(100));
                intDiscountAmount = Double.valueOf(multiply.toString()).intValue();
                //订单优惠金额累加
                order.setDiscountAmount(order.getDiscountAmount() + intDiscountAmount);
            }

            //商品原价金额累加
            int intItemPrice = 0;
            if (Objects.nonNull(juiceOrder.getItemPrice())) {
                BigDecimal multiply = juiceOrder.getItemPrice().multiply(new BigDecimal(100));
                intItemPrice = Double.valueOf(multiply.toString()).intValue();
                order.setItemAmount(order.getItemAmount() + intItemPrice + intDiscountAmount);
                order.setPayAmount(order.getPayAmount() + intItemPrice);
                order.setActualAmount(order.getActualAmount() + intItemPrice);
            }
            order.setTotalAmount(order.getTotalAmount() + intDiscountAmount + intItemPrice);

        }
        orderNoMap.put(juiceOrder.getOrderNo(), order);
    }


    private OrderItem buildT97ItemValue(List<OrderItem> itemList, OrderT97 juiceOrder) {
        int intDiscountAmount = 0;
        //当前商品优惠金
        if (Objects.nonNull(juiceOrder.getDiscountAmount())) {
            BigDecimal multiply = juiceOrder.getDiscountAmount().multiply(new BigDecimal(100));
            intDiscountAmount = Double.valueOf(multiply.toString()).intValue();
        }

        int intItemPrice = 0;
        //当前商品实付
        if (Objects.nonNull(juiceOrder.getItemPrice())) {
            BigDecimal itemPrice = juiceOrder.getItemPrice().multiply(new BigDecimal(100));
            intItemPrice = Double.valueOf(itemPrice.toString()).intValue();
        }

        OrderItem item = new OrderItem();
        item.setId(generator.generateSnowflakeNumKey());
        item.setBizType(5);
        item.setUserId(juiceOrder.getUserId());
        item.setOrderNo(juiceOrder.getOrderNo());
        item.setItemId(juiceOrder.getItemId());
        item.setGoodsId(juiceOrder.getGoodsId());
        item.setItemImage("");
        item.setItemSign(juiceOrder.getItemSign());

        item.setDiscountAmount(intDiscountAmount);

        if (StringUtils.isEmpty(juiceOrder.getItemName())) {
            item.setItemName("历史消费商品");
        } else {
            item.setItemName(juiceOrder.getItemName());
        }
        if (Objects.nonNull(juiceOrder.getNum())) {
            item.setNum(juiceOrder.getNum());
        } else {
            item.setNum(new BigDecimal(1));
        }

        item.setItemPrice( juiceOrder.getItemPriceNew() );

        item.setItemSpec(null);
        item.setItemUnit("");
        item.setBrandSign("");
        item.setMarketPrice(0);
        item.setCostPrice(0);
        item.setMemberPrice(0);
        item.setPackAmount(0);
        item.setfCode("");
        item.setStatus(0);
        Map<String, Object> map = new HashMap();
        map.put("historyOrder", 1);
        map.put("itemAmount", intDiscountAmount + intItemPrice);
        item.setExtraMap(map);

        item.setActivityId(0L);
        item.setIsTimeDiscount(0);
        item.setOrderAt(juiceOrder.getOrderAt());
        item.setProductNo("");
        item.setIsGift(0);
        item.setSellerId(T97sellerId);
        item.setItemType(0);
        item.setOwnerId(0L);
        item.setBatchingInfo("");
        itemList.add(item);
        return item;
    }

    private OrderItem buildT97Item(List<OrderItem> itemList, OrderT97 juiceOrder) {
        OrderItem orderItem = buildT97ItemValue(itemList, juiceOrder);
        return orderItem;
    }

    public Order buildT97Order(List<Order> orderList, OrderT97 juiceOrder) {
        Order order = new Order();
        order.setId(generator.generateSnowflakeNumKey());
        order.setOrderNo(juiceOrder.getOrderNo());
        order.setUserId(juiceOrder.getUserId());
        order.setOrderType(juiceOrder.getOrderType());
        order.setDiscountAmount(0);
        order.setActualAmount(0);
        order.setPayAmount(0);
        order.setItemAmount(0);
        order.setPayStatus(juiceOrder.getPayStatus());
        order.setStatus(juiceOrder.getStatus());
        order.setSource(juiceOrder.getSource());

        int intDiscountAmount = 0;
        //订单优惠金额
        if (Objects.nonNull(juiceOrder.getDiscountAmount())) {
            BigDecimal multiply = juiceOrder.getDiscountAmount().multiply(new BigDecimal(100));
            intDiscountAmount = Double.valueOf(multiply.toString()).intValue();
            //订单优惠金额
            order.setDiscountAmount(order.getDiscountAmount() + intDiscountAmount);
        }
        //订单总金额 + 实付 + 每一笔的优惠
//        if (Objects.nonNull(juiceOrder.getPayAmount())) {
//            BigDecimal multiply = juiceOrder.getPayAmount().multiply(new BigDecimal(100));
//            int intPayAmount = Double.valueOf(multiply.toString()).intValue();
//            order.setTotalAmount(intPayAmount + intDiscountAmount);
//        }

        //订单商品原价
        //当前商品实付金额
        int intItemPrice = 0;
        if (Objects.nonNull(juiceOrder.getItemPrice())) {
            BigDecimal multiply = juiceOrder.getItemPrice().multiply(new BigDecimal(100));
            intItemPrice = Double.valueOf(multiply.toString()).intValue();
            order.setItemAmount(intItemPrice + intDiscountAmount);
        }
        order.setPayAmount(intItemPrice);
        order.setActualAmount(intItemPrice);
        order.setTotalAmount(intItemPrice + intDiscountAmount);

        order.setBizSubType(0);
        order.setPackAmount(0);
        order.setFreightAmount(0);
        order.setChangeAmount(0);
        order.setPayModel(0);
        order.setIsAlone(0);
        order.setInvoiceType(0);
        order.setAfterSaleStatus(0);
        order.setReceiveStatus(0);
        order.setPerformanceStatus(0);
        order.setCommentStatus(0);
        order.setPerformanceType(0);
        order.setIsReceipt(0);
        order.setIsImmediatePerformance(0);
        order.setSourceNo("");
        order.setBizType(5);
        order.setFromSystem(0);
        order.setOrderSubType(0);
        order.setPayType(juiceOrder.getPayType());
        order.setIsDeleted(1);
        order.setAddrId(0);
        order.setSyncFlag(0);
        order.setVersion(1);
        order.setPayFlag(1);
        order.setPayer(juiceOrder.getUserId());

//        if (Objects.nonNull(juiceOrder.getPayNo())) {
//            order.setPayNo(juiceOrder.getPayNo());
//            order.setThirdPayNo(juiceOrder.getPayNo());
//        }
//        if (Objects.nonNull(juiceOrder.getSellerRemark())) {
//            order.setSellerRemarks(juiceOrder.getSellerRemark());
//        }
        if (Objects.nonNull(juiceOrder.getMobile())) {
            order.setMobile(juiceOrder.getMobile());
        }
        order.setSellerId(T97sellerId);
        if (Objects.nonNull(juiceOrder.getStoreId())) {
            order.setStoreId(juiceOrder.getStoreId());
        }

        order.setOrderAt(juiceOrder.getOrderAt());
        order.setCreatedAt(juiceOrder.getOrderAt());
        order.setPayAt(juiceOrder.getCompletedAt());
        order.setCompletedAt(juiceOrder.getCompletedAt());
        order.setUpdatedAt(new Date());
        Map<String, Object> map = new HashMap();
        map.put("historyOrder", 1);
        if (!StringUtils.isEmpty(juiceOrder.getStoreName())) {
            map.put("storeName", juiceOrder.getStoreName());
        }
        order.setExtraMap(map);
        return order;
    }

    private void buildT97PayDetail(List<OrderPayDetails> list, OrderT97 juiceOrder, Order order) {
        //订单总金额 + 实付 + 每一笔的优惠
        Integer payAmount = 0;
        if (Objects.nonNull(juiceOrder.getPayAmount())) {
            BigDecimal multiply = juiceOrder.getPayAmount().multiply(new BigDecimal(100));
            payAmount = Double.valueOf(multiply.toString()).intValue();
        }
        if (payAmount <= 0) {
            return;
        }
        if (!juiceOrder.getPayStatus().equals(1)) {
            return;
        }
        OrderPayDetails payDetails = new OrderPayDetails();
        payDetails.setId(generator.generateSnowflakeNumKey());
        payDetails.setOrderNo(juiceOrder.getOrderNo());
        payDetails.setUserId(juiceOrder.getUserId());
        payDetails.setAmount(payAmount);
        payDetails.setPayType(juiceOrder.getPayType());
        payDetails.setStoreId(juiceOrder.getStoreId());
        payDetails.setSellerId(T97sellerId);
        payDetails.setOrderAt(juiceOrder.getOrderAt());
        payDetails.setPayAt(juiceOrder.getCompletedAt());
        payDetails.setOrderType(juiceOrder.getOrderType());
        payDetails.setSource(juiceOrder.getSource());
        payDetails.setPayNo("");
        payDetails.setThirdPayNo("");
        list.add(payDetails);
        String payDetailInfo = JSON.toJSONString(Arrays.asList(mapper.map(payDetails, InnerOrderPayDetails.class)));
        order.setPayDetailInfo(payDetailInfo);
    }


    @Override
    public void transferRefundOrderT97() {
        try {
            logger.info("transferRefundOrderT97[start]");
            Long lastId = null;
            int size = 200;
            int count = 0;
            int orderCount = 0;
            int refundFlag = 1;
            for (; ; ) {
                List<OrderT97> list = t97Dao.selectList(lastId, size, refundFlag);
                if (CollectionUtils.isEmpty(list)) {
                    break;
                }
                List<Refund> refundList = new ArrayList<>(size);
                List<RefundItem> itemList = new ArrayList<>(size);
                List<OrderRefundDetails> detailsList = new ArrayList<>(size);

                List<String> orderNoList = list.stream().map(OrderT97::getRefundOrderNo).collect(Collectors.toList());

                List<String> refundNoList = list.stream().map(OrderT97::getOrderNo).collect(Collectors.toList());
                List<Long> userIdList = list.stream().map(OrderT97::getUserId).collect(Collectors.toList());
                refundNoList.removeAll(Collections.singleton(null));
                userIdList.removeAll(Collections.singleton(null));
                RefundQuery query = new RefundQuery();
                query.setRefundNoList(refundNoList);
                // 退款单可能已存在
                List<Refund> refundExistList = refundDao.selectList(query);
                //数据库已有的退款单列表
                Map<String, Refund> refundNoMap = refundExistList.stream().collect(Collectors.toMap(Refund::getRefundNo, Function.identity()));
                Map<String, Refund> refundNoInsertMap = new HashMap<>(size);

                for (OrderT97 item : list) {
                    //订单号不存在 ： 不迁移
                    if (Objects.isNull(item.getOrderNo())) {
                        continue;
                    }
                    //退款单已存在数据库，加商品, 更新优惠金额、总金额
                    if (Objects.nonNull(refundNoMap.get(item.getOrderNo()))) {
                        // insert商品，更新订单商品快照
                        buildT97RefundItem  (itemList, item, refundNoMap);
                        logger.info("transferRefundOrderT97[orderExist],count:{},lastId:{},refundNo:{}", count, lastId, item.getOrderNo());
                    } else {
                        //退款单不存在数据库，新构建
                        RefundItem orderItem = buildT97RefundItem(itemList, item);
                        // 本次200条循环前面构建过订单  更新退款金额
                        if (Objects.nonNull(refundNoInsertMap.get(item.getOrderNo()))) {
//                            Refund order = refundNoInsertMap.get(item.getOrderNo());
                            logger.info("transferRefundOrderT97[reBuildOrderItemInfo],count:{},lastId:{},orderNo:{}, orderItem:{}", count, lastId, item.getOrderNo(), orderItem);
                        } else {
                            //前面没构建过： 新构建订单
                            Refund order = buildT97Refund(refundList, item);
//                            InnerOrderItem innerOrderItem = mapper.map(orderItem, InnerOrderItem.class);
                            buildT97RefundDetail(detailsList, item, order);
                            refundNoInsertMap.put(item.getOrderNo(), order);
                            logger.info("transferRefundOrderT97[createNew],count:{},lastId:{},orderNo:{}, orderItem:{}", count, lastId, item.getOrderNo(), orderItem);
                        }
                    }
                }

                //循环更新已存在退款单
                if (!CollectionUtils.isEmpty(refundNoMap)) {
                    for (Refund order : refundNoMap.values()) {
                        refundDao.update(order);
                    }
                }

                //批量新增 退款单
                List<Refund> refundInsertList = new ArrayList<>(size);

                if (!CollectionUtils.isEmpty(refundNoInsertMap)) {
                    for (Refund order : refundNoInsertMap.values()) {
                        refundInsertList.add(order);
                    }
                    refundDao.insertList(refundInsertList);
                    orderCount += refundList.size();
                }
                System.out.println(itemList);
                //批量新增商品
                if (!CollectionUtils.isEmpty(itemList)) {
                    refundItemDao.inserts(itemList);
                }
                System.out.println(detailsList);

                //批量新增支付明细
                if (!CollectionUtils.isEmpty(detailsList)) {
                    detailsDao.insertList(detailsList);
                }
                lastId = list.get(list.size() - 1).getId();
                count = count + list.size();
                logger.info("juiceOrder,count:{},lastId:{}, orderCount:{}", count, lastId, orderCount);
                if (list.size() < size) {
                    break;
                }
            }
        } catch (Throwable e) {
            logger.error("juiceOrder[execute] failed!, cause by:{}", e);
        }
    }

        private void buildT97Discount(List<OrderDiscount> list, Order order ) {
//        Integer discountAmount = Integer.valueOf(juiceOrder.getDiscountAmount().multiply(oneHundred).toString());
//        if (discountAmount <= 0) {
//            return;
//        }
        OrderDiscount discount = new OrderDiscount();
        discount.setId(generator.generateSnowflakeNumKey());
        discount.setBizType(5);
        discount.setUserId(order.getUserId());
        discount.setOrderNo(order.getOrderNo());
        discount.setItemId(null);
        discount.setDiscountLevel(0);
        discount.setDiscountId("0");
        discount.setDiscountType(9);
        discount.setDiscountName("支付优惠");
        discount.setDiscountSummary("支付优惠");
        discount.setDiscountAmount(order.getDiscountAmount());
        discount.setFeatures("");
        list.add(discount);
        order.setDiscountInfo(JSON.toJSONString(Arrays.asList(mapper.map(discount, InnerOrderDiscount.class))));
    }

    private Refund buildT97Refund(List<Refund> refundList, OrderT97 t97){
        Refund order = new Refund();
        order.setId(generator.generateSnowflakeNumKey());
        order.setSource(t97.getSource());
        order.setSellerId(T97sellerId);
        order.setRefundNo(t97.getOrderNo());
        order.setOrderNo(t97.getRefundOrderNo());
        order.setUserId(t97.getUserId());
        order.setBizType(5);
        order.setOrderType(t97.getOrderType());
        order.setOrderSubType(0);
        order.setRefundLevel(2);

        order.setStoreId(t97.getStoreId());
        order.setMobile(t97.getMobile());

        Integer payAmount = 0;
        if (Objects.nonNull(t97.getPayAmount())) {
            BigDecimal multiply = t97.getPayAmount().multiply(new BigDecimal(100));
            payAmount = Double.valueOf(multiply.toString()).intValue();
        }
        order.setRefundAmount(payAmount);
        order.setAmount(payAmount);

        order.setWalletAmount(0);

        order.setApplicant(t97.getUserId());
        order.setApplyAt(t97.getOrderAt());
        order.setOrderAt(t97.getOrderAt());
        order.setCreatedAt(t97.getOrderAt());
        order.setDealAt(t97.getOrderAt());
        order.setStatus(30);
        Map<String, Object> map = new HashMap();
        map.put("historyOrder", 1);
        order.setExtraMap(map);
        order.setIsAlone(0);
        order.setRefundType(0);
        order.setRefundWay(2);
        order.setVersion(0);
        order.setIsDeleted(0);
        order.setIsDeleted(0);
        order.setFromSystem(1);
        order.setPayType(t97.getPayType());
        order.setReviewStatus(0);
        order.setGiftCardAmount(0);
        order.setPerformanceType(0);

        refundList.add(order);
        return order;
    }

    private void buildT97RefundItem(List<RefundItem> itemList, OrderT97 juiceOrder, Map<String, Refund> orderNoMap) {
        RefundItem orderItem = buildT97RefundItemValue(itemList, juiceOrder);
        Refund order = orderNoMap.get(juiceOrder.getOrderNo());
        if (Objects.nonNull(order)) {
            //商品实付金额累加
            if (Objects.nonNull(juiceOrder.getItemPrice())) {
                BigDecimal multiply = juiceOrder.getItemPrice().multiply(new BigDecimal(100));
                int intItemPrice = Double.valueOf(multiply.toString()).intValue();
                order.setRefundAmount(order.getRefundAmount() + intItemPrice);
                order.setAmount(order.getAmount() + intItemPrice);
            }
        }
        orderNoMap.put(juiceOrder.getOrderNo(), order);
    }

    private RefundItem buildT97RefundItemValue(List<RefundItem> itemList, OrderT97 juiceOrder) {
        int intDiscountAmount = 0;
        //当前商品优惠金
        if (Objects.nonNull(juiceOrder.getDiscountAmount())) {
            BigDecimal multiply = juiceOrder.getDiscountAmount().multiply(new BigDecimal(100));
            intDiscountAmount = Double.valueOf(multiply.toString()).intValue();
        }

        RefundItem item = new RefundItem();
        item.setId(generator.generateSnowflakeNumKey());
        item.setSellerId(T97sellerId);
        item.setBizType(5);
        item.setUserId(juiceOrder.getUserId());
        item.setRefundNo(juiceOrder.getOrderNo());
        item.setOrderNo(juiceOrder.getRefundOrderNo());

        // todo
        item.setOrderItemId(0L);
        item.setItemId(juiceOrder.getItemId());
        item.setGoodsId(juiceOrder.getGoodsId());
        item.setItemImage("");
        item.setItemSign(juiceOrder.getItemSign());

        item.setDiscountAmount(intDiscountAmount);


        if (StringUtils.isEmpty(juiceOrder.getItemName())) {
            item.setItemName("历史消费商品");
        } else {
            item.setItemName(juiceOrder.getItemName());
        }
        if (Objects.nonNull(juiceOrder.getNum())) {
            item.setNum(juiceOrder.getNum());
            item.setRefundNum(juiceOrder.getNum());
        } else {
            item.setRefundNum(new BigDecimal(1));
            item.setNum(new BigDecimal(1));
        }

        Integer refundAmount = 0;
        if (Objects.nonNull(juiceOrder.getItemPrice())) {
            BigDecimal multiply = juiceOrder.getItemPrice().multiply(new BigDecimal(100));
            refundAmount = Double.valueOf(multiply.toString()).intValue();
        }
        item.setRefundAmount(refundAmount);

        BigDecimal itemPrice = new BigDecimal(refundAmount + intDiscountAmount).divide(item.getNum(), 0, RoundingMode.DOWN);
        int intItemPrice = (Double.valueOf(itemPrice.toString()).intValue());
        item.setItemPrice(juiceOrder.getItemPriceNew());
        item.setItemSpec(null);
        item.setItemUnit("");
        item.setItemType(2);
        item.setRefundWay(2);
        item.setCreatedAt(juiceOrder.getOrderAt());

        item.setFeatures(null);
        item.setSellerId(T97sellerId);
        item.setItemType(0);
        itemList.add(item);
        return item;
    }

    private RefundItem buildT97RefundItem(List<RefundItem> itemList, OrderT97 juiceOrder) {
        RefundItem orderItem = buildT97RefundItemValue(itemList, juiceOrder);
        return orderItem;
    }

    private void buildT97RefundDetail(List<OrderRefundDetails> list, OrderT97 juiceOrder, Refund order) {
        //订单总金额 + 实付 + 每一笔的优惠
        Integer payAmount = 0;
        if (Objects.nonNull(juiceOrder.getPayAmount())) {
            BigDecimal multiply = juiceOrder.getPayAmount().multiply(new BigDecimal(100));
            payAmount = Double.valueOf(multiply.toString()).intValue();
        }

        OrderRefundDetails payDetails = new OrderRefundDetails();
        payDetails.setId(generator.generateSnowflakeNumKey());
        payDetails.setRefundNo(juiceOrder.getOrderNo());
        payDetails.setOrderNo(juiceOrder.getRefundOrderNo());
        payDetails.setUserId(juiceOrder.getUserId());
        payDetails.setStoreId(juiceOrder.getStoreId());
        payDetails.setSellerId(T97sellerId);
        payDetails.setPayType(juiceOrder.getPayType());
        payDetails.setRefundAmount(payAmount);
        payDetails.setBizType(5);


        list.add(payDetails);
        String payDetailInfo = JSON.toJSONString(Arrays.asList(mapper.map(payDetails, InnerOrderRefundDetail.class)));
        order.setRefundDetailInfo(payDetailInfo);
    }


    @Override
    public void delBaoZhu() {
        try {
            Long lastId = null;
            int size = 200;
            int count = 0;
            int orderCount = 0;
            for (; ; ) {
                List<BaoZhu> list = baoZhuDao.selectList(lastId, size);
                if (CollectionUtils.isEmpty(list)) {
                    break;
                }
                List<String> orderNoList = list.stream().map(BaoZhu::getOrderNo).collect(Collectors.toList());
                List<Long> userIdList = list.stream().map(BaoZhu::getUserId).collect(Collectors.toList());
                OrderQuery query = new OrderQuery();
                query.setUserIdList(userIdList);
                query.setOrderNoList(orderNoList);
                List<Order> orderList = orderDao.selectListByOrderNosUserIds(query);
                if (!CollectionUtils.isEmpty(orderList)) {
                    for (Order order : orderList) {
                        searchManager.deleteOrder(order.getId(), order.getSellerId());
                    }
                }
                orderDao.deleteByOrderNos(orderNoList, userIdList);
                orderItemDao.deleteByOrderNos(orderNoList, userIdList);
                payDao.deleteByOrderNos(orderNoList, userIdList);
                indexDao.realDeleteByOrderNoUserId(orderNoList, userIdList);
                discountDao.deleteByOrderNos(orderNoList, userIdList);

                refundDao.deleteByOrderNos(orderNoList);
                refundItemDao.deleteByOrderNos(orderNoList);
                detailsDao.deleteByOrderNos(orderNoList);

                lastId = list.get(list.size() - 1).getId();
                count = count + list.size();
                logger.info("delBaoZhu,count:{},lastId:{}, orderCount:{}", count, lastId, orderCount);
                if (list.size() < size) {
                    break;
                }
            }
        } catch (Throwable e) {
            logger.error("TempOrderServiceImplSync[delBaoZhu] failed!, cause by:{}", e);
        }
    }

    @Override
    public void orderT97SyncEs() {
        try {
            logger.info("orderT97SyncEs[start]");
            Long lastId = null;
            int size = 200;
            int count = 0;
            int refundFlag = 0;
            for (; ; ) {
                List<OrderT97> list = t97Dao.selectList(lastId, size, refundFlag);
//                List<BatchSyncEsMessage> messageList = new ArrayList<>(size);
                List<String> orderNoList = list.stream().map(OrderT97::getOrderNo).collect(Collectors.toList());
                List<Long> userIdList = list.stream().map(OrderT97::getUserId).collect(Collectors.toList());
                orderNoList.removeAll(Collections.singleton(null));
                userIdList.removeAll(Collections.singleton(null));
                OrderQuery query = new OrderQuery();
                if (CollectionUtils.isEmpty(userIdList)) {
                    continue;
                }
                query.setOrderNoList(orderNoList);
                query.setUserIdList(userIdList);
                // 订单可能已存在
                List<Order> orderList = orderDao.selectListByOrderNosUserIds(query);
                searchManager.indexOrder(orderList);
//                for (Order order : orderList) {
//                    messageList.add(buildMessage(order));
//                }
//                //同步ES
//                List<BatchSyncEsMessage> pushList = new ArrayList<>(size);
//                buildPushMessage(messageList, pushList);
//                messageManager.sendBatchSyncMessage(pushList);

                lastId = list.get(list.size() - 1).getId();
                count = count + list.size();
                logger.info("orderT97SyncEs,count:{},lastId:{}", count, lastId);
                if (list.size() < size) {
                    break;
                }
            }
        } catch (Throwable e) {
            logger.error("TempOrderServiceImplSync[orderT97SyncEs] failed!, cause by:{}", e);
        }
    }
}
