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

import com.alibaba.fastjson.JSON;
import com.github.dozermapper.core.Mapper;
import com.google.common.collect.Lists;
import com.zm.order.tool.server.chen.ChenPayDao;
import com.zm.order.tool.server.chen.FoodDao;
import com.zm.order.tool.server.chen.MasterDao;
import com.zm.order.tool.server.component.ShardingKeyGenerator;
import com.zm.order.tool.server.constants.CommonConstants;
import com.zm.order.tool.server.constants.MapConstChenStore;
import com.zm.order.tool.server.dao.*;
import com.zm.order.tool.server.manager.CommonManager;
import com.zm.order.tool.server.manager.OrderManager;
import com.zm.order.tool.server.manager.RedisManager;
import com.zm.order.tool.server.manager.SearchManager;
import com.zm.order.tool.server.model.*;
import com.zm.order.tool.server.query.OrderQuery;
import com.zm.order.tool.server.service.TransferService;
import com.zm.order.tool.server.tempdb.*;
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.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;

/**
 * @author zhuxiaofeng
 * @packageName: com.zm.order.tool.server.service
 * @className: TransferServiceImpl
 * @date 2023/5/25 11:25
 */
@Service
@SuppressWarnings("all")
public class TransferServiceImpl implements TransferService, InitializingBean {

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

    @Autowired
    private TransferOrderDao transferOrderDao;
    @Autowired
    private MomoDao momoDao;
    @Autowired
    private OrderIndexDao indexDao;
    @Autowired
    private OrderItemDao itemDao;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private OrderPayDetailsDao payDao;
    @Autowired
    private OrderDiscountDao discountDao;
    @Autowired
    private OrderNoUserDao orderNoUserDao;
    @Autowired
    private SearchManager searchManager;
    @Autowired
    private Mapper mapper;
    @Autowired
    private ShardingKeyGenerator keyGenerator;
    @Autowired
    private IdOrderNoDao idOrderNoDao;
    @Autowired
    private OrderManager orderManager;
    @Autowired
    private RedisManager redisManager;
    @Autowired
    private CommonManager commonManager;
    private BlockingQueue workQueue;
    private ExecutorService executorService;

    @Autowired
    private MasterDao masterDao;
    @Autowired
    private FoodDao foodDao;
    @Autowired
    private ChenPayDao chenPayDao;
    @Autowired
    private ChenUserDao chenUserDao;

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

    //beta
//    private final Long chenxiangguiSellerId = 11505L;

    //pro
    private final Long chenxiangguiSellerId = 216359L;

    private final int size = 200;
    private int count = 0;
    private static int itemCount = 0;

    @Override
    public Result momo() {
        try {
            logger.info("momoTransfer[start]");
            Long lastId = 0L;
            for (; ; ) {
                List<TransferOrder> transferOrders = transferOrderDao.selectList(lastId, size);
                if (CollectionUtils.isEmpty(transferOrders)) {
                    break;
                }
                Result<String> redisData = redisManager.get("stop-momo-order");
                if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                    return Result.successNullData();
                }
                executorService.submit(() -> {
                    doTransfer(transferOrders);
                });
                count += transferOrders.size();
                lastId = transferOrders.get(transferOrders.size() - 1).getId();
                logger.info("momoTransfer, lastId:{}, orderCount:{}", lastId, count);

                if (transferOrders.size() > size) {
                    break;
                }
            }
            logger.info("momoTransfer[end], lastId:{}, orderCount:{}, itemCount:{}", lastId, count);
        } catch (Throwable e) {
            logger.error("momoTransfer[error] failed!, cause by:{}", e);
        }
        return null;
    }

    @Autowired
    private DuoshiwuDao duoshiwuDao;

    @Override
    public Result duoshiwu() {
        try {
            int count = 0;
            Long lastId = null;
            for (;;) {
                List<Duoshiwu> list = duoshiwuDao.selectList(lastId, 200, null);
                if (CollectionUtils.isEmpty(list)) {
                    return Result.successNullData();
                }
                executeDsw(list);
                count += list.size();
                logger.info("[duoshiwu]count:{}, lastId:{}", count, lastId);
                if (list.size() < 200) {
                    return Result.successNullData();
                }
                lastId = list.get(list.size() - 1).getId();
            }
        } catch (Exception e) {
            logger.error("duoshiwu, cause by:{}", e);
        }
        return Result.successNullData();
    }

    @Override
    public void duoshiwuDel() {
        try {
            int count = 0;
            Long lastId = null;
            for (;;) {
                List<Duoshiwu> list = duoshiwuDao.selectList(lastId, 200, null);
                if (CollectionUtils.isEmpty(list)) {
                    return ;
                }
                executeDswDel(list);
                count += list.size();
                logger.info("[duoshiwu]count:{}, lastId:{}", count, lastId);
                if (list.size() < 200) {
                    return ;
                }
            }
        } catch (Exception e) {
            logger.error("duoshiwuDel, cause by:{}", e);
        }
    }

    private void executeDswDel(List<Duoshiwu> list) {
        while (workQueue.remainingCapacity() < 10) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executorService.submit(() -> {
            try {
                for (Duoshiwu each : list) {
                    orderDao.deleteByOrderNo(each.getOrderNo(), each.getUserId());
                }
            } catch (Exception e) {
                logger.error("[executeDsw]failed！cause by:{}", e);
            }
        });
    }

    private void executeDsw(List<Duoshiwu> list) {
        while (workQueue.remainingCapacity() < 10) {
            logger.info("workQueue size:{}", workQueue.size());
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        executorService.submit(() -> {
            try {
                List<Order> orderList = new ArrayList<>();
                List<OrderDiscount> disList = new ArrayList<>();
                List<OrderPayDetails> payList = new ArrayList<>();
                List<OrderItem> itemList = new ArrayList<>();
                List<OrderIndex> indexList = new ArrayList<>();

                for (Duoshiwu datasource : list) {
                    Order order = dswOrder(datasource);
                    OrderItem orderItem = dswItem(itemList, order);
                    order.setItemInfo(JSON.toJSONString(Lists.newArrayList(mapper.map(orderItem, InnerOrderItem.class))));
                    buildPay(payList, order);
                    indexList.add(buildIndex(order));
                    orderList.add(order);
                }
                // 新增订单
                if (!CollectionUtils.isEmpty(orderList)) {
                    orderDao.insertList(orderList);
                }
                // 新增订单索引
                if (!CollectionUtils.isEmpty(indexList)) {
                    indexDao.insertList(indexList);
                }
                //批量新增商品
                if (!CollectionUtils.isEmpty(itemList)) {
                    itemDao.inserts(itemList);
                }
                //批量新增支付明细
                if (!CollectionUtils.isEmpty(payList)) {
                    payDao.insertList(payList);
                }
                searchManager.indexOrder(orderList);

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

    private static int threadCount = 0;

    private void doTransfer(List<TransferOrder> transferOrders) {
        try {
            List<String> orderNoList = transferOrders.stream().map(TransferOrder::getOrderNo).collect(Collectors.toList());
            count += orderNoList.size();
            //订单号拉出三方商品信息
            List<Momo> momoList = momoDao.selectList(orderNoList);
            itemCount += momoList.size();
            Map<String, List<Momo>> momoMap = momoList.stream().collect(Collectors.groupingBy(Momo::getOrderNo));
            List<Order> orderList = new ArrayList<>(size);
            List<OrderDiscount> disList = new ArrayList<>(size);
            List<OrderPayDetails> payList = new ArrayList<>(size);
            List<OrderItem> itemList = new ArrayList<>();
            List<OrderIndex> indexList = new ArrayList<>(size);

            for (TransferOrder transferOrder : transferOrders) {
                List<Momo> momos = momoMap.get(transferOrder.getOrderNo());
                if (CollectionUtils.isEmpty(momos)) {
                    continue;
                }
                Order order = buildOrder(momos, orderList, itemList, payList, disList);
                indexList.add(buildIndex(order));
            }

            // 新增订单
            if (!CollectionUtils.isEmpty(orderList)) {
                orderDao.insertList(orderList);
            }
            // 新增订单索引
            if (!CollectionUtils.isEmpty(indexList)) {
                indexDao.insertList(indexList);
            }
            //批量新增商品
            if (!CollectionUtils.isEmpty(itemList)) {
                itemDao.inserts(itemList);
            }
            //批量新增支付明细
            if (!CollectionUtils.isEmpty(payList)) {
                payDao.insertList(payList);
            }
            //批量新增优惠
            if (!CollectionUtils.isEmpty(disList)) {
                discountDao.inserts(disList);
            }
            searchManager.indexOrder(orderList);
            threadCount += transferOrders.size();
            logger.info("momoTransfer[running], ThreadName:{}, lastId:{}, orderThreadCount:{}, itemCount:{}",
                    Thread.currentThread().getName(),
                    transferOrders.get(transferOrders.size() - 1).getId(),
                    threadCount,
                    itemCount);
        } catch (Throwable e) {
            logger.error("momoTransfer[momoError] failed!, cause by:{}", e);
        }
    }

    private void buildDiscount(List<OrderDiscount> list, Order order) {
        OrderDiscount discount = new OrderDiscount();
        discount.setId(keyGenerator.generateSnowflakeNumKey());
        discount.setBizType(order.getBizType());
        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(9);
        discount.setDiscountName("支付优惠");
        discount.setDiscountSummary("支付优惠");
        Map<String, Object> map = new HashMap();
        map.put("historyOrder", 1);
        discount.setExtraMap(map);
        discount.setDiscountAmount(order.getDiscountAmount());
        list.add(discount);
        String discountInfo = JSON.toJSONString(Arrays.asList(mapper.map(discount, InnerOrderDiscount.class)));
        order.setDiscountInfo(discountInfo);
    }

    private void buildPay(List<OrderPayDetails> list, Order order) {
        if (!order.getPayStatus().equals(1)) {
            return;
        }
        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.getPayAt());
        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);
    }

    public OrderIndex buildIndex(Order 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());
        return index;
    }

    public Order buildOrder(Master master,
                            List<Order> orderList,
                            List<OrderItem> itemList,
                            List<OrderPayDetails> payList,
                            List<OrderDiscount> disList,
                            Map<String, List<food>> foodMap,
                            Map<String, List<pay>> payMap,
                            Long userId) {
        Order order = buildMasterOrder(master, userId);
        int totalAmount = 0;
        buildChenItem(foodMap, order, itemList);
        buildChenPay(payMap, order, payList);
        buildChenDis(payMap, order, disList);
        orderList.add(order);
        return order;
    }

    private void buildChenDis(Map<String, List<pay>> payMap, Order order, List<OrderDiscount> disList) {
        List<InnerOrderDiscount> innerOrderDiscounts = new ArrayList<>();
        List<pay> pays = payMap.get(order.getOrderNo());
        if (!CollectionUtils.isEmpty(pays)) {
            Map<String, pay> paySubKeyMap = new HashMap<>(pays.size());
            for (pay item : pays) {
                if(Objects.nonNull(paySubKeyMap.get(item.getPaysubjectkey()))){
                    if (paySubKeyMap.get(item.getPaysubjectkey()).getActionstamp().before(item.getActionstamp())) {
                        paySubKeyMap.put(item.getPaysubjectkey(), item);
                    }
                } else {
                    paySubKeyMap.put(item.getPaysubjectkey(), item);
                }
            }

            for (pay item : paySubKeyMap.values()) {
                OrderDiscount orderItem = buildDisChen(disList, item, order);
                if (Objects.nonNull(orderItem)) {
                    innerOrderDiscounts.add(mapper.map(orderItem, InnerOrderDiscount.class));
                }
            }
        }
        if (innerOrderDiscounts.size() > CommonConstants.MAX_ITEM_SIZE) {
            order.setDiscountInfo(CommonConstants.DISCOUNT_FLAG);
        } else {
            order.setDiscountInfo(JSON.toJSONString(innerOrderDiscounts));
        }
    }

    private OrderDiscount buildDisChen(List<OrderDiscount> disList, pay item, Order order) {
        // 1 支付  0 优惠
        if (!Objects.equals(0, item.getIsjoinreceived().intValue())) {
            return null;
        }
        if (bigDecToInteger(item.getPaysubjectalldiscountamount()) <= 0) {
            return null;
        }
        OrderDiscount discount = new OrderDiscount();
        discount.setId(keyGenerator.generateSnowflakeNumKey());
        discount.setBizType(order.getBizType());
        discount.setUserId(order.getUserId());
        discount.setOrderNo(order.getOrderNo());
        discount.setSellerId(order.getSellerId());
        discount.setStatus(0);
        discount.setItemId("-1");
        discount.setDiscountLevel(0);
        discount.setDiscountId("-1");
        Map<String, Object> map = new HashMap();
        map.put("historyOrder", 1);
        discount.setExtraMap(map);
        discount.setDiscountAmount(bigDecToInteger(item.getPaysubjectalldiscountamount()));
        parDis(item, discount);
        disList.add(discount);
        return discount;
    }

    private void parDis(pay item, OrderDiscount discount) {
        String discountName = "会员优惠";
        Integer type = 10;
        if (item.getPaysubjectcode().equals("130000060")) {
            discountName = "优惠券";
            type = 2;
        }
        if (item.getPaysubjectcode().equals("130000059")) {
            discountName = "满减";
            type = 3;
        }
        if (item.getPaysubjectcode().equals("130000065")) {
            discountName = "新客专享";
            type = 11;
        }
        if (item.getPaysubjectcode().equals("130000067")) {
            discountName = "礼品卡";
            type = 6;
        }
        if (item.getPaysubjectcode().equals("130000066")) {
            discountName = "礼品卡";
            type = 6;
        }
        if (item.getPaysubjectcode().equals("130000062")) {
            discountName = "满赠";
            type = 8;
        }
        if (item.getPaysubjectcode().equals("11311022")) {
            discountName = "支付平台商家优惠";
            type = 37;
        }
        if (item.getPaysubjectcode().equals("11311021")) {
            discountName = "支付平台优惠";
            type = 36;
        }
        if (item.getPaysubjectcode().equals("1202101")) {
            discountName = "微信商家优惠";
            type = 37;
        }
        if (item.getPaysubjectcode().equals("1203101")) {
            discountName = "微信平台优惠";
            type = 36;
        }
        if (item.getPaysubjectcode().equals("51010555")) {
            discountName = "会员优惠";
            type = 10;
        }
        if (item.getPaysubjectcode().equals("130000063")) {
            discountName = "满M份N折";
            type = 12;
        }
        if (item.getPaysubjectcode().equals("130000068")) {
            discountName = "限时折扣";
            type = 13;
        }
        if (item.getPaysubjectcode().equals("130000061")) {
            discountName = "特惠加购折扣";
            type = 14;
        }
        if (item.getPaysubjectcode().equals("51010613")) {
            discountName = "积分抵现";
            type = 21;
        }
        if (item.getPaysubjectcode().equals("51010613")) {
            discountName = "减配送费活动";
            type = 24;
        }

        discount.setDiscountName(discountName);
        discount.setDiscountSummary(discountName);
        discount.setDiscountType(type);
    }


    private void buildChenPay(Map<String, List<pay>> payMap, Order order, List<OrderPayDetails> payList) {
        List<InnerOrderPayDetails> innerOrderPayDetails = new ArrayList<>();
        List<pay> pays = payMap.get(order.getOrderNo());
        if (!CollectionUtils.isEmpty(pays)) {
            Map<String, pay> paySubKeyMap = new HashMap<>(pays.size());
            for (pay item : pays) {
                if(Objects.nonNull(paySubKeyMap.get(item.getPaysubjectkey()))){
                    if (paySubKeyMap.get(item.getPaysubjectkey()).getActionstamp().before(item.getActionstamp())) {
                        paySubKeyMap.put(item.getPaysubjectkey(), item);
                    }
                } else {
                    paySubKeyMap.put(item.getPaysubjectkey(), item);
                }
            }

            for (pay item : paySubKeyMap.values()) {
                OrderPayDetails orderItem = buildPayChen(payList, item, order);
                if (Objects.nonNull(orderItem)) {
                    innerOrderPayDetails.add(mapper.map(orderItem, InnerOrderPayDetails.class));
                }
            }
        }
        if (innerOrderPayDetails.size() > CommonConstants.MAX_ITEM_SIZE) {
            order.setPayDetailInfo(CommonConstants.PAY_FLAG);
        } else {
            order.setPayDetailInfo(JSON.toJSONString(innerOrderPayDetails));
        }
        if (innerOrderPayDetails.size() > 1) {
            order.setPayType(99);
        }
    }

    private OrderPayDetails buildPayChen(List<OrderPayDetails> list, pay item, Order order) {
        if (!order.getPayStatus().equals(1)) {
            return null;
        }
        // 1 支付  0 优惠
        if (!Objects.equals(1, item.getIsjoinreceived().intValue())) {
            return null;
        }
        if (bigDecToInteger(item.getPaysubjectreceivedamount()) <= 0) {
            return null;
        }
        OrderPayDetails payDetails = new OrderPayDetails();
        payDetails.setId(keyGenerator.generateSnowflakeNumKey());
        payDetails.setOrderNo(order.getOrderNo());
        payDetails.setUserId(order.getUserId());
        payDetails.setAmount(bigDecToInteger(item.getPaysubjectreceivedamount()));
        payDetails.setPayType(parPayType(item.getPaysubjectcode()));
        payDetails.setStoreId(order.getStoreId());
        payDetails.setSellerId(order.getSellerId());
        payDetails.setOrderAt(order.getOrderAt());
        payDetails.setPayAt(order.getPayAt());
        payDetails.setOrderType(order.getOrderType());
        payDetails.setSource(order.getSource());
        payDetails.setStatus(0);
        payDetails.setPayNo("");
        payDetails.setThirdPayNo("");
        list.add(payDetails);
        return payDetails;
    }

    private Integer parPayType(String str) {
        Integer payType = 7;
        if (Objects.equals("1201101", str)) {
            payType = 1;
        }
        if (Objects.equals("11311020", str)) {
            payType = 2;
        }
        if (Objects.equals("51010611", str)) {
            payType = 4;
        }
        if (Objects.equals("51010609", str)) {
            payType = 4;
        }
        if (Objects.equals("51010530", str)) {
            payType = 103;
        }
        if (Objects.equals("130000072", str)) {
            payType = 103;
        }
        if (Objects.equals("10020050", str)) {
            payType = 15;
        }
        if (Objects.equals("10010001", str)) {
            payType = 12;
        }
        if (Objects.equals("11310020", str)) {
            payType = 25;
        }
        if (Objects.equals("130000071", str)) {
            payType = 25;
        }
        return payType;
    }

    private void buildChenItem(Map<String, List<food>> foodMap, Order order, List<OrderItem> itemList) {
        List<InnerOrderItem> innerOrderItems = new ArrayList<>();
        List<food> foods = foodMap.get(order.getOrderNo());
        if (!CollectionUtils.isEmpty(foods)) {
            Map<String, food> itemKeyMap = new HashMap<>(foods.size());
            for (food item : foods) {
                if(Objects.nonNull(itemKeyMap.get(item.getItemkey()))){
                    if (itemKeyMap.get(item.getItemkey()).getActionstamp().before(item.getActionstamp())) {
                        itemKeyMap.put(item.getItemkey(), item);
                    }
                } else {
                    itemKeyMap.put(item.getItemkey(), item);
                }
            }

            for (food item : itemKeyMap.values()) {
                OrderItem orderItem = itemDefaultChen(itemList, item, order);
                innerOrderItems.add(mapper.map(orderItem, InnerOrderItem.class));
            }
        }
        if (innerOrderItems.size() > CommonConstants.MAX_ITEM_SIZE) {
            order.setItemInfo(CommonConstants.ITEM_FLAG);
        } else {
            order.setItemInfo(JSON.toJSONString(innerOrderItems));
        }
    }
    
    @Autowired
    private ChenUserDao userDao;

    public Order dswOrder(Duoshiwu currOrder) {
        Order order = new Order();
        order.setId(keyGenerator.generateSnowflakeNumKey());
        order.setOrderNo(currOrder.getOrderNo());
        order.setUserId(currOrder.getUserId());
        order.setPayer(currOrder.getUserId());

        // 用户id
        if (order.getUserId() == null) {
            int hashCode = keyGenerator.generateSnowflakeKey().hashCode();
            if (hashCode > 0) {
                hashCode = -hashCode;
            }
            order.setPayer((long)hashCode);
            order.setUserId((long)hashCode);
        }

        order.setOrderType(2);
        order.setTotalAmount(currOrder.getTotalAmount().multiply(new BigDecimal(100)).intValue());
        order.setDiscountAmount(currOrder.getDiscountAmount().multiply(new BigDecimal(100)).intValue());
        order.setActualAmount(currOrder.getActualAmount().multiply(new BigDecimal(100)).intValue());
        order.setPayAmount(currOrder.getPayAmount().multiply(new BigDecimal(100)).intValue());
        order.setItemAmount(currOrder.getPayAmount().multiply(new BigDecimal(100)).intValue());
        order.setPayStatus(1);
        order.setStatus(8);
        order.setSource(8);
        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(1);
        order.setCommentStatus(0);
        order.setPerformanceType(0);
        order.setIsReceipt(0);
        order.setIsImmediatePerformance(0);
        order.setSourceNo("");
        order.setBizType(4);
        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.setMobile(currOrder.getMobile());

        // beta
//        order.setStoreId(1111774L);
//        order.setSellerId(11568L);
        // pro
        order.setStoreId(224671L);
        order.setSellerId(217138L);

        order.setOrderAt(currOrder.getOrderAt());
        order.setPayAt(currOrder.getPayAt());
        order.setCompletedAt(currOrder.getPayAt());
        order.setCreatedAt(new Date());
        order.setUpdatedAt(new Date());
        Map<String, Object> map = new HashMap();
        map.put("historyOrder", 1);
        order.setExtraMap(map);
        return order;
    }

    public Order buildOrderDefault(Momo currOrder) {
        Order order = new Order();
        order.setId(keyGenerator.generateSnowflakeNumKey());
        order.setOrderNo(currOrder.getOrderNo());
        order.setUserId(currOrder.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;
        int intPayAmount = 0;
        //订单总金额 + 实付 + 每一笔的优惠
        if (Objects.nonNull(currOrder.getPayAmount())) {
            BigDecimal multiply = currOrder.getPayAmount().multiply(new BigDecimal(100));
            intPayAmount = Double.valueOf(multiply.toString()).intValue();
        }
        //当前商品实付金额
        int intItemPrice = 0;
//        if (Objects.nonNull(currOrder.getPrice())) {
//            BigDecimal multiply = currOrder.getPrice().multiply(new BigDecimal(100));
//            intItemPrice = Double.valueOf(multiply.toString()).intValue();
//        }
        order.setItemAmount(intItemPrice);
        order.setPayAmount(intPayAmount);
        order.setActualAmount(intPayAmount);
        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(currOrder.getUserId());
        order.setMobile(null);

//        if (Objects.nonNull(currOrder.getPayNo())) {
//            order.setPayNo(currOrder.getPayNo());
//            order.setThirdPayNo(currOrder.getPayNo());
//        }
//        if (Objects.nonNull(currOrder.getSellerRemark())) {
//            order.setSellerRemarks(currOrder.getSellerRemark());
//        }
        order.setSellerId(chenxiangguiSellerId);
        if (Objects.nonNull(currOrder.getStoreId())) {
            order.setStoreId(currOrder.getStoreId());
        }

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

    private OrderItem dswItem(List<OrderItem> itemList, Order currItem) {
        int intDiscountAmount = 0;
        int intItemPrice = 0;
        OrderItem item = new OrderItem();
        item.setId(keyGenerator.generateSnowflakeNumKey());
        item.setBizType(4);
        item.setSellerId(currItem.getSellerId());
        item.setUserId(currItem.getUserId());
        item.setOrderNo(currItem.getOrderNo());
        item.setItemId("-1");
        item.setGoodsId(-1L);
        item.setItemImage("https://images.qmai.cn/s11568/2023/12/07/012f29b6f63a6f6ba4.jpg");
        item.setItemSign("");
        item.setDiscountAmount(currItem.getDiscountAmount());
        item.setItemPrice(currItem.getTotalAmount());
        item.setItemSpec("[]");
        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", currItem.getItemAmount());
        item.setExtraMap(map);
        item.setActivityId(0L);
        item.setIsTimeDiscount(0);
        item.setOrderAt(currItem.getOrderAt());
        item.setProductNo("");
        item.setIsGift(0);
        item.setItemType(0);
        item.setOwnerId(0L);
        item.setBatchingInfo("");
        item.setItemName("哆士屋面包");
        item.setNum(new BigDecimal(1));

        itemList.add(item);
        return item;
    }


    private OrderItem itemDefaultValue(List<OrderItem> itemList, Momo currItem) {
        int intDiscountAmount = 0;
        int intItemPrice = 0;
        OrderItem item = new OrderItem();
        item.setId(keyGenerator.generateSnowflakeNumKey());
        item.setBizType(5);
        item.setUserId(currItem.getUserId());
        item.setOrderNo(currItem.getOrderNo());
        item.setItemId("-1");
        item.setGoodsId(-1L);
        item.setItemImage("https://images.qmai.cn/s11144/2023/07/17/6ec954ae8487400a67.jpeg");
        item.setItemSign("");
        item.setDiscountAmount(intDiscountAmount);
        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(currItem.getCreatedAt());
        item.setProductNo("");
        item.setIsGift(0);
        item.setSellerId(chenxiangguiSellerId);
        item.setItemType(0);
        item.setOwnerId(0L);
        item.setBatchingInfo("");
        item.setItemName("历史消费商品");
        item.setNum(new BigDecimal(1));

        if (!StringUtils.isEmpty(currItem.getItemName())) {
            item.setItemName(currItem.getItemName());
        }
        if (Objects.nonNull(currItem.getNum())) {
            item.setNum(currItem.getNum());
        }
        // 当前商品单价
        if (Objects.nonNull(currItem.getItemPrice())) {
            BigDecimal itemPrice = currItem.getItemPrice().multiply(new BigDecimal(100));
            intItemPrice = Double.valueOf(itemPrice.toString()).intValue();
            item.setItemPrice(intItemPrice);
        }
        // 商品成本价
        if (Objects.nonNull(currItem.getCostPrice())) {
            BigDecimal costPrice = currItem.getCostPrice().multiply(new BigDecimal(100));
            int intCostPrice = Double.valueOf(costPrice.toString()).intValue();
            item.setCostPrice(intCostPrice);
        }
        // 当前商品单个优惠金额
        if (Objects.nonNull(currItem.getTotalItemActualAmount())) {
            BigDecimal actual = currItem.getTotalItemActualAmount().divide(currItem.getNum(), 2, BigDecimal.ROUND_HALF_DOWN).multiply(new BigDecimal(100));
            int intActual = Double.valueOf(actual.toString()).intValue();
            item.setDiscountAmount(intItemPrice - intActual);
        }
        itemList.add(item);
        return item;
    }


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

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

    @Override
    public void selectOrderToTb() {
        final int size = 200;
        int count = 0;
        List<Long> sellerIdList = Arrays.asList(213951L, 216306L, 206198L, 201424L);

        for (Long sellerId : sellerIdList) {

            while (workQueue.remainingCapacity() < 20) {
                logger.info("momoTransfer[queue] size:{}", workQueue.size());
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            executorService.submit(() -> {
                doSelect(sellerId);
            });

        }
        logger.info("selectOrderToTb[end] count:{}", count);
    }

    private void doSelect(Long sellerId) {
        OrderQuery query = new OrderQuery();
        query.setSize(size);
        query.setOrderType(14);
        query.setBizTypeList(Arrays.asList(5, 6));

        int sellerCount = 0;
        query.setSellerId(sellerId);
        for (int i = 0; i < dbSize; i++) {
            for (int j = 0; j < tbSize; j++) {
                Date orderAtStart = null;
                Date orderAtEnd = null;
                String start = "2021-03-01";
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                for (; ; ) {
                    // 一天一天查询
                    Calendar c = getCalendar(start);
                    orderAtStart = DateUtils.getStartDate(c.getTime());
                    orderAtEnd = DateUtils.getEndDate(c.getTime());

                    start = sdf.format(c.getTime());
                    if (new Date().before(orderAtStart)) {
                        break;
                    }
                    query.setOrderAtStart(orderAtStart);
                    query.setOrderAtEnd(orderAtEnd);
                    Long lastId = 0L;

                    for (; ; ) {
                        query.setLastId(lastId);
                        List<Order> orderList = orderManager.selectSync(query, i, j);
                        if (CollectionUtils.isEmpty(orderList)) {
                            logger.info("selectOrderToTb[empty] count:{}, lastId:{}, sellerId:{}, i:{}, j:{}, orderAtStart:{}, orderAtEnd:{}, sellerCount:{}",
                                    count, lastId, sellerId, i, j, sdf.format(orderAtStart), sdf.format(orderAtEnd), sellerCount);
                            break;
                        }
                        List<IdOrderNo> list = new ArrayList<>(size);
                        for (Order order : orderList) {
                            IdOrderNo idOrderNo = new IdOrderNo();
                            idOrderNo.setOrderNo(order.getOrderNo());
                            idOrderNo.setOrderId(order.getId());
                            idOrderNo.setUserId(order.getUserId());
                            idOrderNo.setStoreId(order.getStoreId());
                            idOrderNo.setSellerId(order.getSellerId());
                            idOrderNo.setOrderType(order.getOrderType());
                            list.add(idOrderNo);
                        }
                        idOrderNoDao.insertList(list);
                        lastId = orderList.get(orderList.size() - 1).getId();
                        count += orderList.size();
                        sellerCount += orderList.size();
                        logger.info("selectOrderToTb[running] count:{}, lastId:{}, sellerId:{}, i:{}, j:{}, orderAtStart:{}, orderAtEnd:{}, sellerCount:{}",
                                count, lastId, sellerId, i, j, sdf.format(orderAtStart), sdf.format(orderAtEnd), sellerCount);
                        if (orderList.size() < size) {
                            break;
                        }
                    }
                }
            }
        }
    }

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

    @Override
    public Result chenDel() {
        try {
            logger.info("chenXiangGuiDel[start]");
            int count = 0;
            for (int i = 0; i < dbSize; i++) {
                for (int j = 0; j < tbSize; j++) {
                    orderManager.delOrderBySellerId(chenxiangguiSellerId, dbSize, tbSize);
                    count = count+200;
                    logger.info("chenXiangGuiDel[running], count:{}", count);
                }
            }

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

    @Override
    public Result chen() {
        try {
            logger.info("chenXiangGui[start]");
            Integer lastId = 0;
            for (; ; ) {
                List<Master> orderList = masterDao.selectList(lastId, size);
                if (CollectionUtils.isEmpty(orderList)) {
                    break;
                }
                Result<String> redisData = redisManager.get("stop-chengxianggui-order");
                if (redisData.isStatus() && Objects.nonNull(redisData.getData())) {
                    return Result.successNullData();
                }
                while (workQueue.remainingCapacity() < 20) {
                    logger.info("chenXiangGui[queue] size:{}", workQueue.size());
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                executorService.submit(() -> {
                    doTransferChen(orderList);
                });
                count += orderList.size();
                lastId = orderList.get(orderList.size() - 1).getItemid();
                logger.info("chenXiangGui[start], lastId:{}, orderCount:{},已扫描数据量", lastId, count);

                if (orderList.size() < size) {
                    break;
                }
//                if (count >= 1000000) {
//                    break;
//                }
            }
            logger.info("chenXiangGui[end], lastId:{}, 【累计扫描数据量】orderCount:{}, itemCount:{}, mobileNoUserIdCount:{}",
                    lastId, count, itemCount, mobileNoUserIdCount);
        } catch (Throwable e) {
            logger.error("chenXiangGui[error] failed!, cause by:{}", e);
        }
        return null;
    }

    public static int mobileNoUserIdCount = 0;
    public static int orderNoItemCount = 0;
    public static int chenRealOrders = 0;

    private void doTransferChen(List<Master> ordersAll) {
        try {
            List<Master> orders = new ArrayList<>(size);
            List<String> mobileList = new ArrayList<>(size);
            for (Master master : ordersAll) {
                if (master.getReportdate() > 20230531L) {
                    continue;
                }
                if (master.getOrderstatus() == 40) {
                    if (!StringUtils.isEmpty(master.getUsermobile())) {
                        orders.add(master);
                        mobileList.add(master.getUsermobile());
                    }
                }
            }
            logger.info("chenXiangGui[bening], ThreadName:{}, ordersSize:{}",
                    Thread.currentThread().getName(), orders.size());
            if (CollectionUtils.isEmpty(orders)) {
                return;
            }
            //手机号查企迈用户id
            List<ChenUser> chenUsers = chenUserDao.selectList(mobileList);
            logger.info("chenXiangGui[bening], ThreadName:{}, chenUsersSize:{}",
                    Thread.currentThread().getName(), chenUsers.size());
            if (CollectionUtils.isEmpty(chenUsers)) {
                return;
            }
            Map<String, Long> chenUserMap = new HashMap<>(chenUsers.size());
            for (ChenUser chenUser : chenUsers) {
                chenUserMap.put(chenUser.getMobilePhone(), chenUser.getId());
            }
            //去除手机号码找不到用户的订单，减少查询数据
            List<Master> newOrders = new ArrayList<>(size);
            for (Master master : orders) {
                if (chenUserMap.containsKey(master.getUsermobile())) {
                    newOrders.add(master);
                }
            }

            List<String> orderNoList = newOrders.stream().map(Master::getSaasorderkey).collect(Collectors.toList());
            count += orderNoList.size();

            //三方商品信息 数量大于0的
            List<food> foodList = foodDao.selectList(orderNoList);
            itemCount += foodList.size();
            Map<String, List<food>> foodMap = foodList.stream().collect(Collectors.groupingBy(food::getSaasorderkey));

            //三方支付优惠信息
            List<pay> chenPayList = chenPayDao.selectList(orderNoList);
            Map<String, List<pay>> payMap = chenPayList.stream().collect(Collectors.groupingBy(pay::getSaasorderkey));

            List<Order> orderList = new ArrayList<>(size);
            List<OrderDiscount> disList = new ArrayList<>();
            List<OrderPayDetails> payList = new ArrayList<>();
            List<OrderItem> itemList = new ArrayList<>();
            List<OrderIndex> indexList = new ArrayList<>(size);

            for (Master master : newOrders) {
                List<food> foods = foodMap.get(master.getSaasorderkey());
                if (CollectionUtils.isEmpty(foods)) {
                    logger.info("chenXiangGui[noItem], orderNo:{}",
                            master.getSaasorderkey());
                    orderNoItemCount++;
                    continue;
                }
                if (!chenUserMap.containsKey(master.getUsermobile())) {
                    mobileNoUserIdCount++;
                    logger.info("chenXiangGui[userIdNoMatch], mobile:{}",
                            master.getUsermobile());
                    continue;
                }
                Long userId = chenUserMap.get(master.getUsermobile());

                Order order = buildOrder(
                        master,
                        orderList,
                        itemList,
                        payList,
                        disList,
                        foodMap,
                        payMap,
                        userId
                );
                indexList.add(buildIndex(order));
            }

            // 新增订单
            if (!CollectionUtils.isEmpty(orderList)) {
                orderDao.insertList(orderList);
            }
            // 新增订单索引
            if (!CollectionUtils.isEmpty(indexList)) {
                indexDao.insertList(indexList);
            }
            //批量新增商品
            if (!CollectionUtils.isEmpty(itemList)) {
                itemDao.inserts(itemList);
            }
            //批量新增支付明细
            if (!CollectionUtils.isEmpty(payList)) {
                payDao.insertList(payList);
            }
            //批量新增优惠
            if (!CollectionUtils.isEmpty(disList)) {
                discountDao.inserts(disList);
            }
            searchManager.indexOrder(orderList);
            chenRealOrders += orderList.size();
            logger.info("chenXiangGui[running], ThreadName:{}, lastId:{}, 【累计迁移订单数】chenRealOrders:{}, 【累计迁移商品数】itemCount:{}, 【没有商品的订单数】orderNoItemCount:{}",
                    Thread.currentThread().getName(),
                    ordersAll.get(ordersAll.size() - 1).getItemid(),
                    chenRealOrders,
                    itemCount,
                    orderNoItemCount);
        } catch (Throwable e) {
            //记录下失败订单，后期可以补 todb
            List<OrderNoUser> orderNoUserList = new ArrayList<>(size);
            for (Master master : ordersAll) {
                OrderNoUser orderNoUser  = new OrderNoUser();
                orderNoUser.setOrderNo(master.getSaasorderkey());
                orderNoUserList.add(orderNoUser);
            }
            if (!CollectionUtils.isEmpty(orderNoUserList)) {
                orderNoUserDao.insertList(orderNoUserList);
            }
            logger.error("chenXiangGui[chenXiangGuiErro] failed!, cause by:{}", e);
        }
    }

    public Order buildOrder(List<Momo> momoList, List<Order> orderList, List<OrderItem> itemList,
                            List<OrderPayDetails> payList,
                            List<OrderDiscount> disList) {
        Order order = buildOrderDefault(momoList.get(0));
        int totalAmount = 0;
        List<InnerOrderItem> innerOrderItems = new ArrayList<>(momoList.size());
        for (Momo momo : momoList) {
            OrderItem orderItem = itemDefaultValue(itemList, momo);
            innerOrderItems.add(mapper.map(orderItem, InnerOrderItem.class));
            if (Objects.nonNull(momo.getItemPrice())) {
                BigDecimal each = momo.getItemPrice().multiply(new BigDecimal(100));
                BigDecimal xiaoji = each.multiply(momo.getNum());
                int xiaojiInt = Double.valueOf(xiaoji.toString()).intValue();
                totalAmount += xiaojiInt;
            }
        }
        order.setTotalAmount(totalAmount);
        order.setItemAmount(totalAmount);
        order.setDiscountAmount(totalAmount - order.getPayAmount());
        if (innerOrderItems.size() > CommonConstants.MAX_ITEM_SIZE) {
            order.setItemInfo(CommonConstants.ITEM_FLAG);
        } else {
            order.setItemInfo(JSON.toJSONString(innerOrderItems));
        }

        buildPay(payList, order);
        buildDiscount(disList, order);
        orderList.add(order);
        return order;
    }


    public Order buildMasterOrder(Master currOrder, Long userId) {
        Order order = new Order();
        order.setId(keyGenerator.generateSnowflakeNumKey());
        order.setOrderNo(currOrder.getSaasorderkey());
        order.setUserId(userId);
        order.setOrderType(1);
        order.setDiscountAmount(0);
        order.setActualAmount(0);
        order.setPayAmount(0);
        order.setItemAmount(0);
        order.setPayStatus(1);
        order.setStatus(50);
        order.setSource(1);
        int intDiscountAmount = 0;
        int intPayAmount = 0;
        //当前商品实付金额
        int intItemPrice = 0;
//        if (Objects.nonNull(currOrder.getPrice())) {
//            BigDecimal multiply = currOrder.getPrice().multiply(new BigDecimal(100));
//            intItemPrice = Double.valueOf(multiply.toString()).intValue();
//        }
        order.setItemAmount(intItemPrice);
        order.setPayAmount(intPayAmount);
        order.setActualAmount(intPayAmount);
        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(order.getUserId());
        order.setMobile(null);
        order.setStoreId(0L);

//        if (Objects.nonNull(currOrder.getPayNo())) {
//            order.setPayNo(currOrder.getPayNo());
//            order.setThirdPayNo(currOrder.getPayNo());
//        }
//        if (Objects.nonNull(currOrder.getSellerRemark())) {
//            order.setSellerRemarks(currOrder.getSellerRemark());
//        }
        order.setSellerId(chenxiangguiSellerId);
        if (MapConstChenStore.map.containsKey(currOrder.getShopid())) {
            order.setStoreId(MapConstChenStore.map.get(currOrder.getShopid()));
        }

        Date date = parDate(currOrder.getStarttime().toString());
        if (Objects.isNull(date)) {
            date = currOrder.getActionstamp();
        }
        order.setOrderAt(date);
        order.setCreatedAt(date);
        order.setPayAt(date);
        order.setCompletedAt(date);
        order.setUpdatedAt(new Date());
        Map<String, Object> map = new HashMap();
        map.put("historyOrder", 1);
        if (!StringUtils.isEmpty(currOrder.getShopname())) {
            Map<String, Object> shopMap = new HashMap();
            shopMap.put("name", currOrder.getShopname());
            map.put("shopInfo", shopMap);
        }
        if (!StringUtils.isEmpty(currOrder.getUsername())) {
            Map<String, Object> userMap = new HashMap();
            userMap.put("userName", currOrder.getUsername());
            map.put("userInfo", userMap);
        }
        if (!StringUtils.isEmpty(currOrder.getTablename())) {
            map.put("tableName", currOrder.getTablename());
            map.put("seatName", currOrder.getTablename());
        }
        order.setExtraMap(map);

        order.setMobile(currOrder.getUsermobile());
        order.setSource(parSource(currOrder.getChannelkey()));
        order.setOrderType(parOrderType(currOrder.getOrdersubtype()));
        order.setTotalAmount(bigDecToInteger(currOrder.getFoodamount()));
        order.setItemAmount(bigDecToInteger(currOrder.getFoodamount()));
        order.setDiscountAmount(bigDecToInteger(currOrder.getPromotionamount()));
        order.setPayAmount(bigDecToInteger(currOrder.getPaidamount()));
        order.setActualAmount(order.getPayAmount());
        return order;
    }

    private Integer parOrderType(Byte subType) {
        if (Objects.isNull(subType)) {
            return 1;
        }
        int i = subType.intValue();
        if (Objects.equals(0, i)) {
            return 1;
        }
        if (Objects.equals(21, i)) {
            return 3;
        }
        return 1;
    }

    private Integer parSource(String channelKey) {
        if (Objects.equals("399_weixin", channelKey)) {
            return 1;
        }
        if (Objects.equals("399_zhifubao", channelKey)) {
            return 2;
        }
        if (Objects.equals("100_pos", channelKey)) {
            return 8;
        }
        return 1;
    }

    public Date parDate(String time) {
        Date date1 = null;
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHssnn");
            Date date = format.parse(time);
            SimpleDateFormat newFormat = new SimpleDateFormat("yyyy-MM-dd HH:ss:nn");
            String format1 = newFormat.format(date);
            date1 = newFormat.parse(format1);
        } catch (Throwable throwable) {

        }
        return date1;
    }

    public int bigDecToInteger(BigDecimal amount) {
        int res = 0;
        if (Objects.nonNull(amount)) {
            BigDecimal multiply = amount.multiply(new BigDecimal(100));
            res = Double.valueOf(multiply.toString()).intValue();
        }
        return res;

    }


    private OrderItem itemDefaultChen(List<OrderItem> itemList, food currItem, Order order) {
        int intDiscountAmount = 0;
        int intItemPrice = 0;
        OrderItem item = new OrderItem();
        item.setId(keyGenerator.generateSnowflakeNumKey());
        item.setBizType(5);
        item.setUserId(order.getUserId());
        item.setOrderNo(order.getOrderNo());
        item.setItemId("-1");
        item.setGoodsId(-1L);
        item.setItemImage("https://images.qmai.cn/s11144/2023/07/17/6ec954ae8487400a67.jpeg");
        item.setItemSign("");
        item.setDiscountAmount(intDiscountAmount);
        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(order.getCreatedAt());
        item.setProductNo("");
        item.setIsGift(0);
        item.setSellerId(order.getSellerId());
        item.setItemType(0);
        item.setOwnerId(0L);
        item.setBatchingInfo("");
        item.setItemName("历史消费商品");
        item.setNum(new BigDecimal(1));

        if (!StringUtils.isEmpty(currItem.getFoodname())) {
            item.setItemName(currItem.getFoodname());
        }
        if (Objects.nonNull(currItem.getFoodnumber())) {
            item.setNum(currItem.getFoodnumber());
        }
        // 当前商品单价
        if (Objects.nonNull(currItem.getFoodproprice())) {
            item.setItemPrice(bigDecToInteger(currItem.getFoodproprice()));
        }

        // 当前商品单个优惠金额
        if (Objects.nonNull(currItem.getFoodrealamount())) {
            int i = item.getItemPrice() - bigDecToInteger(currItem.getFoodrealamount());
            if (i > 0) {
                BigDecimal multiply = item.getNum().multiply(new BigDecimal(i));
                item.setDiscountAmount(multiply.intValue());
            }
        }
        itemList.add(item);
        return item;
    }
}

