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

import com.alibaba.fastjson.JSON;
import com.github.dozermapper.core.Mapper;
import com.google.common.collect.Maps;
import com.zm.order.tool.server.component.ShardingKeyGenerator;
import com.zm.order.tool.server.dao.*;
import com.zm.order.tool.server.manager.AsyncMessageManager;
import com.zm.order.tool.server.manager.RedisManager;
import com.zm.order.tool.server.manager.SearchManager;
import com.zm.order.tool.server.manager.ThirdApiMessage;
import com.zm.order.tool.server.message.BatchSyncEsMessage;
import com.zm.order.tool.server.model.*;
import com.zm.order.tool.server.query.OrderQuery;
import com.zm.order.tool.server.service.ThirdOrderTransferService;
import com.zm.order.tool.server.tempdb.*;
import com.zm.util.dto.Result;
import org.apache.lucene.util.NamedThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

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

/**
 * @author nianchang
 * @ClassName ThirdOrderServiceImpl
 * @date 2021/11/08 10:56 上午
 */
@Service
@SuppressWarnings("all")
public class ThirdOrderTransferServiceImpl implements ThirdOrderTransferService, InitializingBean {

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

    @Autowired
    private ThirdApiMessage thirdApiMessage;

    @Autowired
    private ThirdOrderDao thirdOrderDao;

    @Autowired
    private ShardingKeyGenerator keyGenerator;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private OrderItemDao orderItemDao;
    @Autowired
    private OrderDiscountDao discountDao;
    @Autowired
    private OrderPayDetailsDao payDao;
    @Autowired
    private SearchManager searchManager;
    @Autowired
    private OrderIndexDao indexDao;

    private BlockingQueue workQueue;

    private ExecutorService executorService;
    @Autowired
    private UserCustomerDao customerDao;

    @Autowired
    private Mapper mapper;
    @Autowired
    private OrderOperationDao operationDao;

    @Autowired
    private AsyncMessageManager messageManager;

    @Autowired
    private OrderNuoWaDao orderNuoWaDao;

    @Autowired
    private OrderWuYinDao wuYinDao;

    @Autowired
    private OrderWuYinItemDao wuYinItemDao;

    @Autowired
    private OrderWuYinJiFenDao jiFenDao;

    @Autowired
    private RefundDao refundDao;

    @Autowired
    private OrderPayDetailsDao payDetailsDao;

    @Autowired
    private OrderRefundDetailsDao detailsDao;

    @Autowired
    private RefundItemDao refundItemDao;

    @Autowired
    private RedisManager redisManager;

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

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


    private OrderPayDetails buildPayDetail(OrderWuyin orderNuoWa, Order order) {
        OrderPayDetails payDetails = new OrderPayDetails();
        payDetails.setId(keyGenerator.generateSnowflakeNumKey());
        payDetails.setOrderNo(order.getOrderNo());
        payDetails.setUserId(order.getUserId());
        payDetails.setAmount(order.getPayAmount());
        payDetails.setPayType(order.getPayType());
        payDetails.setStoreId(order.getStoreId());
        payDetails.setSellerId(order.getSellerId());
        payDetails.setOrderAt(order.getOrderAt());
        payDetails.setPayAt(order.getOrderAt());
        payDetails.setOrderType(order.getOrderType());
        payDetails.setSource(order.getSource());
        payDetails.setBizType(order.getBizType());
        payDetails.setPerformanceType(order.getPerformanceType());
        payDetails.setPayNo("");
        payDetails.setThirdPayNo("");
        Map<String, Object> map = new HashMap();
        map.put("historyOrder", 1);
        payDetails.setExtraMap(map);
        String payDetailInfo = JSON.toJSONString(Arrays.asList(mapper.map(payDetails, InnerOrderPayDetails.class)));
        order.setPayDetailInfo(payDetailInfo);
        return payDetails;
    }

    private OrderIndex buildOrderIndex(Order order) {
        OrderIndex index = new OrderIndex();
        index.setId(keyGenerator.generateSnowflakeNumKey());
        index.setOrderNo(order.getOrderNo());
        index.setUserId(order.getUserId());
        index.setBizType(5);
        index.setOrderId(order.getId());
        return index;
    }

    //pro
//    private Long nuowaSellerId = 215925L;

    //beta
    private Long nuowaSellerId = 11478L;


    /**
     * 全部已支付  已完成  source 全部微信小程序
     */
    @Override
    public void nuowaOrder() {
        try {
            logger.info("nuowaOrder[start]");
            Long lastId = null;
            int size = 200;
            int count = 0;
            for (; ; ) {
                List<OrderNuoWa> list = orderNuoWaDao.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<OrderIndex> indexList = new ArrayList<>(size);
//                List<BatchSyncEsMessage> messageList = new ArrayList<>(size);

//                for (OrderNuoWa item : list) {
//                    //订单号不存在 ： 不迁移
//                    if (Objects.isNull(item.getOuttradeno())) {
//                        continue;
//                    }
//                    Order order = buildOrder(item);
//                    OrderItem orderItem = buildItem(item, order);
//                    OrderPayDetails orderPayDetails = buildPayDetail(item, order);
//                    OrderIndex orderIndex = buildOrderIndex(order);
//                    messageList.add(buildMessage(order));
//
//                    orderList.add(order);
//                    itemList.add(orderItem);
//                    payList.add(orderPayDetails);
//                    indexList.add(orderIndex);
//                }

                //批量新增订单
//                if (!CollectionUtils.isEmpty(orderList)) {
//                    orderDao.insertList(orderList);
//                }
//                // 新增订单索引
//                if (!CollectionUtils.isEmpty(indexList)) {
//                    indexDao.insertList(indexList);
//                }
//                //批量新增商品
//                if (!CollectionUtils.isEmpty(itemList)) {
//                    orderItemDao.inserts(itemList);
//                }
//                //批量新增支付明细
//                if (!CollectionUtils.isEmpty(payList)) {
//                    payDao.insertList(payList);
//                }
//                //同步ES
//                for (Order order : orderList) {
//                    searchManager.indexOrder(order, null);
//                }

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

                List<String> orderNoList = list.stream().map(OrderNuoWa::getOuttradeno).collect(Collectors.toList());
                List<Long> userIdList = list.stream().map(OrderNuoWa::getQmaiUserId).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) {
                        messageList.add(buildMessage(order));
                    }
                }

                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("nuowaOrder[running], count:{},lastId:{}", count, lastId);
                if (list.size() < size) {
                    break;
                }
            }
            logger.info("nuowaOrder[end], count:{},lastId:{}", count, lastId);

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


    private Order buildOrder(OrderWuyin item) {
        Order order = new Order();
        order.setId(keyGenerator.generateSnowflakeNumKey());
        order.setOrderNo(item.getOrderCode());
        order.setUserId(item.getUserId());
        order.setDiscountAmount(0);
        order.setActualAmount(0);
        order.setPayAmount(0);
        order.setItemAmount(0);
        order.setPayStatus(1);
        order.setStatus(70);
        order.setSource(item.getSource());
        order.setBizSubType(0);
        order.setPackAmount(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.setIsDeleted(0);
        order.setAddrId(0);
        order.setSyncFlag(0);
        order.setVersion(1);
        order.setPayFlag(1);
        order.setPayer(item.getUserId());
        order.setMobile(item.getMobile());
        order.setSellerId(wuYinSellerId);
        order.setStoreId(item.getStoreId());
        order.setOrderAt(item.getOrderAt());
        order.setCreatedAt(item.getOrderAt());
        order.setPayAt(item.getOrderAt());
        order.setCompletedAt(item.getOrderAt());
        order.setPayType(item.getPayType());
        order.setOrderType(item.getOrderType());
        order.setUpdatedAt(new Date());
        order.setFreightAmount(0);
        Map<String, Object> map = new HashMap();
        map.put("historyOrder", 1);
        Map<String, Object> userInfoMap = new HashMap();
        userInfoMap.put("phone", item.getMobile());
        userInfoMap.put("openId", "");
        userInfoMap.put("userName", "");
        userInfoMap.put("userId", item.getUserId());
        map.put("userInfo", userInfoMap);
        order.setExtraMap(map);
        //订单总金额
        if (Objects.nonNull(item.getTotalAmount())) {
            BigDecimal multiply = item.getTotalAmount().multiply(new BigDecimal(100));
            int intTotalAmount = Double.valueOf(multiply.toString()).intValue();
            order.setTotalAmount(intTotalAmount);
            order.setItemAmount(intTotalAmount);
        }
        //优惠金额
        if (Objects.nonNull(item.getDiscountAmount())) {
            BigDecimal multiply = item.getDiscountAmount().multiply(new BigDecimal(100));
            int intDiscountAmount = Double.valueOf(multiply.toString()).intValue();
            order.setDiscountAmount(intDiscountAmount);
        }
        //订单实付金额
        if (Objects.nonNull(item.getPayAmount())) {
            BigDecimal multiply = item.getPayAmount().multiply(new BigDecimal(100));
            int intPayAmount = Double.valueOf(multiply.toString()).intValue();
            order.setPayAmount(intPayAmount);
            order.setActualAmount(intPayAmount);
        }
        if (item.getPayType() == 4){
            Map<String, Object> payInfoMap = Maps.newHashMap();
            payInfoMap.put("useWallet", 1);
            payInfoMap.put("walletAmount", item.getPayAmount());
            payInfoMap.put("payDetailsList", Arrays.asList("余额支付: ¥" + item.getPayAmount()));
            order.setPayInfo(JSON.toJSONString(payInfoMap));
        }
        return order;
    }


    private void buildWuYinItem(OrderWuyin orderNuoWa, Order order, List<OrderItem> itemList){
        List<OrderWuyinItem> orderWuyinItems = wuYinItemDao.selectOne(order.getOrderNo());
        List<InnerOrderItem> innerOrderItemList = new ArrayList<>();
        if (CollectionUtils.isEmpty(orderWuyinItems)) {
            OrderItem orderItem = buildItem(orderNuoWa, order);
            innerOrderItemList.add(mapper.map(orderItem, InnerOrderItem.class));
            itemList.add(orderItem);
        } else {
            for (OrderWuyinItem item :orderWuyinItems){
                OrderItem orderItem = buildItem(orderNuoWa, order);
                orderItem.setItemName(item.getItemName());
                orderItem.setNum(new BigDecimal(item.getNum()));
                //商品成交价= 三方折扣单价
                int intDiscountAmount = 0;
                if (Objects.nonNull(item.getDiscountAmount())) {
                    BigDecimal multiply = item.getDiscountAmount().multiply(new BigDecimal(100));
                    intDiscountAmount = Double.valueOf(multiply.toString()).intValue();
                }
                // 商品单价 - 折后单价 = 优惠
                if (Objects.nonNull(item.getItemPrice())) {
                    BigDecimal multiply = item.getItemPrice().multiply(new BigDecimal(100));
                    int intItemAmount = Double.valueOf(multiply.toString()).intValue();
                    orderItem.setItemPrice(intItemAmount);
                    orderItem.setDiscountAmount(intItemAmount - intDiscountAmount);
                    orderItem.setMarketPrice(intItemAmount);
                }
                innerOrderItemList.add(mapper.map(orderItem, InnerOrderItem.class));
                itemList.add(orderItem);
            }
        }
        order.setItemInfo(JSON.toJSONString(innerOrderItemList));
    }


    private OrderItem buildItem(OrderWuyin orderNuoWa, Order order){
        OrderItem item = new OrderItem();
        item.setId(keyGenerator.generateSnowflakeNumKey());
        item.setBizType(5);
        item.setUserId(order.getUserId());
        item.setOrderNo(order.getOrderNo());
        item.setItemId("-1");
        item.setGoodsId(0L);
        item.setItemImage("https://images.qmai.cn/s11478/2023/04/10/498a55d18013365ae9.png");
        item.setItemName("历史迁移商品");
        item.setItemSign("");
        item.setDiscountAmount(0);
        item.setNum(new BigDecimal(1));
        item.setItemSpec(null);
        item.setItemUnit("");
        item.setBrandSign("");
        item.setMarketPrice(0);
        item.setCostPrice(0);
        item.setMemberPrice(0);
        item.setPackAmount(0);
        item.setfCode("");
        item.setStatus(0);
        item.setActivityId(0L);
        item.setIsTimeDiscount(0);
        item.setOrderAt(order.getOrderAt());
        item.setProductNo("");
        item.setIsGift(0);
        item.setSellerId(order.getSellerId());
        item.setItemType(0);
        item.setOwnerId(0L);
        item.setBatchingInfo("");
        Map<String, Object> map = new HashMap();
        map.put("historyOrder", 1);
        item.setExtraMap(map);
        //商品实付金额
        item.setItemPrice(order.getItemAmount());
        //市场价
        item.setMarketPrice(order.getItemAmount());
        item.setDiscountAmount(order.getDiscountAmount());
//        InnerOrderItem inner = mapper.map(item, InnerOrderItem.class);
//        List<InnerOrderItem> innerOrderItems = Arrays.asList(inner);
//        order.setItemInfo(JSON.toJSONString(innerOrderItems));
        return item;
    }

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

    //pro
    private Long wuYinSellerId = 215925L;

    //beta
//    private Long wuYinSellerId = 11478L;
    @Override
    public void wuYinOrder() {
        try {
            logger.info("wuYinOrder[start]");
            Long lastId = 0L;
            int count = 0;
            int size = 200;
            for (; ; ) {
                List<OrderWuyin> list = wuYinDao.selectList(lastId, size);
                if (CollectionUtils.isEmpty(list)) {
                    break;
                }
                Result<String> redisData = redisManager.get("stop-wuYin-Order");
                if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                    return;
                }
                while (workQueue.remainingCapacity() < 50) {
                    logger.info("wuYinOrderWorkQueue size:{}", workQueue.size());
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                executorService.submit(() -> {
                    doTransfer(list);
                });

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

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

    private void doTransfer(List<OrderWuyin> list) {
        try {
            int size = 200;
            List<Order> orderList = new ArrayList<>(size);
            List<OrderItem> itemList = new ArrayList<>(size);
            List<OrderPayDetails> payList = new ArrayList<>(size);
            List<OrderIndex> indexList = new ArrayList<>(size);
            List<OrderDiscount> discountList = new ArrayList<>(size);
            List<BatchSyncEsMessage> messageList = new ArrayList<>(size);

            for (OrderWuyin item : list) {
                //订单号不存在 ： 不迁移
                if (Objects.isNull(item.getOrderCode())) {
                    continue;
                }
                //退款不迁移
                if (Objects.equals("RETURN", item.getStatusTxt())) {
                    continue;
                }
                //门店不存在不迁移
                if (Objects.isNull(item.getStoreId())) {
                    continue;
                }
                Order order = buildOrder(item);
                buildWuYinItem(item, order, itemList);
                OrderPayDetails orderPayDetails = buildPayDetail(item, order);
                OrderIndex orderIndex = buildOrderIndex(order);
                OrderDiscount orderDiscount = buildDiscount(item, order);
                messageList.add(buildMessage(order));

                orderList.add(order);
                payList.add(orderPayDetails);
                if (Objects.nonNull(orderDiscount)) {
                    discountList.add(orderDiscount);
                }
                indexList.add(orderIndex);
                messageList.add(buildMessage(order));
            }

            //新增订单
            if (!CollectionUtils.isEmpty(orderList)) {
                orderDao.insertList(orderList);
            }
            // 新增订单索引
            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);
            }
            searchManager.indexOrder(orderList);
            logger.info("wuYinOrder[doTransfer], ThreadName:{},lastId:{}", Thread.currentThread().getName(), list.get(list.size() - 1).getId());

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

    private OrderDiscount buildDiscount(OrderWuyin orderNuoWa, Order order) {
        if (Objects.isNull(order.getDiscountAmount())) {
            return null;
        }
        if (order.getDiscountAmount() <= 0) {
            return null;
        }
        OrderDiscount discount = new OrderDiscount();
        discount.setId(keyGenerator.generateSnowflakeNumKey());
        discount.setBizType(5);
        discount.setUserId(order.getUserId());
        discount.setOrderNo(order.getOrderNo());
        discount.setSellerId(order.getSellerId());
        discount.setStatus(0);
        discount.setItemId("-1");
        discount.setDiscountLevel(0);
        discount.setDiscountId("-1");
        discount.setDiscountType(2);
        discount.setDiscountName("优惠券");
        discount.setDiscountSummary("优惠券");
        Map<String, Object> map = new HashMap();
        map.put("historyOrder", 1);
        discount.setExtraMap(map);
        discount.setDiscountAmount(order.getDiscountAmount());
        String discountInfo = JSON.toJSONString(Arrays.asList(mapper.map(discount, InnerOrderDiscount.class)));
        order.setDiscountInfo(discountInfo);
        return discount;
    }

    @Override
    public void delWuyinOrder() {
        try {
            Long lastId = 0L;
            int size = 200;
            int count = 0;
            int orderCount = 0;
            for (; ; ) {
                List<OrderWuyin> list = wuYinDao.selectList(lastId, size);
                if (CollectionUtils.isEmpty(list)) {
                    break;
                }
                Result<String> redisData = redisManager.get("stop-wuYin-Order");
                if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                    return;
                }
                while (workQueue.remainingCapacity() < 50) {
                    logger.info("delWuyinOrderWorkQueue size:{}", workQueue.size());
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                executorService.submit(() -> {
                    doDel(list);
                });
                lastId = list.get(list.size() - 1).getId();
                count = count + list.size();
                logger.info("delWuyinOrder,count:{},lastId:{}, orderCount:{}", count, lastId, orderCount);
                if (list.size() < size) {
                    break;
                }
            }
        } catch (Throwable e) {
            logger.error("TempOrderServiceImplSync[delWuyinOrder] failed!, cause by:{}", e);
        }
    }

    private void doDel(List<OrderWuyin> list){
        List<String> orderNoList = list.stream().map(OrderWuyin::getOrderCode).collect(Collectors.toList());
        List<Long> userIdList = list.stream().map(OrderWuyin::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);
        discountDao.deleteByOrderNos(orderNoList, userIdList);
        indexDao.realDeleteByOrderNoUserId(orderNoList, userIdList);
        discountDao.deleteByOrderNos(orderNoList, userIdList);

        refundDao.deleteByOrderNos(orderNoList);
        refundItemDao.deleteByOrderNos(orderNoList);
        detailsDao.deleteByOrderNos(orderNoList);
        logger.info("wuYinOrderDel[doDel], ThreadName:{},lastId:{}", Thread.currentThread().getName(), list.get(list.size() - 1).getId());
    }

    @Override
    public void wuYinOrderJiFeng() {
        try {
            logger.info("wuYinOrderJiFeng[start]");
            Long lastId = null;
            int size = 200;
            int count = 0;
            for (; ; ) {
                List<OrderWuyinJiFen> list = jiFenDao.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<OrderIndex> indexList = new ArrayList<>(size);
                List<OrderDiscount> discountList = new ArrayList<>(size);
                List<BatchSyncEsMessage> messageList = new ArrayList<>(size);

                for (OrderWuyinJiFen item : list) {
                    //无用户id不迁移
                    if (Objects.isNull(item.getUserId())) {
                        continue;
                    }
                    Order order = buildOrderJi(item);
                    OrderItem orderItem = buildItemJi(item, order);
                    OrderPayDetails orderPayDetails = buildPayDetailJi(item, order);
                    OrderIndex orderIndex = buildOrderIndex(order);
                    OrderDiscount orderDiscount = buildDiscountJi(item, order);
                    messageList.add(buildMessage(order));

                    orderList.add(order);
                    itemList.add(orderItem);
                    payList.add(orderPayDetails);
                    if (Objects.nonNull(orderDiscount)) {
                        discountList.add(orderDiscount);
                    }
                    indexList.add(orderIndex);
                    messageList.add(buildMessage(order));
                }

                //新增订单
                if (!CollectionUtils.isEmpty(orderList)) {
                    orderDao.insertList(orderList);
                }
                // 新增订单索引
                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);
                }

                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("wuYinOrderJiFeng[running], count:{},lastId:{}", count, lastId);
                if (list.size() < size) {
                    break;
                }
            }
            logger.info("wuYinOrderJiFeng[end], count:{},lastId:{}", count, lastId);

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


    private Order buildOrderJi(OrderWuyinJiFen item) {
        Order order = new Order();
        order.setId(keyGenerator.generateSnowflakeNumKey());
        order.setOrderNo(item.getOrderNo());
        order.setUserId(item.getUserId());
        order.setDiscountAmount(0);
        order.setActualAmount(0);
        order.setPayAmount(0);
        order.setItemAmount(0);
        order.setPayStatus(1);
        order.setStatus(70);
        order.setSource(1);
        order.setBizSubType(0);
        order.setPackAmount(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.setIsDeleted(0);
        order.setAddrId(0);
        order.setSyncFlag(0);
        order.setVersion(1);
        order.setPayFlag(1);
        order.setPayer(item.getUserId());
        order.setMobile(item.getMobile());
        order.setSellerId(wuYinSellerId);
        order.setStoreId(0L);
        order.setOrderAt(item.getOrderAt());
        order.setCreatedAt(item.getOrderAt());
        order.setPayAt(item.getOrderAt());
        order.setCompletedAt(item.getOrderAt());
        order.setPayType(16);
        order.setOrderType(20);
        order.setOrderSubType(29);
        order.setUpdatedAt(new Date());
        order.setFreightAmount(0);
        Map<String, Object> map = new HashMap();
        map.put("historyOrder", 1);
        order.setExtraMap(map);
        //订单总金额
        order.setTotalAmount(0);
        order.setItemAmount(0);
        order.setDiscountAmount(0);
        order.setPayAmount(0);
        order.setActualAmount(0);
        return order;
    }

    private OrderItem buildItemJi(OrderWuyinJiFen orderNuoWa, Order order){
        OrderItem item = new OrderItem();
        item.setId(keyGenerator.generateSnowflakeNumKey());
        item.setBizType(5);
        item.setUserId(order.getUserId());
        item.setOrderNo(order.getOrderNo());
        item.setItemId("-1");
        item.setGoodsId(0L);
        item.setItemImage("https://images.qmai.cn/s11476/2023/03/24/981acd198932548af4.jpg");
        item.setItemName(orderNuoWa.getItemName());
        if (StringUtils.isEmpty(item.getItemName())) {
            item.setItemName("历史迁移商品");
        }
        item.setItemSign("");
        item.setDiscountAmount(0);
        item.setNum(new BigDecimal(1));
        item.setItemSpec(null);
        item.setItemUnit("");
        item.setBrandSign("");
        item.setMarketPrice(0);
        item.setCostPrice(0);
        item.setMemberPrice(0);
        item.setPackAmount(0);
        item.setfCode("");
        item.setStatus(0);
        item.setActivityId(0L);
        item.setIsTimeDiscount(0);
        item.setOrderAt(order.getOrderAt());
        item.setProductNo("");
        item.setIsGift(0);
        item.setSellerId(order.getSellerId());
        item.setItemType(0);
        item.setOwnerId(0L);
        item.setBatchingInfo("");
        Map<String, Object> map = new HashMap();
        map.put("historyOrder", 1);
        map.put("pointsPrice", orderNuoWa.getPoint());
        map.put("pointNum", orderNuoWa.getPoint());
        item.setExtraMap(map);
        //商品实付金额
        item.setItemPrice(order.getItemAmount());
        //市场价
        item.setMarketPrice(order.getItemAmount());
        item.setDiscountAmount(order.getDiscountAmount());
        InnerOrderItem inner = mapper.map(item, InnerOrderItem.class);
        List<InnerOrderItem> innerOrderItems = Arrays.asList(inner);
        order.setItemInfo(JSON.toJSONString(innerOrderItems));
        return item;
    }


    private OrderPayDetails buildPayDetailJi(OrderWuyinJiFen orderNuoWa, Order order) {
        OrderPayDetails payDetails = new OrderPayDetails();
        payDetails.setId(keyGenerator.generateSnowflakeNumKey());
        payDetails.setOrderNo(order.getOrderNo());
        payDetails.setUserId(order.getUserId());
        payDetails.setAmount(order.getPayAmount());
        payDetails.setPayType(order.getPayType());
        payDetails.setStoreId(order.getStoreId());
        payDetails.setSellerId(order.getSellerId());
        payDetails.setOrderAt(order.getOrderAt());
        payDetails.setPayAt(order.getOrderAt());
        payDetails.setOrderType(order.getOrderType());
        payDetails.setSource(order.getSource());
        payDetails.setBizType(order.getBizType());
        payDetails.setPerformanceType(order.getPerformanceType());
        payDetails.setPayNo("");
        payDetails.setThirdPayNo("");
        Map<String, Object> map = new HashMap();
        map.put("historyOrder", 1);
        payDetails.setExtraMap(map);
        String payDetailInfo = JSON.toJSONString(Arrays.asList(mapper.map(payDetails, InnerOrderPayDetails.class)));
        order.setPayDetailInfo(payDetailInfo);
        return payDetails;
    }


    private OrderDiscount buildDiscountJi(OrderWuyinJiFen jiFen, Order order) {
        OrderDiscount discount = new OrderDiscount();
        discount.setId(keyGenerator.generateSnowflakeNumKey());
        discount.setBizType(5);
        discount.setUserId(order.getUserId());
        discount.setOrderNo(order.getOrderNo());
        discount.setSellerId(order.getSellerId());
        discount.setStatus(0);
        discount.setItemId("-1");
        discount.setDiscountLevel(1);
        discount.setDiscountId("-1");
        discount.setDiscountType(20);
        discount.setDiscountName("积分商品");
        discount.setDiscountSummary("积分商品");
        Map<String, Object> map = new HashMap();
        map.put("historyOrder", 1);
        map.put("pointNum", jiFen.getPoint());
        discount.setExtraMap(map);
        discount.setDiscountAmount(order.getDiscountAmount());
        String discountInfo = JSON.toJSONString(Arrays.asList(mapper.map(discount, InnerOrderDiscount.class)));
        order.setDiscountInfo(discountInfo);
        return discount;
    }

    @Override
    public void delWuyinOrderJiFeng() {
        try {
            Long lastId = 0L;
            int size = 200;
            int count = 0;
            int orderCount = 0;
            for (; ; ) {
                List<OrderWuyinJiFen> list = jiFenDao.selectList(lastId, size);
                if (CollectionUtils.isEmpty(list)) {
                    break;
                }
                List<String> orderNoList = list.stream().map(OrderWuyinJiFen::getOrderNo).collect(Collectors.toList());
                List<Long> userIdList = list.stream().map(OrderWuyinJiFen::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);
                discountDao.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("delWuyinOrderJiFeng,count:{},lastId:{}, orderCount:{}", count, lastId, orderCount);
                if (list.size() < size) {
                    break;
                }
            }
        } catch (Throwable e) {
            logger.error("TempOrderServiceImplSync[delWuyinOrder] failed!, cause by:{}", e);
        }
    }
}

