package com.tmerclub.cloud.order.feign;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.tmerclub.cloud.api.multishop.bo.OrderChangeShopWalletAmountBO;
import com.tmerclub.cloud.api.order.bo.UserScoreLogOrderBO;
import com.tmerclub.cloud.api.order.constant.OrderStatus;
import com.tmerclub.cloud.api.order.dto.CustomerRetainedDTO;
import com.tmerclub.cloud.api.order.dto.FlowOrderItemDTO;
import com.tmerclub.cloud.api.order.dto.FormExcelDTO;
import com.tmerclub.cloud.api.order.dto.QueryOrderDTO;
import com.tmerclub.cloud.api.order.feign.OrderFeignClient;
import com.tmerclub.cloud.api.order.vo.*;
import com.tmerclub.cloud.api.seckill.feign.SeckillFeignClient;
import com.tmerclub.cloud.api.user.bo.UserOrderStatisticBO;
import com.tmerclub.cloud.api.user.bo.UserOrderStatisticListBO;
import com.tmerclub.cloud.api.user.dto.MemberReqDTO;
import com.tmerclub.cloud.api.vo.EsPageVO;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.i18n.LanguageEnum;
import com.tmerclub.cloud.common.leaf.manager.SegmentManager;
import com.tmerclub.cloud.api.order.dto.SaveOrderToMallDTO;
import com.tmerclub.cloud.common.order.bo.EsOrderBO;
import com.tmerclub.cloud.common.order.bo.OrderIdWithRefundIdBO;
import com.tmerclub.cloud.common.order.bo.OrderStatusBO;
import com.tmerclub.cloud.common.order.constant.DeliveryType;
import com.tmerclub.cloud.common.order.constant.OrderType;
import com.tmerclub.cloud.common.order.constant.RefundStatusEnum;
import com.tmerclub.cloud.common.order.dto.OrderDTO;
import com.tmerclub.cloud.common.order.dto.OrderSearchDTO;
import com.tmerclub.cloud.common.order.dto.OrderVirtualInfoDTO;
import com.tmerclub.cloud.common.order.vo.*;
import com.tmerclub.cloud.common.response.ResponseEnum;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.rocketmq.config.RocketMqConstant;
import com.tmerclub.cloud.common.util.BeanUtil;
import com.tmerclub.cloud.constant.DistributedIdKey;
import com.tmerclub.cloud.order.manager.MongoOrderManager;
import com.tmerclub.cloud.order.mapper.OrderItemLangMapper;
import com.tmerclub.cloud.order.mapper.OrderItemMapper;
import com.tmerclub.cloud.order.mapper.OrderMapper;
import com.tmerclub.cloud.order.model.Order;
import com.tmerclub.cloud.order.model.OrderItem;
import com.tmerclub.cloud.order.model.OrderItemLang;
import com.tmerclub.cloud.order.service.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.GenericMessage;

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

/**
 * @author tmerclub
 * @date 2020/12/25
 */
@DubboService
public class OrderFeignController implements OrderFeignClient {

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

    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private OrderItemLangMapper orderItemLangMapper;
    @Autowired
    private OrderAnalysisService orderAnalysisService;
    @Autowired
    private OrderStatisticsService orderStatisticsService;
    @Autowired
    private MongoOrderManager mongoOrderManager;
    @Autowired
    private RocketMQTemplate orderSettledShopTemplate;
    @Autowired
    private RocketMQTemplate orderSettlementShopByAllinpayTemplate;
    @Autowired
    private RocketMQTemplate orderReceiptTemplate;
    @Autowired
    private OrderAllinpayService orderAllinpayService;
    @Autowired
    private OrderVirtualInfoService orderVirtualInfoService;
    @Autowired
    private SegmentManager segmentManager;
    @DubboReference
    private SeckillFeignClient seckillFeignClient;
    @Autowired
    private RocketMQTemplate orderCancelTemplate;

    @Override
    public ServerResponseEntity<OrderAmountVO> getOrdersAmountAndIfNoCancel(List<Long> orderIds, Long userId) {
        List<OrderStatusBO> orderStatus = orderService.getOrdersStatus(orderIds);

        if (CollectionUtil.isEmpty(orderStatus)) {
            // 查询一下redis有没有数据,因为秒杀订单还存在redis
            ServerResponseEntity<ShopCartOrderMergerVO> seckillOrderByRedisResp = seckillFeignClient.getSeckillOrderByRedis(orderIds.get(0), userId);
            if (!seckillOrderByRedisResp.isSuccess()) {
                throw new LuckException(seckillOrderByRedisResp.getMsg());
            }
            if (Objects.isNull(seckillOrderByRedisResp.getData())) {
                return ServerResponseEntity.fail(ResponseEnum.ORDER_NOT_EXIST);
            }
            ShopCartOrderMergerVO shopCartOrderMergerVO = seckillOrderByRedisResp.getData();
            ShopCartOrderVO shopCartOrderVO = shopCartOrderMergerVO.getShopCartOrders().get(0);
            OrderAmountVO orderAmountVO = new OrderAmountVO();
            orderAmountVO.setPayAmount(shopCartOrderMergerVO.getActualTotal());
            orderAmountVO.setPayScore(0L);

            // 添加下收款人和金额
            ShopAmountVO shopAmountVO = new ShopAmountVO();
            shopAmountVO.setBizUserId(shopCartOrderVO.getShopId().toString());
            shopAmountVO.setAmount(shopCartOrderMergerVO.getActualTotal());

            orderAmountVO.setShopAmountList(Collections.singletonList(shopAmountVO));
            return ServerResponseEntity.success(orderAmountVO);
        }
        for (OrderStatusBO orderStatusBO : orderStatus) {
            // 订单已关闭
            if (orderStatusBO.getStatus() == null || Objects.equals(orderStatusBO.getStatus(), OrderStatus.CLOSE.value())) {
                return ServerResponseEntity.showFailMsg("订单已关闭");
            }
        }
        OrderAmountVO orderAmountVO = orderService.getOrdersActualAmount(orderIds);
        return ServerResponseEntity.success(orderAmountVO);
    }

    @Override
    public ServerResponseEntity<OrderAmountVO> getOrdersAmountAndCheckOrderStatus(List<Long> orderIds) {
        if (CollUtil.isEmpty(orderIds)) {
            return ServerResponseEntity.showFailMsg("订单id列表不能为空");
        }
        List<OrderStatusBO> orderStatus = orderService.getOrdersStatus(orderIds);
        if (CollectionUtil.isEmpty(orderStatus)) {
            return ServerResponseEntity.fail(ResponseEnum.ORDER_NOT_EXIST);
        }

        for (OrderStatusBO statusBO : orderStatus) {
            // 如果现在时间大于尾款时间，尾款时间已过期不能支付
            boolean dateCheck = DateUtil.compare(new Date(), statusBO.getBalanceEndTime()) > 0;
            // 订单状态不可支付尾款，请稍后再试
            if (statusBO.getStatus() == null || !Objects.equals(statusBO.getStatus(), OrderStatus.WAIT_BALANCE.value()) || dateCheck) {
                return ServerResponseEntity.showFailMsg("订单状态不可支付尾款，请稍后再试");
            }
        }
        OrderAmountVO orderAmountVO = orderService.getOrdersActualAmount(orderIds);
        return ServerResponseEntity.success(orderAmountVO);
    }

    @Override
    public ServerResponseEntity<List<OrderStatusBO>> getOrdersStatus(List<Long> orderIds) {
        List<OrderStatusBO> orderStatus = orderService.getOrdersStatus(orderIds);
        return ServerResponseEntity.success(orderStatus);
    }

    @Override
    public ServerResponseEntity<List<OrderSimpleAmountInfoBO>> getOrdersSimpleAmountInfo(List<Long> orderIds) {
        return ServerResponseEntity.success(orderService.getOrdersSimpleAmountInfo(orderIds));
    }

    @Override
    public ServerResponseEntity<EsOrderBO> getEsOrder(Long orderId) {
        EsOrderBO esOrderBO = orderService.getEsOrder(orderId);
        return ServerResponseEntity.success(esOrderBO);
    }

    @Override
    public void submit(ShopCartOrderMergerVO mergerOrder) {
        // 发送消息，如果三十分钟后没有支付，则取消订单
        Long orderId = mergerOrder.getShopCartOrders().get(0).getOrderId();
        SendStatus sendStatus = orderCancelTemplate.syncSend(RocketMqConstant.ORDER_CANCEL_TOPIC, new GenericMessage<>(Collections.singletonList(orderId)), RocketMqConstant.TIMEOUT, RocketMqConstant.CANCEL_ORDER_DELAY_LEVEL).getSendStatus();
        if (!Objects.equals(sendStatus, SendStatus.SEND_OK)) {
            // 消息发不出去就抛异常
            throw new LuckException(ResponseEnum.EXCEPTION);
        }
        // 目前用于团购活动的提交订单
        orderService.submit(mergerOrder);
    }

    @Override
    public ServerResponseEntity<List<UserOrderStatisticVO>> countOrderByUserIds(QueryOrderDTO queryOrderDTO) {
        Long shopId = queryOrderDTO.getShopId() == null ? 0L : queryOrderDTO.getShopId();
        return ServerResponseEntity.success(orderStatisticsService.countOrderByUserIds(queryOrderDTO.getUserIds(), shopId));
    }

    @Override
    public ServerResponseEntity<OrderCountVO> countOrderByUserId(Long userId) {
        OrderCountVO orderCount = orderService.countNumberOfStatus(userId);
        return ServerResponseEntity.success(orderCount);
    }

    @Override
    public ServerResponseEntity<List<Long>> getOrderUserIdsBySearchDTO(OrderSearchDTO orderSearchDTO) {
        return ServerResponseEntity.success(orderStatisticsService.getOrderUserIdsBySearchDTO(orderSearchDTO));
    }

    @Override
    public ServerResponseEntity<List<Long>> listUserIdByPurchaseNum(Integer isPayed, Integer deleteStatus, Date startDate, Date endDate, Integer status, Long minNum, Long maxNum) {
        List<Long> userIds = orderStatisticsService.listUserIdByPurchaseNum(isPayed, deleteStatus, startDate, endDate, status, minNum, maxNum);
        return ServerResponseEntity.success(userIds);
    }

    @Override
    public ServerResponseEntity<List<Long>> listUserIdByAverageActualTotal(Integer isPayed, Integer deleteStatus, Date startDate, Date endDate, Integer status, Long minAmount, Long maxAmount) {
        List<Long> userIds = orderStatisticsService.listUserIdByAverageActualTotal(isPayed, deleteStatus, startDate, endDate, status, minAmount, maxAmount);
        return ServerResponseEntity.success(userIds);
    }

    @Override
    public ServerResponseEntity<List<OrderProdEffectRespVO>> getProdEffectByDateAndProdIds(List<Long> spuIds, Long startTime, Long endTime) {
        return ServerResponseEntity.success(orderStatisticsService.getProdEffectByDateAndProdIds(spuIds, new Date(startTime), new Date(endTime)));
    }

    @Override
    public ServerResponseEntity<List<CustomerRetainVO>> getTradeRetained(CustomerRetainedDTO customerRetainedDTO) {
        List<CustomerRetainVO> list = orderAnalysisService.getTradeRetained(customerRetainedDTO);
        return ServerResponseEntity.success(list);
    }

    @Override
    public ServerResponseEntity<List<FlowOrderVO>> listFlowOrderByOrderIds(Collection<Long> orderIds) {
        if (CollUtil.isEmpty(orderIds)) {
            return ServerResponseEntity.success(new ArrayList<>(0));
        }
        List<FlowOrderVO> orderList = orderStatisticsService.listFlowOrderByOrderIds(orderIds);
        return ServerResponseEntity.success(orderList);
    }

    @Override
    public ServerResponseEntity<UserOrderStatisticBO> getPaidMemberByParam(MemberReqDTO param) {
        return ServerResponseEntity.success(orderStatisticsService.getPaidMemberByParam(param));
    }

    @Override
    public ServerResponseEntity<UserOrderStatisticListBO> getMemberPayData(MemberReqDTO param) {
        UserOrderStatisticListBO userOrderStatisticListBO = orderStatisticsService.getMemberPayData(param);
        return ServerResponseEntity.success(userOrderStatisticListBO);
    }

    @Override
    public ServerResponseEntity<Void> removeCacheTradeRetained(CustomerRetainedDTO customerRetainedDTO) {
        orderAnalysisService.removeCacheTradeRetained(customerRetainedDTO);
        return ServerResponseEntity.success();
    }

    @Override
    public void updateOrderItemBatchById(List<OrderItemVO> orderItemVOList) {
        List<OrderItem> orderItems = BeanUtil.mapAsList(orderItemVOList, OrderItem.class);
        for (OrderItem orderItem : orderItems) {
            orderItemMapper.update(orderItem);
        }
    }

    @Override
    public EsOrderBO getEsOrderInfo(Long orderId) {
        return orderService.getEsOrderInfo(orderId);
    }


    @Override
    public ServerResponseEntity<SendNotifyBO> getOrderDetailInfo(Long orderId) {
        return ServerResponseEntity.success(orderService.getOrderInfoByOrderId(orderId));
    }

    @Override
    public ServerResponseEntity<Integer> countNormalOrderByOrderIds(List<Long> orderIds) {
        int count = orderMapper.countNormalOrderByOrderIds(orderIds);
        ;
        return ServerResponseEntity.success(count);
    }

    @Override
    public ServerResponseEntity<List<SumAmountVO>> listSumDataByUserIds(List<Long> userIds) {
        return ServerResponseEntity.success(orderStatisticsService.listSumDataByUserIds(userIds));
    }

    @Override
    public ServerResponseEntity<Long> hasBuySuccessProd(Long spuId, Long userId) {
        return ServerResponseEntity.success(orderStatisticsService.hasBuySuccessProd(spuId, userId));
    }

    @Override
    public ServerResponseEntity<UserShoppingDataVO> calculateUserInShopData(Long userId) {
        return ServerResponseEntity.success(orderStatisticsService.calculateUserInShopData(userId));
    }

    @Override
    public ServerResponseEntity<Long> sumTotalDistributionAmountByOrderItem(List<OrderItemVO> orderItems) {
        // 订单总分销金额
        BigDecimal totalDistributionAmount = new BigDecimal(Constant.ZERO_LONG.toString());
        if (CollectionUtil.isNotEmpty(orderItems)) {
            for (OrderItemVO orderItem : orderItems) {
                if (Objects.isNull(orderItem.getDistributionUserId())) {
                    continue;
                }
                // 如果改订单项已经退款了的话，分销员的佣金就已经回退了，不需要继续算钱
                if (Objects.equals(orderItem.getRefundStatus(), RefundStatusEnum.SUCCEED.value()) || Objects.equals(orderItem.getRefundStatus(), RefundStatusEnum.PARTIAL_SUCCESS.value())) {
                    continue;
                }
                // 分销佣金
                if (orderItem.getDistributionAmount() != null && orderItem.getDistributionAmount() > 0) {
                    totalDistributionAmount = totalDistributionAmount.add(new BigDecimal(orderItem.getDistributionAmount().toString()));
                }
                // 上级分销佣金
                if (orderItem.getDistributionParentAmount() != null && orderItem.getDistributionParentAmount() > 0) {
                    totalDistributionAmount = totalDistributionAmount.add(new BigDecimal(orderItem.getDistributionParentAmount().toString()));
                }
            }
        }
        return ServerResponseEntity.success(totalDistributionAmount.longValue());
    }

    @Override
    public ServerResponseEntity<List<OrderItemVO>> listOrderItemByOrderIds(List<Long> orderIds) {
        if (CollUtil.isEmpty(orderIds)) {
            return ServerResponseEntity.success(new ArrayList<>(0));
        }
        return ServerResponseEntity.success(orderItemMapper.listOrderItemByOrderIds(orderIds));
    }

    @Override
    public ServerResponseEntity<List<Long>> getInsightSpuIdsByDate(Integer begin, Integer size, Long shopId, Long startTime, Long endTime) {
        List<Long> spuIds = orderStatisticsService.getInsightSpuIdsByDate(begin, size, shopId, new Date(startTime), new Date(endTime));
        return ServerResponseEntity.success(spuIds);
    }

    @Override
    public ServerResponseEntity<List<UserScoreLogOrderBO>> getUserScoreLogDetail(List<Long> orderIds) {
        return ServerResponseEntity.success(orderItemService.getUserScoreLogDetail(orderIds));
    }

    @Override
    public ServerResponseEntity<Void> settledOrder(List<OrderChangeShopWalletAmountBO> orderChangeShopWalletAmountList) {
        List<Long> orderIds = orderChangeShopWalletAmountList.stream().map(OrderChangeShopWalletAmountBO::getOrderId).filter(Objects::nonNull).toList();
        // 开启事务消息，通知订单自己，开始往各个服务发送通知了
        TransactionSendResult transactionSendResult = orderSettledShopTemplate.sendMessageInTransaction(RocketMqConstant.ORDER_SETTLED_SHOP_TOPIC, new GenericMessage<>(orderChangeShopWalletAmountList), orderIds);

        if (!Objects.equals(transactionSendResult.getLocalTransactionState(), LocalTransactionState.COMMIT_MESSAGE)) {
            throw new LuckException(ResponseEnum.EXCEPTION);
        }
        return ServerResponseEntity.success();
    }

    @Override
    public ServerResponseEntity<Void> confirmOrder(List<Long> orderIds) {
        for (Long orderId : orderIds) {
            // 开启事务消息，通知订单自己，开始往各个服务发送通知了
            TransactionSendResult transactionSendResult = orderReceiptTemplate.sendMessageInTransaction(RocketMqConstant.ORDER_RECEIPT_TOPIC, new GenericMessage<>(orderId), null);

            if (!Objects.equals(transactionSendResult.getLocalTransactionState(), LocalTransactionState.COMMIT_MESSAGE)) {
                throw new LuckException(ResponseEnum.EXCEPTION);
            }
        }
        return ServerResponseEntity.success();
    }

    @Override
    public ServerResponseEntity<OrderActivityVO> getActivityOrderInfo(Long orderId) {
        OrderActivityVO orderVO = orderMapper.getActivityOrderInfo(orderId);
        if (Objects.isNull(orderVO)) {
            throw new LuckException("订单不存在, 订单id：" + orderId);
        }
        OrderItemVO orderItemVO = orderVO.getOrderItems().get(0);
        orderVO.setActivityId(orderItemVO.getActivityId());
        orderVO.setActivityType(orderItemVO.getActivityType());
        orderVO.setSpuId(orderItemVO.getSpuId());
        orderVO.setSkuId(orderItemVO.getSkuId());
        orderVO.setCount(orderItemVO.getCount());
        orderVO.setUserId(orderVO.getUserId());
        return ServerResponseEntity.success(orderVO);
    }

    @Override
    public ServerResponseEntity<Integer> getUserBuyNumByActivityId(Long activityId, Integer activityType, Long spuId, Long userId) {
        Integer num = orderMapper.getUserBuyNumByActivityId(activityId, activityType, spuId, userId);
        if (Objects.isNull(num)) {
            num = 0;
        }
        return ServerResponseEntity.success(num);
    }

    @Override
    public List<OrderActivityVO> getActivitySalesQuantity(List<Long> orderIds, Integer activityType) {
        if (CollUtil.isEmpty(orderIds)) {
            throw new LuckException("订单id不能为空");
        }
        List<OrderItemVO> orderItemList = orderItemMapper.listOrderItemByOrderIds(orderIds);
        List<Long> activityIds = orderItemList.stream()
                .filter(orderItemVO -> Objects.equals(orderItemVO.getActivityType(), activityType) && Objects.nonNull(orderItemVO.getActivityId()))
                .map(OrderItemVO::getActivityId)
                .collect(Collectors.toList());
        if (CollUtil.isEmpty(activityIds)) {
            return Collections.emptyList();
        }
        List<OrderActivityVO> orderActivityList = orderStatisticsService.getActivitySalesQuantity(activityIds, activityType);
        if (CollUtil.isEmpty(orderActivityList)) {
            logger.error("套餐订单数量统计-无套餐统计结果， 套餐活动ids：{}", activityIds);
        }
        return orderActivityList;
    }

    @Override
    public ServerResponseEntity<List<EsOrderVO>> getUserByOrderIdList(List<Long> orderIds) {
        return ServerResponseEntity.success(orderMapper.getUserByOrderIdList(orderIds));
    }

    @Override
    public ServerResponseEntity<Integer> countActivityOrderSale(Long activityId, Integer activityType) {
        return countActivitySkuSale(null, activityId, activityType);
    }

    @Override
    public ServerResponseEntity<Integer> countActivitySkuSale(Long skuId, Long activityId, Integer activityType) {
        if (Objects.isNull(activityId)) {
            throw new LuckException("活动id不能为空");
        }
        if (Objects.isNull(activityType)) {
            throw new LuckException("活动类型不能为空");
        }
        Long activityOrderSale = orderStatisticsService.countActivityOrderSale(skuId, activityId, activityType);
        return ServerResponseEntity.success(activityOrderSale.intValue());
    }

    @Override
    public ServerResponseEntity<List<OrderVO>> listOrderAndOrderItemByOrderIds(List<Long> orderIds) {
        if (CollUtil.isEmpty(orderIds)) {
            return ServerResponseEntity.success(new ArrayList<>(0));
        }
        List<OrderVO> orderVOList = orderMapper.listOrderAndOrderItemByOrderIds(orderIds);
        return ServerResponseEntity.success(orderVOList);
    }

    @Override
    public ServerResponseEntity<AccountOrderDetailVO> getAccountOrderDetail(Date startTime, Date endTime, String shopName, Long shopId) {
        AccountOrderDetailVO accountOrderDetail = orderStatisticsService.getAccountOrderDetail(startTime, endTime, shopName, shopId);
        return ServerResponseEntity.success(accountOrderDetail);
    }

    @Override
    public ServerResponseEntity<PageShopAccountOrderVO> listShopAccountDetail(Date startTime, Date endTime, String shopName, Integer pageSize, Integer pageNum) {
        PageShopAccountOrderVO list = orderStatisticsService.listShopAccountDetail(startTime, endTime, shopName, pageSize, pageNum);
        return ServerResponseEntity.success(list);
    }

    @Override
    public ServerResponseEntity<PageShopAccountOrderVO> listOrderPayInfo(Date startTime, Date endTime, Long shopId, String shopName, Integer pageSize, Integer pageNum) {
        PageShopAccountOrderVO list = orderStatisticsService.listOrderPayInfo(startTime, endTime, shopId, shopName, pageSize, pageNum);
        return ServerResponseEntity.success(list);
    }

    @Override
    public List<FormExcelDTO> listFormExcelByParam(FormExcelParamVO formExcelParamVO) {
        return orderStatisticsService.listFormExcel(formExcelParamVO);
    }

    @Override
    public ServerResponseEntity<List<Long>> getSoldNumRankByShopIdAndTime(String key, Long shopId, Integer time, Integer expireTime, Integer esRenovationSpuSort, Long primaryCategoryId) {
        return ServerResponseEntity.success(orderStatisticsService.addSoldNumRankCacheByShopIdAndTime(key, shopId, time, expireTime, esRenovationSpuSort, primaryCategoryId));
    }

    @Override
    public ServerResponseEntity<GroupInfoVO> getGroupInfoById(Long groupActivityId) {
        return ServerResponseEntity.success(orderStatisticsService.getGroupInfo(groupActivityId));
    }

    @Override
    public ServerResponseEntity<List<EsOrderVO>> getStationOrderBySeachDTO(OrderSearchDTO orderSearchDTO) {
        orderSearchDTO.setDeliveryType(DeliveryType.STATION.value());
        EsPageVO<EsOrderVO> esPageVO = orderService.orderPage(orderSearchDTO);
        return ServerResponseEntity.success(esPageVO.getList());
    }

    @Override
    public ServerResponseEntity<Boolean> orderStationByOrderId(List<Long> orderIds, Long stationId) throws LuckException {
        orderService.orderStationByOrderId(orderIds, null, stationId);
        return ServerResponseEntity.success(Boolean.TRUE);
    }

    @Override
    public ServerResponseEntity<List<OrderVO>> listStationOrder(OrderDTO orderDTO) {
        return ServerResponseEntity.success(orderService.listStationOrder(orderDTO));
    }

    @Override
    public ServerResponseEntity<Boolean> orderWriteOffByOrderId(OrderVirtualInfoDTO orderVirtualInfoDTO, Long orderId, Long statinoId) {
        Order order = orderService.getByOrderId(orderId);
        if (Objects.isNull(order) || order.getOrderMold() == 0) {
            // 订单不存在
            throw new LuckException("订单不存在");
        }
        orderVirtualInfoService.orderWriteOffByOrderId(orderVirtualInfoDTO, order, statinoId);
        return ServerResponseEntity.success(Boolean.TRUE);
    }

    @Override
    public void deleteAllinpayCache() {
        orderAllinpayService.deleteAllinpayCache();
    }

    @Override
    public ServerResponseEntity<Void> settledOrderByAllinpay(List<OrderChangeShopWalletAmountBO> orderList) {
        // 开启消息
        SendStatus sendStatus = orderSettlementShopByAllinpayTemplate.syncSend(RocketMqConstant.ORDER_SETTLED_SHOP_BY_ALLINPAY_TOPIC, new GenericMessage<>(orderList)).getSendStatus();
        if (!Objects.equals(sendStatus, SendStatus.SEND_OK)) {
            // 消息发不出去就抛异常
            throw new LuckException(ResponseEnum.EXCEPTION);
        }
        return ServerResponseEntity.success();
    }

    @Override
    public ServerResponseEntity<List<OrderIdWithRefundIdBO>> listWaitPurchaseAndUnPayBalanceOrderIds(Integer paySysType) {
        List<OrderVO> orderList = orderMapper.listWaitPurchaseAndUnPayBalanceOrderIds(paySysType);
        List<OrderIdWithRefundIdBO> orderIdWithRefundIdList = new ArrayList<>();
        for (OrderVO orderVO : orderList) {
            Long segmentId = segmentManager.getSegmentIdWithDateTime(DistributedIdKey.tmerclub_REFUND, orderVO.getUserId());
            OrderIdWithRefundIdBO orderIdWithRefundIdBO = new OrderIdWithRefundIdBO();
            orderIdWithRefundIdBO.setOrderId(orderVO.getOrderId());
            orderIdWithRefundIdBO.setRefundId(segmentId);
            orderIdWithRefundIdBO.setShopId(orderVO.getShopId());
            orderIdWithRefundIdList.add(orderIdWithRefundIdBO);
        }

        return ServerResponseEntity.success(orderIdWithRefundIdList);
    }

    @Override
    public ServerResponseEntity<OrderSearchDTO> checkOrderSearchInfo(OrderSearchDTO orderSearchDTO) {
        orderService.checkShopName(orderSearchDTO);
        orderService.checkSupplierName(orderSearchDTO);
        return ServerResponseEntity.success(orderSearchDTO);
    }

    @Override
    public List<OrderVO> listOrderByOrderIds(List<Long> orderIds) {
        if (CollUtil.isEmpty(orderIds)) {
            return new ArrayList<>();
        }
        List<OrderVO> orderList = orderMapper.listOrderByOrderIds(orderIds);
        return orderList;
    }

    @Override
    public List<FlowOrderItemVO> listFlowOrderItems(FlowOrderItemDTO flowOrderItemDTO) {
        return mongoOrderManager.listFlowOrderItems(flowOrderItemDTO);
    }

    @Override
    public Long saveOrderToMall(SaveOrderToMallDTO saveOrderToMallDTO) {
        // order
        Order order = new Order();
        order.setUserId(saveOrderToMallDTO.getUserId());
        order.setTotal(-saveOrderToMallDTO.getEstimatedAmount());
        order.setActualTotal(-saveOrderToMallDTO.getEstimatedAmount());
        order.setStatus(OrderStatus.CUE_PENDING_AUDIT.value());
        order.setAllCount(1);
        order.setOrderType(OrderType.RECYCLE.value());
        order.setOrderId(segmentManager.getSegmentIdWithDateTime(DistributedIdKey.tmerclub_ORDER, order.getUserId()));
        order.setCreateTime(new Date());
        order.setShopId(0L);
        order.setDeliveryType(DeliveryType.DELIVERY.value());
        orderMapper.saveCueOrder(order);
        // order_item
        OrderItem orderItem = new OrderItem();
        orderItem.setOrderItemId(segmentManager.getSegmentIdWithDateTime(DistributedIdKey.tmerclub_ORDER_ITEM, order.getUserId()));
        orderItem.setCreateTime(new Date());
        orderItem.setShopId(0L);
        orderItem.setOrderId(order.getOrderId());
        orderItem.setSpuId(0L);
        orderItem.setSkuId(0L);
        orderItem.setUserId(saveOrderToMallDTO.getUserId());
        orderItem.setCount(1);
        orderItem.setPrice(saveOrderToMallDTO.getEstimatedAmount());
        orderItem.setPic(saveOrderToMallDTO.getProductImages());
        orderItem.setSpuTotalAmount(saveOrderToMallDTO.getEstimatedAmount());
        orderItemMapper.saveCueOrderItem(orderItem);
        // order_item_lang
        OrderItemLang orderItemLang = new OrderItemLang();
        orderItemLang.setOrderItemId(orderItem.getOrderItemId());
        orderItemLang.setLang(LanguageEnum.LANGUAGE_ZH_CN.getLang());
        orderItemLang.setSpuName(saveOrderToMallDTO.getProductName());
        orderItemLangMapper.saveCueOrderItemLang(orderItemLang);
        return order.getOrderId();
    }

    @Override
    public void updateOrderMall(Long shopId,Long mallOrderId, Integer orderStatus) {
        Order order = new Order();
        order.setOrderId(mallOrderId);
        order.setStatus(orderStatus);
        order.setShopId(shopId);
        if(orderStatus.equals(OrderStatus.CUE_EVALUATION_SUCCESS_PAY.value())){
            // 订单已完成
            order.setIsSettled(0);
            order.setFinallyTime(new Date());
        }
        orderMapper.updateCueOrder(order);
    }
}
