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

import com.alibaba.fastjson.JSON;
import com.aliyun.openservices.shade.com.google.common.collect.Maps;
import com.github.dozermapper.core.Mapper;
import com.google.common.collect.Lists;
import com.zm.order.tool.server.component.ShardingKeyGenerator;
import com.zm.order.tool.server.constants.CommonConstants;
import com.zm.order.tool.server.constants.StoreIdMap;
import com.zm.order.tool.server.constants.XueliStoreIdMap;
import com.zm.order.tool.server.dao.*;
import com.zm.order.tool.server.enums.BizTypeEnum;
import com.zm.order.tool.server.hint.HintOrderDao;
import com.zm.order.tool.server.inner.ThirdApiRequest;
import com.zm.order.tool.server.manager.*;
import com.zm.order.tool.server.message.BatchSyncEsMessage;
import com.zm.order.tool.server.message.CommentDocumentMessage;
import com.zm.order.tool.server.message.MallTransferMessage;
import com.zm.order.tool.server.model.*;
import com.zm.order.tool.server.query.OrderPayDetailsQuery;
import com.zm.order.tool.server.query.OrderQuery;
import com.zm.order.tool.server.query.RefundQuery;
import com.zm.order.tool.server.service.ExceptionConstants;
import com.zm.order.tool.server.service.ThirdOrderService;
import com.zm.order.tool.server.tempdb.BaoZhuDao;
import com.zm.order.tool.server.tempdb.IdOrderNoDao;
import com.zm.order.tool.server.tempdb.ThirdOrderDao;
import com.zm.order.tool.server.tempdb.UserCustomerDao;
import com.zm.order.tool.server.utils.CommonUtils;
import com.zm.order.tool.server.utils.ConvertUtils;
import com.zm.order.tool.server.utils.DateUtils;
import com.zm.util.dto.Result;
import org.apache.lucene.util.NamedThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

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

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

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

    @Autowired
    private ThirdApiMessage thirdApiMessage;

    @Autowired
    private ThirdOrderDao thirdOrderDao;

    @Autowired
    private Mapper mapper;
    @Autowired
    private ShardingKeyGenerator keyGenerator;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private IdOrderNoDao idOrderNoDao;
    @Autowired
    private OrderItemDao itemDao;
    @Autowired
    private OrderDiscountDao discountDao;
    @Autowired
    private OrderPayDetailsDao payDetailsDao;
    @Autowired
    private SearchManager searchManager;
    @Autowired
    private OrderIndexDao indexDao;

    private BlockingQueue workQueue;

    private ExecutorService executorService;
    @Autowired
    private UserCustomerDao customerDao;

    @Autowired
    private OrderOperationDao operationDao;

    @Autowired
    private BaoZhuDao baoZhuDao;

    @Autowired
    private OrderManager orderManager;

    @Autowired
    private HintOrderDao hintOrderDao;

    @Autowired
    private RefundDao refundDao;

    @Autowired
    private RefundItemDao refundItemDao;

    @Autowired
    private OrderRefundDetailsDao refundDetailsDao;

    @Autowired
    private CommonManager commonManager;
    @Autowired
    private PerformanceSelfTakeDao takeDao;

    @Autowired
    private AsyncMessageManager messageManager;
    @Autowired
    private OrderCommentDao commentDao;
    @Autowired
    private OrderItemCommentDao itemCommentDao;

    @Autowired
    private SearchCommentManager commentManager;

    private static final String DOMAIN_NAME = "https://kypopenapi.cloud.seltek.cn";

    private static final String URL = "/openapi/order/getOrderPages";

    private static final String KEY = "key";

    private static final String VALUE = "51e561a1e0110ebb172477e8ebedeef8";

    @Override
    public Result xueliOrder() {
        int count = 0;
        try {
            Long lastId = null;
            for (; ; ) {
                List<UserCustomerIdMap> list = customerDao.selectList(lastId);
                if (CollectionUtils.isEmpty(list)) {
                    break;
                }
                list.forEach(this::doExecute);
                count += list.size();
                logger.info("xueliOrder_count:{}条", count);
                if (list.size() < 200) {
                    break;
                }
                lastId = list.get(list.size() - 1).getUserId();
                logger.info("xueliOrder_lastId:{}", lastId);
            }
        } catch (Exception e) {
            logger.error("xueliOrderError！, cause by:{}", e);
        }
        return Result.successNullData();
    }

    private void doExecute(UserCustomerIdMap onu) {
        while (workQueue.remainingCapacity() < 1000) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executorService.submit(() -> {
            try {
                Map<String, Object> param = new LinkedHashMap<>(4);
                long startAt = System.currentTimeMillis();
                logger.info("doExecute！userId:{}", onu.getUserId());
                Long userId = Long.valueOf(onu.getUserId());
                int currentPage = 1;
                logger.info("execute_time:{}ms", System.currentTimeMillis() - startAt);

                List<ThirdOrder> list = new ArrayList<>();

                param.put("currentPage", currentPage);
                param.put("memberId", userId);
                param.put("pageSize", 10000);
                long startAt1 = System.currentTimeMillis();
                Map<String, Object> dataMap = obtainOrderList0(param);
                if (CollectionUtils.isEmpty(dataMap)) {
                    return;
                }

                if (!StringUtils.isEmpty(dataMap.get("result"))) {
                    List<XueliOrder> orderList = JSON.parseArray(dataMap.get("result").toString(), XueliOrder.class);
                    orderList.forEach(order -> {
                        ThirdOrder thirdOrder = new ThirdOrder();
                        thirdOrder.setMobile(onu.getPhone());
                        thirdOrder.setUserId(Objects.nonNull(onu.getCustomerId()) ?
                                Long.valueOf(onu.getCustomerId()) : 0L);
                        thirdOrder.setOrderData(JSON.toJSONString(order));
                        list.add(thirdOrder);
                    });
                }

                Integer totalPage = getTotalPage(dataMap);
                if (Objects.nonNull(totalPage) && totalPage > 1) {
                    currentPage++;
                    for (int i = currentPage; i <= totalPage; i++) {
                        param.put("currentPage", currentPage);
                        List<XueliOrder> orderList = this.obtainOrderList(param);
                        logger.info("query_time:{}ms", System.currentTimeMillis() - startAt1);
                        orderList.forEach(order -> {
                            ThirdOrder thirdOrder = new ThirdOrder();
                            thirdOrder.setMobile(onu.getPhone());
                            thirdOrder.setUserId(Objects.nonNull(onu.getCustomerId()) ?
                                    Long.valueOf(onu.getCustomerId()) : 0L);
                            thirdOrder.setOrderData(JSON.toJSONString(order));
                            list.add(thirdOrder);
                        });
                    }
                }
                if (!CollectionUtils.isEmpty(list)) {
                    thirdOrderDao.insertList(list);
                }
            } catch (Exception e) {
                logger.error("doExecute！param:{}, cause by:{}", onu, e);
            }
        });
    }

    private Integer getTotalPage(Map<String, Object> dataMap) {
        Integer totalPage = null;
        if (!CollectionUtils.isEmpty(dataMap)) {
            if (Objects.nonNull(dataMap.get("pageInfo"))) {
                Map<String, Object> pageInfo = JSON.parseObject(dataMap.get("pageInfo").toString());
                if (!CollectionUtils.isEmpty(pageInfo)) {
                    if (Objects.nonNull(pageInfo.get("totalPage"))) {
                        totalPage = Integer.valueOf(pageInfo.get("totalPage").toString());
                    }
                }
            }
        }
        return totalPage;
    }

    private List<XueliOrder> obtainOrderList(Map<String, Object> param) {
        ThirdApiRequest request = thirdApiMessage.buildRequest(DOMAIN_NAME, URL, param, buildHeaderMap(), KEY, VALUE);
        Result result = thirdApiMessage.request(request);
        if (!StringUtils.isEmpty(result.getData())) {
            Map<String, Object> jsonMap = JSON.parseObject(result.getData().toString());
            if (!StringUtils.isEmpty(jsonMap.get("result"))) {
                return JSON.parseArray(jsonMap.get("result").toString(), XueliOrder.class);
            }
        }
        return Collections.EMPTY_LIST;
    }

    private Map<String, Object> obtainOrderList0(Map<String, Object> param) {
        ThirdApiRequest request = thirdApiMessage.buildRequest(DOMAIN_NAME, URL, param, buildHeaderMap(), KEY, VALUE);
        Result result = thirdApiMessage.request(request);
        if (!StringUtils.isEmpty(result.getData())) {
            return JSON.parseObject(result.getData().toString());
        }
        return Collections.EMPTY_MAP;
    }

    private Map<String, String> buildHeaderMap() {
        Map<String, String> headers = Maps.newHashMap();
        headers.put("tenantId", "1");
        headers.put("channelId", "610");
        return headers;
    }

    @Override
    public Result xueliOrderTransfer() {
        int count = 0;
        try {
            Long lastId = null;
            for (; ; ) {
                List<ThirdOrder> thirdOrderList = thirdOrderDao.scanList(lastId);
                if (CollectionUtils.isEmpty(thirdOrderList)) {
                    break;
                }
                doExecute0(thirdOrderList);
                count += thirdOrderList.size();
                logger.info("xueliOrderTransfer_count:{}条", count);
                if (thirdOrderList.size() < 200) {
                    break;
                }
                lastId = thirdOrderList.get(thirdOrderList.size() - 1).getId();
                logger.info("xueliOrderTransfer_lastId:{}条", lastId);
            }
        } catch (Exception e) {
            logger.error("xueliOrderTransfer！cause by:{}", e);
        }
        return Result.successNullData();
    }

    @Override
    public Result updateUserId() {
        Long lastId = null;
        int count = 0;
        for (; ; ) {
            List<UserCustomerIdMap> customerIdList = customerDao.selectList(lastId);
            if (CollectionUtils.isEmpty(customerIdList)) {
                break;
            }
            count += customerIdList.size();
            logger.info("updateUserId_count:{}条", count);
            if (customerIdList.size() < 200) {
                break;
            }
            lastId = customerIdList.get(customerIdList.size() - 1).getUserId();
        }
        return Result.successNullData();
    }

    @Override
    public Result updateStore() {
        int count = 0;
        try {
            Long lastId = null;
            for (; ; ) {
                List<ThirdOrder> thirdOrderList = thirdOrderDao.scanList(lastId);
                if (CollectionUtils.isEmpty(thirdOrderList)) {
                    break;
                }
                doExecute1(thirdOrderList);
                count += thirdOrderList.size();
                logger.info("updateStore_count:{}条", count);
                if (thirdOrderList.size() < 200) {
                    break;
                }
                lastId = thirdOrderList.get(thirdOrderList.size() - 1).getId();
                logger.info("updateStore_lastId:{}条", lastId);
            }
        } catch (Exception e) {
            logger.error("updateStore！cause by:{}", e);
            return Result.failureData(ExceptionConstants.SYSTEM_ERROR);
        }
        return Result.successNullData();
    }

    private void doExecute1(List<ThirdOrder> thirdOrderList) {
        while (workQueue.remainingCapacity() < 20) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executorService.submit(() -> {
            try {
                List<Order> orderList = new ArrayList<>(thirdOrderList.size());
                List<BatchSyncEsMessage> messageList = new ArrayList<>(200);
                for (ThirdOrder thirdOrder : thirdOrderList) {
                    build1(thirdOrder, orderList);
                }
                if (!CollectionUtils.isEmpty(orderList)) {
                    for (Order order : orderList) {
                        orderDao.updateStoreId(order);
                        messageList.add(buildMessage(order));
                    }
                }
                if (!CollectionUtils.isEmpty(messageList)) {
                    messageManager.sendBatchSyncMessage(messageList);
                }
            } catch (Exception e) {
                logger.error("doExecute！param:{}, cause by:{}", thirdOrderList, e);
            }
        });
    }

    private void build1(ThirdOrder thirdOrder, List<Order> orderList) {
        Long userId = thirdOrder.getUserId();
        String orderData = thirdOrder.getOrderData();
        if (StringUtils.isEmpty(orderData)) {
            return;
        }
        XueliOrder xueliOrder = JSON.parseObject(orderData, XueliOrder.class);
        // 订单
        Order order = buildOrder1(xueliOrder, userId);
        Order existedOrder = orderDao.selectByOrderNo(order.getOrderNo(), order.getUserId());
        if (existedOrder != null) {
            existedOrder.setStoreId(order.getStoreId());
            orderList.add(existedOrder);
        }
    }

    private Order buildOrder1(XueliOrder xueliOrder, Long userId) {
        Order order = new Order();
        order.setUserId(userId);
        order.setOrderNo(xueliOrder.getExternalId().substring(0, 16));
        Long storeId = 0L;
        String storeCode = XueliStoreIdMap.map.get(xueliOrder.getStoreId());
        if (!StringUtils.isEmpty(storeCode)) {
            Long aLong = StoreIdMap.map.get(storeCode);
            if (Objects.nonNull(aLong)) {
                storeId = aLong;
            }
        }
        order.setStoreId(storeId);
        return order;
    }

    private void doExecute0(List<ThirdOrder> thirdOrderList) {
        while (workQueue.remainingCapacity() < 20) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executorService.submit(() -> {
            try {
                List<Order> orderList = new ArrayList<>(thirdOrderList.size());
                List<OrderItem> itemList = new ArrayList<>(thirdOrderList.size());
                List<OrderDiscount> discountList = new ArrayList<>(thirdOrderList.size());
                List<OrderPayDetails> payDetailsList = new ArrayList<>(thirdOrderList.size());
                List<OrderIndex> indexList = new ArrayList<>(thirdOrderList.size());
                List<OrderOperation> operationList = new ArrayList<>(thirdOrderList.size());
                List<BatchSyncEsMessage> messageList = new ArrayList<>(200);

                for (ThirdOrder thirdOrder : thirdOrderList) {
                    build(thirdOrder, orderList, itemList, discountList, payDetailsList, indexList, operationList);
                }
                if (!CollectionUtils.isEmpty(orderList)) {
                    orderList.forEach(order -> messageList.add(buildMessage(order)));
                    orderDao.insertList(orderList);
                }
                if (!CollectionUtils.isEmpty(itemList)) {
                    itemDao.inserts(itemList);
                }
                if (!CollectionUtils.isEmpty(discountList)) {
                    discountDao.inserts(discountList);
                }
                if (!CollectionUtils.isEmpty(payDetailsList)) {
                    payDetailsDao.insertList(payDetailsList);
                }
                if (!CollectionUtils.isEmpty(indexList)) {
                    indexDao.insertList(indexList);
                }
                if (!CollectionUtils.isEmpty(messageList)) {
                    messageManager.sendBatchSyncMessage(messageList);
                }
                if (!CollectionUtils.isEmpty(operationList)) {
                    operationDao.insertList(operationList);
                }
            } catch (Exception e) {
                logger.error("doExecute！param:{}, cause by:{}", thirdOrderList, e);
            }
        });
    }

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

    private void build(ThirdOrder thirdOrder, List<Order> orderList, List<OrderItem> itemList,
                       List<OrderDiscount> discountList, List<OrderPayDetails> payDetailsList, List<OrderIndex> indexList,
                       List<OrderOperation> operationList) {
        final Long userId = thirdOrder.getUserId();
        String orderData = thirdOrder.getOrderData();
        if (StringUtils.isEmpty(orderData)) {
            return;
        }
        XueliOrder xueliOrder = JSON.parseObject(orderData, XueliOrder.class);
        // 订单
        Order order = buildOrder(xueliOrder, userId, thirdOrder.getMobile());
        Order existedOrder = orderDao.selectByOrderNo(order.getOrderNo(), order.getUserId());
        if (existedOrder != null) {
            return;
        }
        orderList.add(order);
        // 商品
        List<OrderItem> itemListByOne = new ArrayList<>();
        List<XueliOrderItem> xueliItem = xueliOrder.getOrderItemList();
        if (CollectionUtils.isEmpty(xueliItem)) {
            OrderItem orderItem = buildItem(order);
            itemList.add(orderItem);
            itemListByOne.add(orderItem);
            order.setItemInfo(JSON.toJSONString(itemListByOne));
        } else {
            buildItem(itemList, xueliItem, order, itemListByOne);
            if (itemListByOne.size() > 10) {
                order.setItemInfo("TL");
            } else {
                order.setItemInfo(JSON.toJSONString(itemListByOne));
            }
        }
        // 优惠
        List<OrderDiscount> discountListByOne = new ArrayList<>();
        List<XueliOrderDiscount> xueliDiscount = xueliOrder.getDiscountList();
        if (!CollectionUtils.isEmpty(xueliDiscount)) {
            buildDiscount(discountList, xueliDiscount, order, discountListByOne);
            order.setDiscountInfo(JSON.toJSONString(discountListByOne));
        }
        // 支付
        List<OrderPayDetails> payDetailsListByOne = new ArrayList<>();
        buildPayDetail(payDetailsList, order, payDetailsListByOne);
        order.setPayDetailInfo(JSON.toJSONString(payDetailsListByOne));
        // 索引
        OrderIndex orderIndex = buildOrderIndex(order);
        indexList.add(orderIndex);
        // 操作日志
        OrderOperation operation = buildOperation(order);
        operationList.add(operation);
    }

    private OrderItem buildItem(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.setItemName("普通商品");
        item.setItemImage("https://images.qmai.cn/s203007/2021/11/15/116211446400673bd8.png");
        item.setItemSpec("");
        item.setItemUnit("");
        item.setBrandSign("");
        item.setMarketPrice(0);
        item.setCostPrice(0);
        item.setMemberPrice(0);
        item.setItemPrice(0);
        item.setNum(new BigDecimal(1));
        item.setDiscountAmount(0);
        item.setPackAmount(0);
        item.setfCode("");
        item.setStatus(0);
        item.setFeatures("");
        item.setGoodsId(0L);
        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("");
        return item;
    }

    private OrderOperation buildOperation(Order order) {
        OrderOperation operation = new OrderOperation();
        operation.setBeforeStatus(10);
        operation.setAfterStatus(70);
        operation.setId(keyGenerator.generateSnowflakeNumKey());
        operation.setUserId(order.getUserId());
        operation.setOrderNo(order.getOrderNo());
        operation.setRole(1);
        operation.setOperation("orderTransfer");
        operation.setOperator(0L);
        operation.setOperateAt(order.getCompletedAt());
        operation.setDataSourceType(0);
        Map<String, Object> extraMap = new HashMap<>();
        Map<String, Object> operateInfo = new HashMap<>();
        operateInfo.put("statusText", "已关闭");
        operateInfo.put("statusUpdate", 1);
        operateInfo.put("operateMessage", "历史订单迁移");
        extraMap.put("operateInfo", operateInfo);
        operation.setExtraMap(extraMap);
        return operation;
    }

    private Order buildOrder(XueliOrder xueliOrder, Long userId, String mobile) {
        Order order = new Order();
        order.setId(keyGenerator.generateSnowflakeNumKey());
        order.setBizType(5);
        order.setBizSubType(0);
        order.setUserId(userId);
        order.setOrderNo(xueliOrder.getExternalId().substring(0, 16));
        // 统一映射成堂食
        order.setOrderType(1);
        order.setOrderSubType(0);
        //
        order.setSellerId(209562L);
        //
        Long newStoreId = StoreIdMap.map.get(xueliOrder.getStoreId());
        order.setStoreId(newStoreId != null ? newStoreId : 0L);
        order.setStoreOrderNo("GYP");
        order.setMobile(mobile);
        order.setAddrId(0);
        order.setSource(mapSource(xueliOrder.getChannelId()));
        order.setSourceNo(xueliOrder.getExternalId());
        order.setFromSystem(0);
        order.setSourceInfo("");
        Integer totalAmount = Objects.nonNull(xueliOrder.getOrderAmount()) ? xueliOrder.getOrderAmount() : 0;
        Integer deliveryAmount = Objects.nonNull(xueliOrder.getDeliveryAmount()) ? xueliOrder.getDeliveryAmount() : 0;
        Integer couponAmount = Objects.nonNull(xueliOrder.getCouponAmount()) ? xueliOrder.getCouponAmount() : 0;
        Integer payAmount = Objects.nonNull(xueliOrder.getPayAmount()) ? xueliOrder.getPayAmount() : 0;
        order.setTotalAmount(totalAmount);
        order.setCostAmount(0);
        order.setPackAmount(0);
        order.setItemAmount(totalAmount - deliveryAmount);
        order.setFreightAmount(deliveryAmount);
        order.setDiscountAmount(couponAmount);
        order.setActualAmount(payAmount);
        order.setPayAmount(payAmount);
        order.setChangeAmount(0);
        order.setIsAlone(0);
        // 统一映射成在线支付
        order.setPayType(7);
        order.setPayModel(0);
        order.setPayer(userId);
        order.setPayNo("");
        order.setThirdPayNo("");
        Map<String, Object> payInfo = new HashMap<>();
        payInfo.put("useWallet", 0);
        payInfo.put("amount", payAmount / 100);
        payInfo.put("walletAmount", 0);
        payInfo.put("payDetailsList", Lists.newArrayList("在线支付: ¥" + payAmount / 100));
        order.setPayInfo(JSON.toJSONString(payInfo));

        order.setInvoiceType(0);
        order.setPerformanceType(0);
        order.setPerformancePlatform("");
        order.setIsImmediatePerformance(0);
        order.setPerformanceInfo("");
        order.setActivityInfo("");
        order.setSellerRemarks("");
        order.setBuyerRemarks("");
        order.setIsReceipt(0);
        order.setReceiptTerminal("");
        order.setStatus(70);
        order.setPayStatus(1);
        order.setAfterSaleStatus(0);
        order.setPerformanceStatus(0);
        order.setCommentStatus(0);
        order.setReceiveStatus(0);
        order.setRefusalReason("");
        order.setOrderAt(xueliOrder.getOrderTime());
        order.setPayAt(new Date(xueliOrder.getOrderTime().getTime() + 3000));
        order.setCompletedAt(DateUtils.next(xueliOrder.getOrderTime(), Calendar.HOUR_OF_DAY, 1));
        order.setFeatures(JSON.toJSONString(xueliOrder));
        Map<String, Object> extraMap = order.getExtraMap();
        extraMap.put("invoiceStatus", 1);
        order.setExtraMap(extraMap);
        order.setSyncFlag(0);
        order.setPayFlag(0);
        order.setAddrInfo("");
        order.setRefundFlag(0);
        order.setIsDeleted(0);
        order.setVersion(0);
        order.setCreatedAt(Objects.nonNull(xueliOrder.getOrderTime()) ? xueliOrder.getOrderTime() : new Date());
        order.setUpdatedAt(Objects.nonNull(xueliOrder.getOrderTime()) ? xueliOrder.getOrderTime() : new Date());
        return order;
    }

    private void buildItem(List<OrderItem> orderItemList, List<XueliOrderItem> xieliItem, Order order, List<OrderItem> itemListByOne) {
        for (XueliOrderItem xueliOrderItem : xieliItem) {
            OrderItem item = new OrderItem();
            item.setId(keyGenerator.generateSnowflakeNumKey());
            item.setBizType(5);
            item.setUserId(order.getUserId());
            item.setOrderNo(order.getOrderNo());
            item.setItemId("-1");
            item.setItemName(xueliOrderItem.getItemName());
            item.setItemImage("https://images.qmai.cn/s203007/2021/11/15/116211446400673bd8.png");
            item.setItemSpec("");
            item.setItemUnit("");
            item.setBrandSign("");
            item.setMarketPrice(0);
            item.setCostPrice(0);
            item.setMemberPrice(0);
            item.setItemPrice(xueliOrderItem.getUnitPrice());
            item.setNum(new BigDecimal(xueliOrderItem.getQuantity()));
            item.setDiscountAmount(0);
            item.setPackAmount(0);
            item.setfCode("");
            item.setStatus(0);
            item.setFeatures(JSON.toJSONString(xueliOrderItem));
            item.setGoodsId(0L);
            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("");
            orderItemList.add(item);
            itemListByOne.add(item);
        }
    }

    private void buildDiscount(List<OrderDiscount> discountList, List<XueliOrderDiscount> xueliDiscounts, Order order,
                               List<OrderDiscount> discountListByOne) {
        for (XueliOrderDiscount xueliDiscount : xueliDiscounts) {
            OrderDiscount discount = new OrderDiscount();
            discount.setId(keyGenerator.generateSnowflakeNumKey());
            discount.setBizType(5);
            discount.setUserId(order.getUserId());
            discount.setOrderNo(order.getOrderNo());
            discount.setItemId("-1");
            discount.setDiscountLevel(0);
            discount.setDiscountId("-1");
            discount.setDiscountType(2);
            discount.setDiscountName(xueliDiscount.getCouponName());
            discount.setDiscountSummary(xueliDiscount.getCouponName());
            discount.setDiscountAmount(xueliDiscount.getCouponAmount());
            discount.setFeatures(JSON.toJSONString(xueliDiscount));
            discountList.add(discount);
            discountListByOne.add(discount);
        }
    }

    private void buildPayDetail(List<OrderPayDetails> payDetailsList, Order order, List<OrderPayDetails> payDetailsListByOne) {
        OrderPayDetails payDetails = new OrderPayDetails();
        payDetails.setId(keyGenerator.generateSnowflakeNumKey());
        payDetails.setOrderNo(order.getOrderNo());
        payDetails.setUserId(order.getUserId());
        payDetails.setSellerId(order.getSellerId());
        payDetails.setStoreId(order.getStoreId());
        payDetails.setPayType(order.getPayType());
        payDetails.setAmount(order.getActualAmount());
        payDetails.setPayNo("");
        payDetails.setThirdPayNo("");
        payDetails.setOrderAt(order.getOrderAt());
        payDetails.setPayAt(order.getPayAt());
        payDetails.setSource(order.getSource());
        payDetails.setOrderType(order.getOrderType());
        payDetailsList.add(payDetails);
        payDetailsListByOne.add(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;
    }

    /**
     * 支付方式需要一份映射
     *
     * @param payType
     * @return Date: 2021/11/11 2:11 下午
     */
    private Integer mapPayType(Integer payType) {
        if (Objects.isNull(payType)) {
            return 0;
        }

        return 0;
    }

    /**
     * 订单渠道来源 205-小程序订单 105-合阔pos 106-哗啦啦历史订单 301-百度 302-饿了么 303-美团
     *
     * @param payType
     * @return Date: 2021/11/11 2:11 下午
     */
    private Integer mapSource(Integer source) {
        if (Objects.isNull(source)) {
            return 0;
        }
        switch (source) {
            case 205:
                return 1;
            case 105:
                return 8;
            case 106:
                return 8;
            case 301:
                return 11;
            case 302:
                return 5;
            case 303:
                return 4;
        }
        return 0;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        int coreSize = Runtime.getRuntime().availableProcessors();
        workQueue = new ArrayBlockingQueue(100);
        executorService = new ThreadPoolExecutor(3, 3, 1,
                TimeUnit.MINUTES, workQueue, new NamedThreadFactory("order-data-sync"),
                new ThreadPoolExecutor.AbortPolicy());
    }

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

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

    //    public List<Long> sellerIdList = Arrays.asList(215345L, 214777L, 215593L, 213004L, 211986L, 215393L);
    public List<Long> sellerIdList = Arrays.asList(217858L);

    final Integer bakingBizType = 4;
    final int size = 200;

    @Override
    public Result luWeiTransfer() {
        logger.info("luWeiTransfer[start]");
        Result result = new Result();
        try {
            int count = 0;
            OrderQuery query = new OrderQuery();
            query.setSize(size);
            query.setBizTypeList(Arrays.asList(5, 6));
            for (Long sellerId : sellerIdList) {
                int sellerCount = 0;
                query.setSellerId(sellerId);

                for (int i = 0; i < dbSize; i++) {
                    for (int j = 0; j < tbSize; j++) {
                        Long lastId = null;
                        for (; ; ) {
                            query.setLastId(lastId);
                            List<Order> orderList = commonManager.scanOrder(query, i, j);
                            if (CollectionUtils.isEmpty(orderList)) {
                                break;
                            }

                            while (workQueue.remainingCapacity() < 50) {
                                logger.info("workQueue size:{}", workQueue.size());
                                try {
                                    Thread.sleep(1000);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                            int finalI = i;
                            int finalJ = j;
                            executorService.submit(() -> {
                                try {
                                    exece(orderList, finalI, finalJ);
                                } catch (Exception e) {
                                    logger.error("[execute]failed！cause by:{}", e);
                                }
                            });


                            sellerCount += orderList.size();
                            count += orderList.size();

                            lastId = orderList.get(orderList.size() - 1).getId();
                            if (orderList.size() < size) {
                                break;
                            }
                            logger.info("luWeiTransfer[running], sellerId:{}, sellerCount:{}, i:{}, j:{}", sellerId, sellerCount, i, j);
                        }
                    }
                }
                logger.info("luWeiTransfer[sellerEnd], sellerId:{}, sellerCount:{}", sellerId, sellerCount);
            }
            logger.info("luWeiTransfer[end], totalCount:{}", count);

        } catch (Throwable e) {
            logger.error("luWeiTransfer[fail]!, cause by:{}", e);
        }
        return null;
    }

    private void exece(List<Order> orderList, int i, int j) {
            if (CollectionUtils.isEmpty(orderList)) {
                return;
            }
        Long sellerId = orderList.get(0).getSellerId();
        List<Long> userIdList = new ArrayList<>(size);
            List<PerformanceSelfTake> takeList = new ArrayList<>(size);
            List<String> orderNoList = orderList.stream().map(Order::getOrderNo).collect(Collectors.toList());

            // 转换discountType
            List<OrderDiscount> discountList = commonManager.scanOrderDiscount(orderNoList, i, j);
            Map<String, List<OrderDiscount>> discountMap = null;
            if (!CollectionUtils.isEmpty(discountList)) {
                for (OrderDiscount discount : discountList) {
                    Map<String, Object> extraMap = discount.getExtraMap();
                    extraMap.put("historyDiscountType", discount.getDiscountType());
                    discount.setExtraMap(extraMap);
                    discount.setDiscountType(checkDiscountType(discount));
                }
                discountMap = discountList.stream().collect(Collectors.groupingBy(OrderDiscount::getOrderNo));
            }
        logger.info("luWeiTransfer[running], ThreadName:{}, sellerId:{}, discountListSize:{}, i:{}, j:{}",
                Thread.currentThread().getName(), sellerId, discountList.size(), i, j);


        // 转换支付表
            List<OrderPayDetails> payList = commonManager.scanPayByOrderNo(orderNoList, i, j);
            Map<String, List<OrderPayDetails>> payMap = null;
            if (!CollectionUtils.isEmpty(payList)) {
                payMap = payList.stream().collect(Collectors.groupingBy(OrderPayDetails::getOrderNo));
            }
        logger.info("luWeiTransfer[running], ThreadName:{}, sellerId:{}, payListSize:{}, i:{}, j:{}",
                Thread.currentThread().getName(), sellerId, payList.size(), i, j);

            // 退款单表
            List<Refund> refundList = refundDao.selectByOrderNoList(orderNoList);
            Map<String, List<Refund>> refundMap = null;
            if (!CollectionUtils.isEmpty(refundList)) {
                refundMap = refundList.stream().collect(Collectors.groupingBy(Refund::getOrderNo));
            }
        logger.info("luWeiTransfer[running], ThreadName:{}, sellerId:{}, refundListSize:{}, i:{}, j:{}",
                Thread.currentThread().getName(), sellerId, refundList.size(), i, j);

            // 退款明细表
            List<OrderRefundDetails> orderRefundDetails = refundDetailsDao.selectByOrderNoNoList(orderNoList);
            Map<String, List<OrderRefundDetails>> refundDetailsMap = null;
            if (!CollectionUtils.isEmpty(orderRefundDetails)) {
                refundDetailsMap = orderRefundDetails.stream().collect(Collectors.groupingBy(OrderRefundDetails::getRefundNo));
            }
        logger.info("luWeiTransfer[running], ThreadName:{}, sellerId:{}, orderRefundDetailsSize:{}, i:{}, j:{}",
                Thread.currentThread().getName(), sellerId, orderRefundDetails.size(), i, j);

            List<OrderPayDetails> newPayList = new ArrayList<>(payList.size());
            List<Refund> newRefundList = new ArrayList<>(refundList.size());
            List<OrderRefundDetails> newRefundDetailsList = new ArrayList<>(orderRefundDetails.size());

            for (Order order : orderList) {
                if (order.getBizType().equals(bakingBizType)) {
                    continue;
                }
                buildHistoryExtra(order);
                orderTypeCatering2Baking(order);
                sourceCatering2Baking(order);
                payTypeCatering2Baking(order);
                orderSubTypeCatering2Baking(order);
                payStatusCatering2Baking(order);
                statusCatering2Baking(order);

                userIdList.add(order.getUserId());
                order.setBizType(bakingBizType);
                buildTake(order, takeList);
                order.setDiscountInfo(getDiscountInfo(discountMap, order.getOrderNo()));

                //支付明细表
                buildPayList(order, payMap, newPayList);
                //处理退款
                buildRefundList(order, refundMap, newRefundList, refundDetailsMap, newRefundDetailsList);
                //处理退款明细 修改payType bizType
            }


            //更新订单
            commonManager.batchUpdateOrderBaking(orderList, i, j);
            itemDao.updateBizTypeByList(bakingBizType, orderNoList, userIdList);

            //退款单商品 更新bizType 和 itemType = 2
            refundItemDao.updateForBaking(bakingBizType, orderNoList, 2);
            indexDao.updateBiz(bakingBizType, orderNoList);

            //更新优惠
            if (!CollectionUtils.isEmpty(discountList)) {
                commonManager.updateDiscountBatchBaking(discountList, i, j);
            }
            //补充自提信息
            if (!CollectionUtils.isEmpty(takeList)) {
                takeDao.insertList(takeList);
            }
            //更新支付
            if (!CollectionUtils.isEmpty(newPayList)) {
                commonManager.updatePayBatchBaking(newPayList, i, j);
            }
            //更新退款
            if (!CollectionUtils.isEmpty(newRefundList)) {
                refundDao.updateBatchToBaking(newRefundList);
            }
            //更新退款明细
            if (!CollectionUtils.isEmpty(newRefundDetailsList)) {
                refundDetailsDao.updateBatchToBaking(newRefundDetailsList);
            }
            searchManager.indexOrder(orderList);
            handleComment(orderNoList, orderList, i, j);
    }

    private void handleComment(List<String> orderNoList, List<Order> orderList, int i, int j) {
        try {
            Long sellerId = orderList.get(0).getSellerId();
            Map<Long, Order> orderMap = orderList.stream().collect(Collectors.toMap(Order::getId, Function.identity()));
            List<OrderComment> list = commentDao.selectByOrderNoList(orderNoList, sellerId);
            logger.info("luWeiTransfer[running], ThreadName:{}, sellerId:{}, commentListSize:{}, i:{}, j:{}",
                    Thread.currentThread().getName(), sellerId, list.size(), i, j);
            if(CollectionUtils.isEmpty(list)){
                return;
            }
            for (OrderComment comment : list) {
                comment.setOrderType(orderMap.get(comment.getOrderNo()).getOrderType());
                comment.setPerformanceType(orderMap.get(comment.getOrderNo()).getPerformanceType());
                comment.setBizType(bakingBizType);
            }
            commentDao.updateBatchToBaking(list, sellerId);

            List<OrderItemComment> commentList = itemCommentDao.selectByOrderNoList(orderNoList, sellerId);
            for (OrderItemComment itemComment : commentList){
                itemComment.setPerformanceType(orderMap.get(itemComment.getOrderNo()).getPerformanceType());
                itemComment.setBizType(bakingBizType);
            }
            commentManager.batchIndex(commentList);
            itemCommentDao.updateBatchToBaking(commentList, sellerId);
            // 发统计消息
            List<CommentDocumentMessage> messageList = buildAsyncEs(commentList);
            Result<Integer> result = messageManager.sendCommentSyncEsMessage(messageList);
            logger.info("luWeiTransfer[running][sendCommentSyncEsMessage], ThreadName:{}, sellerId:{}, commentListSize:{}, i:{}, j:{}, result:{}",
                    Thread.currentThread().getName(), sellerId, list.size(), i, j, result);
        } catch (Throwable e) {
            logger.error("DelEsExpireDataTask[handleComment][error] failed!, cause by:{}", e);
        }

    }

    public List<CommentDocumentMessage> buildAsyncEs(List<OrderItemComment> itemCommentList) {
        List<CommentDocumentMessage> commentToEsDTOList  = new ArrayList<>(itemCommentList.size());
        for (OrderItemComment itemCommentDTO : itemCommentList) {
            CommentDocumentMessage commentToEsDTO = new CommentDocumentMessage();
            commentToEsDTO.setSellerId(itemCommentDTO.getSellerId());
            commentToEsDTO.setOrderNo(itemCommentDTO.getOrderNo());
            commentToEsDTO.setGoodsId(itemCommentDTO.getGoodsId());
            commentToEsDTO.setItemId(itemCommentDTO.getItemId());
            commentToEsDTOList.add(commentToEsDTO);
        }
        return commentToEsDTOList;
    }


    private void buildPayList(Order order, Map<String, List<OrderPayDetails>> payMap, List<OrderPayDetails> newPayList) {
        if (Objects.isNull(payMap)) {
            return;
        }
        List<OrderPayDetails> orderPayList = payMap.get(order.getOrderNo());
        if (CollectionUtils.isEmpty(orderPayList)) {
            return;
        }
        List<InnerOrderPayDetails> innerOrderPayDetailsList = new ArrayList<>(orderPayList.size());
        for (OrderPayDetails pay : orderPayList) {
            Map<String, Object> extraMapPay = pay.getExtraMap();
            extraMapPay.put("historyPayType", pay.getPayType());
            pay.setExtraMap(extraMapPay);

            pay.setBizType(order.getBizType());
            pay.setOrderType(order.getOrderType());
            pay.setPerformanceType(order.getPerformanceType());
            pay.setPayType(payTypeChange(pay.getPayType()));
            newPayList.add(pay);
            innerOrderPayDetailsList.add(mapper.map(pay, InnerOrderPayDetails.class));
        }
        if (innerOrderPayDetailsList.size() > CommonConstants.MAX_ITEM_SIZE) {
            order.setPayDetailInfo(CommonConstants.PAY_FLAG);
        } else {
            order.setPayDetailInfo(JSON.toJSONString(innerOrderPayDetailsList));
        }
    }

    private void buildRefundList(Order order, Map<String,
            List<Refund>> refundMap,
                                 List<Refund> newRefundList,
                                 Map<String, List<OrderRefundDetails>> refundDetailsMap,
                                 List<OrderRefundDetails> newRefundDetailsList) {
        if (Objects.isNull(refundMap)) {
            return;
        }
        List<Refund> refundList = refundMap.get(order.getOrderNo());
        if (CollectionUtils.isEmpty(refundList)) {
            return;
        }
        for (Refund refund : refundList) {
            Map<String, Object> extraMapPay = refund.getExtraMap();
            extraMapPay.put("historyStatus", refund.getStatus());
            extraMapPay.put("historyPayType", refund.getPayType());
            refund.setExtraMap(extraMapPay);

            refund.setBizType(order.getBizType());
            refund.setOrderType(order.getOrderType());
            refund.setSource(order.getSource());
            refund.setOrderSubType(order.getOrderSubType());
            refund.setPerformanceType(order.getPerformanceType());
            refund.setPayType(payTypeChange(refund.getPayType()));
            refund.setStatus(ConRefundStatus(refund.getStatus()));
            buildRefundDetailsList(refund, refundDetailsMap, newRefundDetailsList);
            newRefundList.add(refund);
        }
    }

    private void buildRefundDetailsList(Refund refund,
                                        Map<String, List<OrderRefundDetails>> refundDetailsMap,
                                        List<OrderRefundDetails> newRefundDetailsList) {
        if (!refundDetailsMap.containsKey(refund.getRefundNo())) {
            return;
        }
        List<OrderRefundDetails> orderRefundDetails = refundDetailsMap.get(refund.getRefundNo());
        List<InnerOrderRefundDetail> innerOrderRefundDetails = new ArrayList<>(orderRefundDetails.size());
        for (OrderRefundDetails details : orderRefundDetails) {
            Map<String, Object> detailsExtraMap = details.getExtraMap();
            detailsExtraMap.put("historyPayType", details.getPayType());
            details.setExtraMap(detailsExtraMap);
            details.setPayType(payTypeChange(details.getPayType()));
            newRefundDetailsList.add(details);
            innerOrderRefundDetails.add(mapper.map(details, InnerOrderRefundDetail.class));
        }
        if (innerOrderRefundDetails.size() > CommonConstants.MAX_ITEM_SIZE) {
            refund.setRefundDetailInfo(CommonConstants.ITEM_FLAG);
        } else {
            String refundDetailInfo = JSON.toJSONString(innerOrderRefundDetails);
            refund.setRefundDetailInfo(refundDetailInfo);
        }
    }


    private Integer ConRefundStatus(Integer status) {
        if (Objects.equals(10, status)) {
            return 0;
        }
        if (Objects.equals(20, status)) {
            return 0;
        }
        if (Objects.equals(30, status)) {
            return 1;
        }
        if (Objects.equals(40, status)) {
            return 2;
        }
        if (Objects.equals(50, status)) {
            return 3;
        }
        return status;
    }

    /**
     * 扩展字段保存一下历史枚举值
     *
     * @param order
     */
    private void buildHistoryExtra(Order order) {
        Map<String, Object> map = new HashMap<>();
        map.put("bizType", order.getBizType());
        map.put("orderType", order.getOrderType());
        map.put("orderSubType", order.getOrderSubType());
        map.put("source", order.getSource());
        map.put("payType", order.getPayType());
        map.put("status", order.getStatus());

        Map<String, Object> extraMap = order.getExtraMap();
        extraMap.put("historyData", map);
        extraMap.put("luWeiTraFlag", 1);
        if (Objects.nonNull(order.getStoreId()) && order.getStoreId() > 0L) {
            extraMap.put("from", 0);
        }
        order.setExtraMap(extraMap);
    }

    private String getDiscountInfo(Map<String, List<OrderDiscount>> discountMap, String orderNo) {
        if (!CollectionUtils.isEmpty(discountMap)) {
            List<OrderDiscount> orderDiscounts = discountMap.get(orderNo);
            if (!CollectionUtils.isEmpty(orderDiscounts)) {
                if (orderDiscounts.size() > CommonConstants.MAX_ITEM_SIZE) {
                    return CommonConstants.DISCOUNT_FLAG;
                }
                return JSON.toJSONString(ConvertUtils.convertList(orderDiscounts, InnerOrderDiscount.class));
            }
        }
        return null;
    }

    private void orderTypeCatering2Baking(Order order) {
        Integer performanceType = 0;
        if (Objects.isNull(order.getOrderType())) {
            return;
        }
        Integer orderType = order.getOrderType();
        if (order.getOrderType().equals(0)) {
            orderType = 1;
        }
        if (order.getOrderType().equals(1)) {
            orderType = 1;
            performanceType = 3;
        }
        if (order.getOrderType().equals(2)) {
            orderType = 1;
            performanceType = 3;
        }
        if (order.getOrderType().equals(3)) {
            orderType = 1;
            performanceType = 2;
        }
        if (order.getOrderType().equals(4)) {
            orderType = 2;
        }
        if (order.getOrderType().equals(5)) {
            orderType = 3;
        }
        if (order.getOrderType().equals(8)) {
            orderType = 6;
        }
        if (order.getOrderType().equals(10)) {
            orderType = 4;
        }
        if (order.getOrderType().equals(13)) {
            orderType = 5;
        }
        if (order.getOrderType().equals(14)) {
            orderType = 1;
            performanceType = 3;
            Map<String, Object> extraMap = order.getExtraMap();
            extraMap.put("from", 1);
            order.setExtraMap(extraMap);
        }
        if (order.getOrderType().equals(20)) {
            orderType = 7;
            performanceType = 1;
        }
        if (order.getOrderType().equals(40)) {
            if (Objects.nonNull(order.getOrderSubType()) && order.getOrderSubType().equals(60)) {
                orderType = 60;
                performanceType = 1;
            }
        }
        if (orderType.equals(7)) {
            if (order.getPayStatus().equals(1)) {
                order.setReceiveAt(order.getPayAt());
                order.setReceiveStatus(1);
            }
        }
        order.setOrderType(orderType);
        order.setPerformanceType(performanceType);
    }

    private void sourceCatering2Baking(Order order) {
        if (Objects.isNull(order.getSource())) {
            return;
        }
        Integer source = order.getSource();
        if (order.getSource().equals(9)) {
            source = 19;
        }
        if (order.getSource().equals(30)) {
            source = 2;
        }
        if (order.getSource().equals(50)) {
            source = 8;
        }
        order.setSource(source);
    }

    private void payTypeCatering2Baking(Order order) {
        if (Objects.isNull(order.getPayType())) {
            return;
        }
        Integer payType = order.getPayType();
        order.setPayType(payTypeChange(payType));
    }

    private void orderSubTypeCatering2Baking(Order order) {
        if (Objects.isNull(order.getOrderSubType())) {
            return;
        }
        Integer orderSubType = order.getOrderSubType();
        if (order.getOrderSubType().equals(1)) {
            orderSubType = 3;
        }
        if (order.getOrderSubType().equals(2)) {
            orderSubType = 4;
        }
        if (order.getOrderSubType().equals(3)) {
            orderSubType = 0;
        }
        if (order.getOrderSubType().equals(6)) {
            orderSubType = 1;
        }
        if (order.getOrderSubType().equals(60)) {
            orderSubType = 0;
        }
        order.setOrderSubType(orderSubType);
    }

    private void statusCatering2Baking(Order order) {
        if (Objects.isNull(order.getStatus())) {
            return;
        }
        Integer status = order.getStatus();
        if (order.getStatus().equals(10)) {
            status = 1;
        }
        if (order.getStatus().equals(20)) {
            status = 2;
        }
        if (order.getStatus().equals(30)) {
            status = 2;
            if (order.getPerformanceType().equals(3) && order.getPayStatus().equals(1)) {
                order.setReceiveStatus(1);
                order.setReceiveAt(order.getPayAt());
            }
        }
        if (order.getStatus().equals(40)) {
            status = 2;
            order.setReceiveStatus(1);
            order.setReceiveAt(order.getPayAt());
        }
        if (order.getStatus().equals(50)) {
            status = 4;
        }
        if (order.getStatus().equals(60)) {
            status = 8;
        }
        if (order.getStatus().equals(70)) {
            status = 8;
        }
        order.setStatus(status);
    }

    private void payStatusCatering2Baking(Order order) {
        if (Objects.isNull(order.getPayStatus())) {
            return;
        }
        Integer payStatus = order.getPayStatus();
        if (order.getPayStatus().equals(2)) {
            payStatus = 0;
        }
        order.setPayStatus(payStatus);
    }

    private Integer payTypeChange(Integer payType) {
        Integer newPayType = null;
        if (Objects.equals(9, payType)) {
            newPayType = 8;
        }
        if (Objects.equals(5, payType)) {
            newPayType = 267;
        }
        if (Objects.equals(6, payType)) {
            newPayType = 268;
        }
        if (Objects.equals(7, payType)) {
            newPayType = 132;
        }
        if (Objects.equals(12, payType)) {
            newPayType = 266;
        }
        if (Objects.equals(8, payType)) {
            newPayType = 265;
        }
        if (Objects.equals(99, payType)) {
            newPayType = 8;
        }
        if (Objects.equals(103, payType)) {
            newPayType = 17;
        }
        if (Objects.equals(101, payType)) {
            newPayType = 17;
        }
        if (Objects.equals(102, payType)) {
            newPayType = 17;
        }
        if (Objects.equals(32, payType)) {
            newPayType = 128;
        }
        if (Objects.nonNull(newPayType)) {
            return newPayType;
        }
        return payType;
    }

    private Integer checkDiscountType(OrderDiscount discount) {
        Integer discountType = discount.getDiscountType();
        if (discount.getBizType().equals(BizTypeEnum.CATERING.getType())) {
            discountType = catering2Baking(discountType);
        }
        if (discount.getBizType().equals(BizTypeEnum.ASSISTANT.getType())) {
            discountType = ass2Baking(discountType);
        }
        return discountType;
    }

    private Integer ass2Baking(Integer discountType) {
        if (Objects.equals(discountType, 10001)) {
            return 2;
        }
        if (Objects.equals(discountType, 3)) {
            return 8;
        }
        if (Objects.equals(discountType, 11)) {
            return 5;
        }
        if (Objects.equals(discountType, 10003)) {
            return 18;
        }
        if (Objects.equals(discountType, 8)) {
            return 31;
        }
        if (Objects.equals(discountType, 10)) {
            return 1;
        }
        if (Objects.equals(discountType, 12)) {
            return 20;
        }
        if (Objects.equals(discountType, 34)) {
            return 24;
        }
        if (Objects.equals(discountType, 13)) {
            return 22;
        }
        if (Objects.equals(discountType, 10004)) {
            return 19;
        }
        if (Objects.equals(discountType, 22)) {
            return 1;
        }
        if (Objects.equals(discountType, 24)) {
            return 21;
        }
        if (Objects.equals(discountType, 29)) {
            return 20003;
        }
        if (Objects.equals(discountType, 30)) {
            return 20002;
        }
        if (Objects.equals(discountType, 31)) {
            return 33;
        }
        if (Objects.equals(discountType, 10016)) {
            return 84;
        }
        return discountType;
    }

    private Integer catering2Baking(Integer discountType) {
        if (Objects.equals(discountType, 3)) {
            return 8;
        }
        if (Objects.equals(discountType, 4)) {
            return 32;
        }
        if (Objects.equals(discountType, 11)) {
            return 5;
        }
        if (Objects.equals(discountType, 6)) {
            return 18;
        }
        if (Objects.equals(discountType, 8)) {
            return 31;
        }
        if (Objects.equals(discountType, 10)) {
            return 1;
        }
        if (Objects.equals(discountType, 12)) {
            return 20;
        }
        if (Objects.equals(discountType, 13)) {
            return 22;
        }
        if (Objects.equals(discountType, 21)) {
            return 19;
        }
        if (Objects.equals(discountType, 22)) {
            return 1;
        }
        if (Objects.equals(discountType, 24)) {
            return 21;
        }
        if (Objects.equals(discountType, 25)) {
            return 15;
        }
        if (Objects.equals(discountType, 29)) {
            return 20003;
        }
        if (Objects.equals(discountType, 30)) {
            return 20002;
        }
        if (Objects.equals(discountType, 31)) {
            return 33;
        }
        if (Objects.equals(discountType, 27)) {
            return 20001;
        }
        if (Objects.equals(discountType, 56)) {
            return 65;
        }
        if (Objects.equals(discountType, 71)) {
            return 76;
        }
        if (Objects.equals(discountType, 57)) {
            return 66;
        }
        return discountType;
    }

    private void buildTake(Order order, List<PerformanceSelfTake> takeList) {
        //非自提单不处理
        if (!order.getOrderType().equals(1) && !order.getPerformanceType().equals(3)) {
            return;
        }
        PerformanceSelfTake take = new PerformanceSelfTake();
        take.setBizType(bakingBizType);
        take.setOrderNo(order.getOrderNo());
        take.setSellerId(order.getSellerId());
        take.setUserId(order.getUserId());
        take.setStoreId(order.getStoreId());
        take.setSelfTakeName("");
        take.setCodeUrl("");
        take.setBarCodeUrl("");
        take.setSelfTakeMobile("");
        if (Objects.nonNull(order.getMobile())) {
            take.setSelfTakeMobile(order.getMobile());
        }
        take.setVerifyType(0);
        take.setAppointedDateType(0);
        take.setCreatedAt(new Date());
        take.setUpdatedAt(new Date());
        take.setIsDeleted(0);
        take.setSelfTakeStatus(0);
        take.setFeatures("");
        if (order.getStatus().equals(50)) {
            take.setPickAt(order.getCompletedAt());
            take.setSelfTakeStatus(1);
        }
        take.setSelfTakeCode(Long.valueOf(CommonUtils.random(16)));
        takeList.add(take);
    }

    @Override
    public Result mallTransfer() {
        Result result = new Result();
        try {
            int count = 0;
            int size = 200;
            final Integer bizType = 8;
            Long lastId = null;
            for (; ; ) {
                List<IdOrderNo> idOrderList = idOrderNoDao.selectListByIdSize(lastId, size);
                if (CollectionUtils.isEmpty(idOrderList)) {
                    break;
                }
                for (IdOrderNo item : idOrderList) {
                    Order order = orderDao.selectById(item.getOrderId(), item.getUserId());

                    Order update = new Order();
                    update.setBizType(bizType);
                    update.setId(item.getOrderId());
                    update.setUserId(item.getUserId());
                    if (Objects.nonNull(order)) {
                        if (order.getStatus() == 20 && order.getPerformanceStatus() == 1) {
                            update.setStatus(40);
                            order.setStatus(40);
                        }
                        if (order.getStatus() == 60) {
                            update.setStatus(70);
                            order.setStatus(70);
                        }
                    }
                    orderManager.updateBizType(bizType, item.getUserId(), item.getOrderNo(), update);
                    MallTransferMessage message = new MallTransferMessage();
                    message.setOrderNo(item.getOrderNo());
                    message.setUserId(item.getUserId());
                    message.setSellerId(item.getSellerId());
                    messageManager.sendMallMessage(message);
                    count++;

                    order.setBizType(bizType);
                    searchManager.indexOrder(order, null);
                }
                List<String> orderNoList = idOrderList.stream().map(IdOrderNo::getOrderNo).collect(Collectors.toList());

                RefundQuery refundQuery = new RefundQuery();
                refundQuery.setOrderNoList(orderNoList);
                List<Refund> refundList = refundDao.selectList(refundQuery);
                for (Refund refund : refundList) {
                    if (refund.getStatus().equals(20)) {
                        Refund updateRefund = new Refund();
                        updateRefund.setId(refund.getId());
                        updateRefund.setStatus(10);
                        refundDao.update(updateRefund);
                    }
                }

                orderManager.updateRefundBizType(bizType, orderNoList);

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

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

    /**
     * test
     */
//    private Long BaozhusellerId = 11506L;

    /**
     * pro
     */
    private Long BaozhusellerId = 216330L;

    @Override
    public Result baozhuTransfer() {
        try {
            logger.info("baozhuTransfer[start]");
            Long lastId = null;
            int size = 200;
            int count = 0;
            int orderCount = 0;
            int refundFlag = 0;
            for (; ; ) {
                List<BaoZhu> list = baoZhuDao.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(BaoZhu::getOrderNo).collect(Collectors.toList());
                List<Long> userIdList = list.stream().map(BaoZhu::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);

                //支付是否存在
                OrderPayDetailsQuery payDetailsQuery = new OrderPayDetailsQuery();
                payDetailsQuery.setUserIdList(userIdList);
                payDetailsQuery.setOrderNoList(orderNoList);
                List<OrderPayDetails> payExistList = payDetailsDao.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 (BaoZhu item : list) {
                    //订单号不存在 ： 不迁移
                    if (Objects.isNull(item.getOrderNo())) {
                        continue;
                    }
                    if (Objects.isNull(item.getUserId())) {
                        continue;
                    }
                    if (Objects.isNull(item.getMobile())) {
                        continue;
                    }
                    //订单已存在数据库：更新商品快照，加商品, 更新、总金额
                    if (Objects.nonNull(orderNoMap.get(item.getOrderNo()))) {
                        // insert商品，更新订单商品快照
                        buildT97Item(itemList, item, orderNoMap);
                        logger.info("baozhuTransfer[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(CommonConstants.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() > CommonConstants.MAX_ITEM_SIZE) {
                                    order.setItemInfo(CommonConstants.ITEM_FLAG);
                                } else {
                                    order.setItemInfo(JSON.toJSONString(innerOrderItems));
                                }
                            }
                            order.setDiscountAmount(0);

                            int intItemAmount = 0;
                            if (Objects.nonNull(item.getPrice())) {
                                BigDecimal multiply = item.getPrice().multiply(new BigDecimal(100));
                                intItemAmount = (Double.valueOf(multiply.toString()).intValue());
                            }
                            int totalAmount = order.getTotalAmount() + intItemAmount;
                            order.setPayAmount(totalAmount);
                            order.setActualAmount(totalAmount);
                            order.setTotalAmount(totalAmount);
                            order.setItemAmount(totalAmount);
                            logger.info("baozhuTransfer[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("baozhuTransfer[createNew],count:{},lastId:{},orderNo:{}", count, lastId, item.getOrderNo());
                        }
                    }
                }
                List<BatchSyncEsMessage> messageList = new ArrayList<>(size);

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

                //批量新增订单
                if (!CollectionUtils.isEmpty(orderNoInsertMap)) {
                    for (Order order : orderNoInsertMap.values()) {
                        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(keyGenerator.generateSnowflakeNumKey());
                        indexList.add(index);
                    }
                    orderDao.insertList(orderList);
                    orderCount += orderList.size();
                    searchManager.indexOrder(orderList);
                }
                //循环更新已存在支付
                if (!CollectionUtils.isEmpty(payExistMap)) {
                    for (OrderPayDetails payDetails : payExistMap.values()) {
                        payDetailsDao.updateAmount(payDetails);
                    }
                }
                // 新增订单索引
                if (!CollectionUtils.isEmpty(indexList)) {
                    indexDao.insertList(indexList);
                }
                //批量新增商品
                if (!CollectionUtils.isEmpty(itemList)) {
                    itemDao.inserts(itemList);
                }
                //批量新增支付明细
                if (!CollectionUtils.isEmpty(payList)) {
                    payDetailsDao.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("baozhuTransfer[for-end],count:{},lastId:{}, orderCount:{}", count, lastId, orderCount);
                if (list.size() < size) {
                    break;
                }
            }
            logger.info("baozhuTransfer[end],count:{},lastId:{}, orderCount:{}", count, lastId, orderCount);

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

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

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

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

            //商品实付金额累加
            int intItemPrice = 0;
            if (Objects.nonNull(item.getPrice())) {
                BigDecimal multiply = item.getPrice().multiply(new BigDecimal(100));
                intItemPrice = Double.valueOf(multiply.toString()).intValue();
            }
            int totalAmount = order.getTotalAmount() + intItemPrice;
            order.setItemAmount(totalAmount);
            order.setPayAmount(totalAmount);
            order.setActualAmount(totalAmount);
            order.setTotalAmount(totalAmount);
        }
        orderNoMap.put(item.getOrderNo(), order);
    }


    private OrderItem buildT97ItemValue(List<OrderItem> itemList, BaoZhu juiceOrder) {
        int intDiscountAmount = 0;
        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(keyGenerator.generateSnowflakeNumKey());
        item.setBizType(5);
        item.setUserId(juiceOrder.getUserId());
        item.setOrderNo(juiceOrder.getOrderNo());
        item.setItemId("-1");
        item.setGoodsId(-1L);
        item.setItemImage("https://images.qmai.cn/s11478/2023/04/06/f05e6b031b4c42c6dc.jpg");
        item.setItemSign("");

        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(intItemPrice);
        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.getCreatedAt());
        item.setProductNo("");
        item.setIsGift(0);
        item.setSellerId(BaozhusellerId);
        item.setItemType(0);
        item.setOwnerId(0L);
        item.setBatchingInfo("");
        itemList.add(item);
        return item;
    }


    public Order buildT97Order(List<Order> orderList, BaoZhu juiceOrder) {
        Order order = new Order();
        order.setId(keyGenerator.generateSnowflakeNumKey());
        order.setOrderNo(juiceOrder.getOrderNo());
        order.setUserId(juiceOrder.getUserId());
        order.setOrderType(1);
        order.setDiscountAmount(0);
        order.setActualAmount(0);
        order.setPayAmount(0);
        order.setItemAmount(0);
        order.setPayStatus(1);
        order.setStatus(70);
        order.setSource(1);
        int intDiscountAmount = 0;
        //订单总金额 + 实付 + 每一笔的优惠
//        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.getPrice())) {
            BigDecimal multiply = juiceOrder.getPrice().multiply(new BigDecimal(100));
            intItemPrice = Double.valueOf(multiply.toString()).intValue();
        }
        order.setItemAmount(intItemPrice);
        order.setPayAmount(intItemPrice);
        order.setActualAmount(intItemPrice);
        order.setTotalAmount(intItemPrice);

        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(1);
        order.setIsDeleted(0);
        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(BaozhusellerId);
        if (Objects.nonNull(juiceOrder.getStoreId())) {
            order.setStoreId(juiceOrder.getStoreId());
        }

        order.setOrderAt(juiceOrder.getCreatedAt());
        order.setCreatedAt(juiceOrder.getCreatedAt());
        order.setPayAt(juiceOrder.getCreatedAt());
        order.setCompletedAt(juiceOrder.getCreatedAt());
        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 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(keyGenerator.generateSnowflakeNumKey());
        payDetails.setOrderNo(order.getOrderNo());
        payDetails.setUserId(order.getUserId());
        payDetails.setAmount(order.getPayAmount());
        payDetails.setPayType(order.getPayType());
        payDetails.setStoreId(order.getStoreId());
        payDetails.setSellerId(BaozhusellerId);
        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);
    }
}
