package com.neusoft.smart.pos.order.service;

import com.neusoft.smart.pos.constants.DictionaryConstant;
import com.neusoft.smart.pos.dto.order.request.*;
import com.neusoft.smart.pos.dto.order.response.*;
import com.neusoft.smart.pos.dto.trade.request.PutPrinterFlagRequest;
import com.neusoft.smart.pos.dto.trade.response.GetOrderPayStatusResponse;
import com.neusoft.smart.pos.dto.trade.response.PutPrinterFlagResponse;
import com.neusoft.smart.pos.framework.config.RabbitExchangeConfiguration;
import com.neusoft.smart.pos.framework.exception.BusinessCommonException;
import com.neusoft.smart.pos.framework.utils.BeanUtil;
import com.neusoft.smart.pos.framework.utils.DateUtils;
import com.neusoft.smart.pos.framework.utils.ListUtils;
import com.neusoft.smart.pos.mq.rabbitmq.RabbitMQSender;
import com.neusoft.smart.pos.order.constants.TradeErrorCode;
import com.neusoft.smart.pos.order.persistent.domain.OrderDelivery;
import com.neusoft.smart.pos.order.persistent.domain.OrderMaster;
import com.neusoft.smart.pos.order.persistent.domain.OrderRefund;
import com.neusoft.smart.pos.order.persistent.domain.OrderTransaction;
import com.neusoft.smart.pos.order.repository.OrderDeliveryRepository;
import com.neusoft.smart.pos.order.repository.OrderMasterRepository;
import com.neusoft.smart.pos.order.repository.OrderRefundRepository;
import com.neusoft.smart.pos.order.repository.OrderTransactionRepository;
import com.neusoft.smart.pos.order.utils.OrderStatusUtils;
import com.neusoft.smart.pos.payorder.persistent.domain.PayOrder;
import com.neusoft.smart.pos.payorder.persistent.domain.PayRefundOrder;
import com.neusoft.smart.pos.payorder.repository.PayRefundOrderRepository;
import com.neusoft.smart.pos.payorder.service.PayOrderService;
import com.neusoft.smart.pos.strategy.service.StrategyService;
import com.neusoft.smart.pos.utils.PosDeviceRedisUtils;
import com.neusoft.smart.pos.utils.RequestHeaderUtil;
import lombok.val;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service("orderService")
public class OrderService {
    @Autowired
    private OrderMasterRepository orderMasterRepository;

    @Autowired
    private OrderTransactionRepository orderTransactionRepository;

    @Autowired
    private OrderDeliveryRepository orderDeliveryRepository;

    @Autowired
    private OrderRefundRepository orderRefundRepository;

    @Autowired
    private PayRefundOrderRepository payRefundOrderRepository;

    @Autowired
    private PayOrderService payOrderService;


    @Autowired
    private StrategyService strategyService;

    @Autowired
    private RabbitMQSender rabbitMQSender;//TODO

    /**
     * 普通订单订单信息创建方法
     *
     * @return
     */
    public PostOrderResponse createOrder(PostCreateOrderRequest createOrderRequest) {
        OrderMaster orderMaster = saveOrder(createOrderRequest, createOrderRequest.getOrderNumber());
        val orderResponse = new com.neusoft.smart.pos.dto.order.response.PostOrderResponse();
        BeanUtils.copyProperties(orderMaster, orderResponse);

        orderResponse.setDiscountAmount(0l);
        orderResponse.setHasPay(0l);
        return orderResponse;
    }

    /**
     * 订单信息创建方法（含普通订单、充值订单、微信点餐订单）
     *
     * @return
     */
    private OrderMaster saveOrder(PostCreateOrderRequest tradeOrderRequest, String orderNumber) {
        //1.根据订单类型校验参数信息,并获取集团及门店ID
        validateCreateOrderParams(tradeOrderRequest);

        if(!StringUtils.isEmpty(RequestHeaderUtil.getUsername())){
            tradeOrderRequest.setCreatedBy(RequestHeaderUtil.getUsername());
        }

        //2.生成当前订单号
        if (StringUtils.isEmpty(orderNumber)) {
            orderNumber = orderMasterRepository.generateOrderNumber();
        }

        //3.整理variableFees数据,并保存
        if(null != tradeOrderRequest.getVariableFees() && validateVariableFees(tradeOrderRequest)){
            saveVariableFees(orderNumber, tradeOrderRequest.getVariableFees(), tradeOrderRequest.getCreatedBy());
        }

        //4.整理orderDetails数据,并保存
        if(null != tradeOrderRequest.getOrderDetails()){
            saveOrderTransations(orderNumber, tradeOrderRequest.getOrderDetails(), tradeOrderRequest.getCreatedBy());
        }

        //5.整理deliveryInfo数据,并保存
        if(null != tradeOrderRequest.getDeliveryInfo()){
            saveDelivery(orderNumber, tradeOrderRequest.getDeliveryInfo(), tradeOrderRequest.getCreatedBy());
        }

        //计算订单金额
        PostCreateOrderRequest validateRequest = calculateOrderAmount(tradeOrderRequest);
        tradeOrderRequest.setOrderAmount(validateRequest.getOrderAmount());

        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(tradeOrderRequest, orderMaster);
        orderMaster.setOrderNumber(orderNumber);

        orderMasterRepository.saveOrder(orderMaster);
        return orderMaster;
    }

    /**
     * 验证试算费用是否一致
     * @param createOrderRequest
     * @return
     */
    private boolean validateVariableFees(PostCreateOrderRequest createOrderRequest) {
        List<VariableFee> getFees = strategyService.doCalculation(createOrderRequest);
        if(getFees == null || getFees.size() != createOrderRequest.getVariableFees().size()){
            return false;
        }
        for(val fee:getFees){
            val sendFee = getVariableFeeFromList(fee,createOrderRequest.getVariableFees());
            if(sendFee == null || sendFee.getVarFeeAmount() != fee.getVarFeeAmount() || sendFee.getVarFeeDiscount() != fee.getVarFeeDiscount() ){
                throw new BusinessCommonException(TradeErrorCode.VARIABLE_FEE_VALIDATE_ERROR);
            }
        }
        return true;
    }

    /**
     * 订单整单试算接口
     * @param postCreateOrderRequest
     * @return
     */
    public PostCreateOrderRequest doOrderTrial(PostCreateOrderRequest postCreateOrderRequest) {
        List<VariableFee> getFees = strategyService.doCalculation(postCreateOrderRequest);
        postCreateOrderRequest.setVariableFees(getFees);
        return calculateOrderAmount(postCreateOrderRequest);
    }

    /**
     * 订单金额计算接口
     * @param postCreateOrderRequest
     * @return
     */
    public PostCreateOrderRequest calculateOrderAmount(PostCreateOrderRequest postCreateOrderRequest) {
        if (postCreateOrderRequest != null &&
                postCreateOrderRequest.getOrderType().equals(DictionaryConstant.ORDER_TYPE_HYCZ.getCode())) {
            return postCreateOrderRequest;
        }
        Long orderAmount = 0l;

        List<PostOrderDetailRequest> orderDetails = postCreateOrderRequest.getOrderDetails();
        if (orderDetails != null) {
            for (val orderDetail : orderDetails) {
                Long detailFinalPrice = orderDetail.getFinalPrice().multiply(new BigDecimal("100")).longValue();
                orderAmount = orderAmount + detailFinalPrice;
            }
        }

        List<VariableFee> getFees = postCreateOrderRequest.getVariableFees();
        if (getFees != null) {
            for (val fee : getFees) {
                orderAmount = orderAmount + fee.getVarFeeAmount();
            }
        }
        postCreateOrderRequest.setOrderAmount(orderAmount);
        return postCreateOrderRequest;
    }

    /**
     * 验证订单总金额是否一致
     * @param createOrderRequest
     * @return
     */
    private boolean validateOrderAmount(PostCreateOrderRequest createOrderRequest) {
        PostCreateOrderRequest validateRequest = calculateOrderAmount(createOrderRequest);
        if(createOrderRequest == null || createOrderRequest.getOrderAmount() != validateRequest.getOrderAmount()){
            return false;
        }
        return true;
    }

    /**
     * 从费用列表中获得附加费用
     * @param fee
     * @param variableFees
     * @return
     */
    private VariableFee getVariableFeeFromList(VariableFee fee, List<VariableFee> variableFees) {
        for (val sendFee : variableFees) {
            if (sendFee.getVarFeeName().equals(fee.getVarFeeName())) {
                return sendFee;
            }
        }
        return null;
    }

    /**
     * 订单信息创建方法（含普通订单、充值订单、微信点餐订单）
     *
     * @return
     */
    private OrderMaster saveOrderOld(PostCreateOrderRequest tradeOrderRequest, String orderNumber) {
        //1.根据订单类型校验参数信息,并获取集团及门店ID
        validateCreateOrderParams(tradeOrderRequest);


        //2.生成当前订单号
        if (StringUtils.isEmpty(orderNumber)) {
            orderNumber = orderMasterRepository.generateOrderNumber();
        }

        //3.整理orderDetails数据,并保存
        if(null != tradeOrderRequest.getOrderDetails()){
            saveOrderTransations(orderNumber, tradeOrderRequest.getOrderDetails(), tradeOrderRequest.getCreatedBy());
        }

        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(tradeOrderRequest, orderMaster);
        orderMaster.setOrderNumber(orderNumber);



        orderMasterRepository.saveOrder(orderMaster);
        return orderMaster;
    }

    /**
     * 根据订单号更新订单信息
     * @param order
     * @return
     */
    public boolean updateOrderInfo(OrderMaster order){
        if(order == null || order.getOrderNumber() == null || order.getOrderNumber().isEmpty()){
            return false;
        }
        return orderMasterRepository.updateOrder(order);
    }

    /**
     * 存储订单商品信息
     * @param orderNumber
     * @param orderDetails
     * @param createdBy
     */
    private void saveOrderTransations(String orderNumber, List<PostOrderDetailRequest> orderDetails, String createdBy){
        for (val temp:orderDetails) {
            val orderTransaction = new OrderTransaction();
            if(!StringUtils.isEmpty(temp.getItemName())){
                BeanUtils.copyProperties(temp,orderTransaction);
                orderTransaction.setOrderNumber(orderNumber);
                orderTransaction.setCreatedBy(createdBy);
                orderTransactionRepository.saveOrderDetails(orderTransaction);
            }
        }
    }

    /**
     * 存储附加费用信息
     * @param orderNumber
     * @param variableFees
     * @param createdBy
     */
    private void saveVariableFees(String orderNumber, List<VariableFee> variableFees, String createdBy){
        for (val temp:variableFees) {
            val orderTransaction = new OrderTransaction();
            if(!StringUtils.isEmpty(temp.getVarFeeName())){
                orderTransaction.setItemName(temp.getVarFeeName());
                orderTransaction.setFinalPrice(BigDecimal.valueOf(temp.getVarFeeAmount()).divide(new BigDecimal(100)));
                orderTransaction.setDiscountAmount(BigDecimal.valueOf(temp.getVarFeeDiscount()).divide(new BigDecimal(100)));
                orderTransaction.setCategoryName(temp.getVarFeeDescription());
                orderTransaction.setCategoryNumber("-2");
                orderTransaction.setOrderNumber(orderNumber);
                orderTransaction.setCreatedBy(createdBy);
                orderTransactionRepository.saveOrderDetails(orderTransaction);
            }
        }
    }

    /**
     * 保存配送地址信息
     * @param orderNumber
     * @param deliveryInfo
     * @param createdBy
     */
    private void saveDelivery(String orderNumber, DeliveryInfo deliveryInfo, String createdBy){
        val orderDelivery = new OrderDelivery();
        if(deliveryInfo != null){
            BeanUtils.copyProperties(deliveryInfo,orderDelivery);
            orderDelivery.setOrderNumber(orderNumber);
            orderDelivery.setCreateBy(createdBy);
            orderDeliveryRepository.saveOrderDelivery(orderDelivery);
        }
    }

    /**
     * 普通订单订单信息保存方法
     *
     * @return
     */
    public PostOrderResponse saveOrder(PostSaveOrderRequest saveOrderRequest) {
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(saveOrderRequest, orderMaster);

        orderMasterRepository.updateOrder(orderMaster);
        val orderResponse = new com.neusoft.smart.pos.dto.order.response.PostOrderResponse();
        BeanUtils.copyProperties(orderMaster, orderResponse);
        return orderResponse;
    }

    /**
     * 普通订单订单取消方法
     *
     * @return
     */
    public PutCancelOrderResponse cancelOrder(PutCancelOrderRequest cancleOrderRequest) {
        boolean bResult = orderMasterRepository.updateOrderStatusByOrderNumber(cancleOrderRequest.getOrderNumber(), cancleOrderRequest.getOrgId(),cancleOrderRequest.getShopId(),DictionaryConstant.ORDER_UPDATE_STATUS_DDQX.getCode());
        val cancelOrderResponse = new com.neusoft.smart.pos.dto.order.response.PutCancelOrderResponse(bResult);
        return cancelOrderResponse;
    }

    /**
     * 普通订单自动计算并更新订单状态方法
     * @param orderNumber
     * @return
     */
    public boolean computeOrderStatus(String orderNumber) {
        OrderMaster order = orderMasterRepository.queryOrderByOrderNumber(orderNumber);
        if(order == null){
            throw new BusinessCommonException(TradeErrorCode.ORDER_INFO_NOT_EXIST);
        }
        List<PayOrder> payOrders = payOrderService.queryPayOrderList(orderNumber);
        List<OrderRefund> orderRefunds = orderRefundRepository.queryOrderRefunds(orderNumber);

        long hasPayAmountSum = orderMasterRepository.queryHasPayAmountSum(orderNumber);
        long hasRefundAmountSum = orderMasterRepository.queryHasRefundAmountSum(orderNumber);
        long discountAmountSum = orderMasterRepository.queryDiscountAmountSum(orderNumber);
        long couponsAmountSum = orderMasterRepository.queryCouponsAmountSum(orderNumber);

        order.setRealPayAmount(hasPayAmountSum - discountAmountSum - couponsAmountSum - hasRefundAmountSum);
        String oldOrderStatus = order.getOrderStatus();

        OrderStatusUtils orderStatusUtils = new OrderStatusUtils(payOrders, orderRefunds, order, hasPayAmountSum, hasRefundAmountSum);
        String orderStatus = orderStatusUtils.computeOrderStatus();
        if(orderStatus == null){
            throw new BusinessCommonException(TradeErrorCode.TRADE_STATUS_COMPUTE_ERROR);
        }

        OrderMaster updateOrder = new OrderMaster();
        updateOrder.setOrderNumber(order.getOrderNumber());
        updateOrder.setOrderStatus(orderStatus);
        updateOrder.setRealPayAmount(order.getRealPayAmount());
        boolean bResult = orderMasterRepository.updateOrder(updateOrder);

        if(oldOrderStatus != orderStatus && (orderStatus.equals(DictionaryConstant.ORDER_UPDATE_STATUS_ZFWC.getCode())
                ||orderStatus.equals(DictionaryConstant.ORDER_UPDATE_STATUS_TKWC.getCode()))) {
            // 通知订单完成，用监听者方式
            GetAllOrderInfoResponse getAllOrderInfoResponse = getOrderInfoByOrderNumber(orderNumber);
            rabbitMQSender.sendMessage(RabbitExchangeConfiguration.FANOUT_EXCHANGE_ORDER_COMPLETE, "", getAllOrderInfoResponse);
        }

        return bResult;
    }


    /**
     * 设置订单指定状态方法
     *
     * @return
     */
    public PutSetOrderStatusResponse setOrderStatus(PutSetOrderStatusRequest setOrderStatusRequest) {
        boolean bResult = orderMasterRepository.updateOrderStatusByOrderNumber(setOrderStatusRequest.getOrderNumber(), setOrderStatusRequest.getOrgId(),setOrderStatusRequest.getShopId(), setOrderStatusRequest.getOrderStatus());
        val setOrderStatusResponse = new com.neusoft.smart.pos.dto.order.response.PutSetOrderStatusResponse(bResult);
        return setOrderStatusResponse;
    }

    public void setOrderStatus(String orderNumber, String oldStatus, String newStatus) {
        val orderMaster = orderMasterRepository.queryOrderByOrderNumber(orderNumber);
        if(orderMaster == null) {
            throw new BusinessCommonException(TradeErrorCode.ORDER_INFO_NOT_EXIST);
        }

        if(!oldStatus.equals(orderMaster.getOrderStatus())) {
            throw new BusinessCommonException(TradeErrorCode.ORDER_STATUS_ERROR);
        }

        if(!orderMasterRepository.updateOrderStatusByOrderNumber(orderNumber, newStatus)) {
            throw new BusinessCommonException(TradeErrorCode.ORDER_UPDATE_STATUS_ERROR);
        }
    }

    public OrderMaster getOrderMasterObj(String orderNumber) {
        return orderMasterRepository.queryOrderByOrderNumber(orderNumber);
    }

    /**
     * 获得订单全部信息方法
     *
     * @return
     */
    public GetAllOrderInfoResponse getOrderInfoByOrderNumber(String orderNumber) {
        OrderMaster orderMaster = orderMasterRepository.queryOrderByOrderNumber(orderNumber);
        val orderInfoResponse = new com.neusoft.smart.pos.dto.order.response.GetAllOrderInfoResponse();
        BeanUtils.copyProperties(orderMaster, orderInfoResponse);

        //获得shopName和orgName
        val shopNameMap = orderMasterRepository.queryShopNameAndOrgName(orderMaster.getShopId());
        if(shopNameMap != null){
            orderInfoResponse.setShopName((String) shopNameMap.get("shop_name"));
            orderInfoResponse.setOrgName((String) shopNameMap.get("org_name"));
        }else {
            orderInfoResponse.setShopName("");
            orderInfoResponse.setOrgName("");
        }

        //获得订单商品信息
        List<OrderTransaction> orderDetails = orderTransactionRepository.queryOrderDetails(orderMaster.getOrderNumber());
        if (null != orderDetails && orderDetails.size() > 0) {
            orderInfoResponse.setOrderDetailList(ListUtils.convertListToList(orderDetails, GetAllOrderInfoResponse.OrderDetail.class));
        }

        //获得支付订单信息
        List<PayOrder> payOrders = payOrderService.queryPayOrderList(orderNumber);
        if (null != payOrders && payOrders.size() > 0) {
            orderInfoResponse.setPayInfos(ListUtils.convertListToList(payOrders, GetAllOrderInfoResponse.PayInfo.class));
        }

        //获得订单的退款订单
        List<OrderRefund> orderRefunds = orderRefundRepository.queryOrderRefunds(orderNumber);
        if (null != orderRefunds && orderRefunds.size() > 0) {
//            orderInfoResponse.setOrderRefunds(ListUtils.convertListToList(orderRefunds, GetAllOrderInfoResponse.OrderRefundInfo.class));
            List<GetAllOrderInfoResponse.OrderRefundInfo> orderRefundInfoList = new ArrayList<>();
            for (OrderRefund orderRefund:orderRefunds) {
                List<PayRefundOrder> payRefundOrderList = payRefundOrderRepository.queryPayRefundOrder(orderRefund.getRefundNumber());
                List<GetAllOrderInfoResponse.PayRefundOrderInfo> payRefundOrderInfos = ListUtils.convertListToList(payRefundOrderList, GetAllOrderInfoResponse.PayRefundOrderInfo.class);
                GetAllOrderInfoResponse.OrderRefundInfo orderRefundInfo = new GetAllOrderInfoResponse.OrderRefundInfo();
                BeanUtils.copyProperties(orderRefund, orderRefundInfo);
                orderRefundInfo.setPayRefundOrderInfos(payRefundOrderInfos);
                orderRefundInfoList.add(orderRefundInfo);
            }
            orderInfoResponse.setOrderRefunds(orderRefundInfoList);
        }

        //获得订单附加费用信息
        List<OrderTransaction> variableFees = orderTransactionRepository.queryVariableFees(orderMaster.getOrderNumber());
        if (null != variableFees && variableFees.size() > 0) {
            List<VariableFee> responseVariableFees = new ArrayList<>();
            for (OrderTransaction fee:variableFees) {
                VariableFee vFee = new VariableFee();
                vFee.setVarFeeName(fee.getItemName());
                vFee.setVarFeeAmount(fee.getFinalPrice().multiply(new BigDecimal("100")).longValue());
                vFee.setVarFeeDiscount(fee.getDiscountAmount().multiply(new BigDecimal("100")).longValue());
                vFee.setVarFeeDescription(fee.getCategoryName());
                responseVariableFees.add(vFee);
            }
            orderInfoResponse.setVariableFees(responseVariableFees);
        }

        //获得订单配送信息
        List<OrderDelivery> deliveryInfos= orderDeliveryRepository.queryOrderDeliverys(orderNumber);
        if (null != deliveryInfos && deliveryInfos.size() > 0) {
            DeliveryInfo deliveryInfo = new DeliveryInfo();
            BeanUtils.copyProperties(deliveryInfos.get(0),deliveryInfo);
            orderInfoResponse.setDeliveryInfo(deliveryInfo);
        }

//        OrderStatusUtils orderStatusUtils = new OrderStatusUtils(payOrders,orderRefunds,orderMaster);
//        String orderStatus = orderStatusUtils.computeOrderStatus();
//        if(orderStatus == null){
//            throw new BusinessCommonException(TradeErrorCode.TRADE_STATUS_COMPUTE_ERROR);
//        }
//        orderMasterRepository.updateOrderStatusByOrderNumber(orderNumber, orderStatus);
//        orderInfoResponse.setOrderStatus(orderStatus);
        orderInfoResponse.setOrderAmountLong(orderMaster.getOrderAmount());

        long hasPayAmountSum = orderMasterRepository.queryHasPayAmountSum(orderNumber);
        long hasRefundAmountSum = orderMasterRepository.queryHasRefundAmountSum(orderNumber);
        long discountAmountSum = orderMasterRepository.queryDiscountAmountSum(orderNumber);
        long couponsAmountSum = orderMasterRepository.queryCouponsAmountSum(orderNumber);

        orderInfoResponse.setDiscountAmount(discountAmountSum + couponsAmountSum);
        orderInfoResponse.setHasPay(hasPayAmountSum - hasRefundAmountSum);
        return orderInfoResponse;
    }

    /**
     * 获得订单全部商品信息方法
     *
     * @return
     */
    public GetOrderDetailsResponse getOrderGoodsListByOrderNumber(String orderNumber) {
        GetOrderDetailsResponse orderDetailsResponse = new GetOrderDetailsResponse();
        List<OrderTransaction> orderDetailsList = orderTransactionRepository.queryOrderDetails(orderNumber);
        List<GetOrderDetailsModelResponse> orderDetailsModelList = ListUtils.convertListToList(orderDetailsList,GetOrderDetailsModelResponse.class);
        orderDetailsResponse.setOrderDetails(orderDetailsModelList);
        return orderDetailsResponse;
    }

    public PostDoPayOrderResponse doPay(PostDoPayOrderRequest doPayOrderRequest) {
        return null;
    }


    /**
     * 根据订单类型校验创建订单相关参数信息,并存入集团ID、门店ID
     */
    private void validateCreateOrderParams(PostCreateOrderRequest tradeOrderRequest) {
        //订单类型@1正常订单@2POS端补录订单@3会员卡充值订单@4微信点餐订单
        if (StringUtils.isEmpty(tradeOrderRequest.getOrderType())) {
            //订单类型不能为空
            throw new BusinessCommonException(TradeErrorCode.ORDER_TYPE_IS_EMPTY);
        }
        if (null == tradeOrderRequest.getOrderAmount()) {
            //订单应付金额不能为空
            throw new BusinessCommonException(TradeErrorCode.ORDER_AMOUNT_IS_EMPTY);
        }
//        if (tradeOrderRequest.getOrderAmount().doubleValue() < 0) {
//            //订单应付金额输入错误
//            throw new BusinessCommonException(TradeErrorCode.ORDER_AMOUNT_ERROR);
//        }

//        DictionaryConstant dict = DictionaryConstant.getEnumByCode(DictionaryConstant.ORDER_TYPE.getCode(),tradeOrderRequest.getOrderType());
//        switch(dict){
//            case ORDER_TYPE_ZC:
//                //POS端正常订单
//                validateOrderParamsByZC(tradeOrderRequest);
//                break;
//            case ORDER_TYPE_HYCZ:
//                //会员卡充值订单
//                validateOrderParamsByHYCZ(tradeOrderRequest);
//                break;
//            case ORDER_TYPE_WXDC:
//                //微信点餐订单
//                validateOrderParamsByWXDC(tradeOrderRequest);
//                break;
//            default:
//                //订单类型错误
//                throw new BusinessCommonException(TradeErrorCode.ORDER_TYPE_ERROR);
//        }
    }

    public OrderMaster getOrderMasterByOrderNumber(String orderNumber) {
        return orderMasterRepository.queryOrderByOrderNumber(orderNumber);
    }


    //////////////////////////////////////////////// 适配北国新增 //////////////////////////////////////////////////
    /**
     * 订单编号信息查询方法
     * @return
     */
    public String queryOrderNumber(){
        return orderMasterRepository.generateOrderNumber();
    }

    /**
     * 订单打印状态更新
     * @return
     */
    public PutPrinterFlagResponse updatePrinterFlag(PutPrinterFlagRequest printerFlagRequest) {
        //2.更新订单状态
        val result = orderMasterRepository.updatePrinterFlagByOrderNumber(printerFlagRequest.getOrderNumber());
        return new PutPrinterFlagResponse(result);
    }

    /**
     * 订单支付状态查询方法
     * @param orderNumber：订单编号
     * @return
     */
    public GetOrderPayStatusResponse queryOrderPayStatus(String serialNo, String orderNumber) {
        //1.查询订单信息，并进行校验
        val deviceInfo = PosDeviceRedisUtils.getDeviceInfoBySerialNo(serialNo);
        if(null == deviceInfo){
            throw new BusinessCommonException(TradeErrorCode.DEVICE_ORG_EMPTY);
        }
        val orgId = deviceInfo.getOrganizationId();
        val shopId = deviceInfo.getStoreId();
        val orderMaster = orderMasterRepository.queryOrderByOrderNumber(orgId,shopId,orderNumber);
        if(null == orderMaster){
            throw new BusinessCommonException(TradeErrorCode.ORDER_INFO_NOT_EXIST);
        }
        //2.根据orderNumber获得payOrder
        List<PayOrder> payOrderList = payOrderService.queryPayOrderList(orderNumber);
        if(null == payOrderList && payOrderList.size() <= 0){
            throw new BusinessCommonException(TradeErrorCode.PAY_ORDER_QUERY_ERROR);
        }
        com.neusoft.smart.pos.dto.trade.response.GetOrderPayStatusResponse orderPayStatusResponse = new com.neusoft.smart.pos.dto.trade.response.GetOrderPayStatusResponse();
        orderPayStatusResponse.setPayStatus(payOrderList.get(payOrderList.size()-1).getPayStatus());
        if(orderPayStatusResponse.getPayStatus().equals(DictionaryConstant.PAY_STATUS_YFK.getCode())){
            orderPayStatusResponse.setPaidTime(DateUtils.format(payOrderList.get(payOrderList.size()-1).getPayTime(),DateUtils.FORMAT_LONG));
        }else{
            orderPayStatusResponse.setPaidTime("");
        }
        return orderPayStatusResponse;
    }


}
