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


import com.neusoft.smart.pos.constants.DictionaryConstant;
import com.neusoft.smart.pos.dto.member.request.MemberRechargeRequest;
import com.neusoft.smart.pos.dto.member.request.MemberRefundRequest;
import com.neusoft.smart.pos.dto.member.request.MemberTransactionRequest;
import com.neusoft.smart.pos.dto.member.response.DetailedMemberResponse;
import com.neusoft.smart.pos.dto.promotion.request.GetPreferentialPriceRequest;
import com.neusoft.smart.pos.dto.promotion.response.GetPreferentialPriceResponse;
import com.neusoft.smart.pos.dto.trade.request.*;
import com.neusoft.smart.pos.dto.trade.response.*;
import com.neusoft.smart.pos.framework.constants.ApplicationConstants;
import com.neusoft.smart.pos.framework.dto.ResponseData;
import com.neusoft.smart.pos.framework.exception.BusinessCommonException;
import com.neusoft.smart.pos.framework.task.TaskExecutor;
import com.neusoft.smart.pos.framework.utils.*;
import com.neusoft.smart.pos.gateway.constants.InventoryConstant;
import com.neusoft.smart.pos.gateway.constants.MemberErrorCode;
import com.neusoft.smart.pos.gateway.service.feignService.*;
import com.neusoft.smart.pos.gateway.task.RecordOrderTask;
import com.neusoft.smart.pos.redis.bean.DeviceInfo;
import com.neusoft.smart.pos.utils.PosDeviceRedisUtils;
import com.neusoft.smart.pos.utils.PosMemberRedisUtils;
import lombok.val;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

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

@Service("orderService")
public class OrderService {
    
    @Value("${smart.pos.constant.promotion.enabled}")
    private Boolean promotionEnabled;
    
    @Autowired
    private RemoteOrderService remoteOrderService;
    
    @Autowired
    private RemotePayNotifyService remotePayNotifyService;
    
    @Autowired
    private RemotePromotionService remotePromotionService;
    
    @Autowired
    private RemoteMemberService remoteMemberService;
    
    @Autowired
    private TaskExecutor taskExecutor;
    
    @Autowired
    private InventoryService inventoryService;
    
    @Autowired
    private RemoteTradeSettlementService remoteTradeSettlementService;
    
    private String memberBalance;
    
    @Autowired
    private PrinterService printerService;
    
    /**
     * 订单信息创建方法
     *
     * @return
     */
    public PostOrderResponse saveOrder(PostOrderRequest orderRequest) {
        val tradeOrderRequest = new PostTradeOrderRequest();
        BeanUtils.copyProperties(orderRequest, tradeOrderRequest);
        tradeOrderRequest.setOrderType(DictionaryConstant.ORDER_TYPE_ZC.getCode());
        
        //1.判断会员卡号是否为空，如果不为空则计算优惠信息
        memberDiscountHandle(tradeOrderRequest);
        
        //生成订单前锁定库存
        String orderNumber = remoteOrderService.queryOrderNumber().getResult();
        inventoryService.lockInventory(orderRequest.getSerialNo(),orderNumber,orderRequest.getOrderDetails());
        tradeOrderRequest.setOrderNumber(orderNumber);
        
        //2.创建订单信息
        val orderResponseData = remoteOrderService.saveOrder(tradeOrderRequest);
        if (null == orderResponseData || !ApplicationConstants.SUCCESS_CODE.equals(orderResponseData.getCode())) {
            throw new BusinessCommonException(orderResponseData);
        }
        return orderResponseData.getResult();
    }
    
    /**
     * 充值订单信息创建方法
     *
     * @return
     */
    public PostRechargeOrderResponse saveRechargeOrder(PostRechargeOrderRequest rechargeOrderRequest) {
        val tradeOrderRequest = new PostTradeOrderRequest();
        BeanUtils.copyProperties(rechargeOrderRequest, tradeOrderRequest);
        tradeOrderRequest.setOrderType(DictionaryConstant.ORDER_TYPE_HYCZ.getCode());

        if(!SignUtils.isSignatureValidSHA256(rechargeOrderRequest)) {
            throw new BusinessCommonException(MemberErrorCode.SIGN_VERIFY_FAILED);
        }

        //判断是否为沈阳饭卡支付
        if (!StringUtils.isEmpty(tradeOrderRequest.getMemberCardNo())) {
            DeviceInfo deviceInfo = PosDeviceRedisUtils.getDeviceInfoBySerialNo(rechargeOrderRequest.getSerialNo());
            if (null == deviceInfo) {
                throw new BusinessCommonException(MemberErrorCode.MEMBER_CARD_NOT_EXIST);
            }
            
            DetailedMemberResponse detailedMemberData = remoteMemberService.getMemberByCondition(null, rechargeOrderRequest.getMemberCardNo(), "", deviceInfo.getOrganizationId(), null).getResult();
            //获取员工卡号、会员卡编号(印刷,沈阳食堂使用)、会员卡hid编码(卡内,沈阳食堂使用)
            if (null != detailedMemberData && !StringUtils.isEmpty(detailedMemberData.getCardHidCode())) {
                tradeOrderRequest.setCardHidCode(detailedMemberData.getCardHidCode());     //会员卡hid编码(卡内,沈阳食堂使用)
                tradeOrderRequest.setMemberCardNo(detailedMemberData.getMemberCode());    //东软员工号
                tradeOrderRequest.setCardNum(detailedMemberData.getCardNum());         //会员卡编号(印刷,沈阳食堂使用)
                tradeOrderRequest.setMemberName(detailedMemberData.getName());       //会员名称
            } else if (null == detailedMemberData) {
                throw new BusinessCommonException(MemberErrorCode.MEMBER_CARD_NOT_EXIST);
            }
        }
        
        //进入营销系统
        memberDiscountHandle(tradeOrderRequest);
        
        //2.生成充值订单
        val rechargeOrderResponseData = remoteOrderService.saveRechargeOrder(tradeOrderRequest);
        if (null == rechargeOrderResponseData || !ApplicationConstants.SUCCESS_CODE.equals(rechargeOrderResponseData.getCode())) {
            throw new BusinessCommonException(rechargeOrderResponseData);
        }
        return rechargeOrderResponseData.getResult();
    }
    
    /**
     * 微信点餐订单信息创建方法
     *
     * @return
     */
    public PostWxOrderResponse saveWxOrder(PostWxOrderRequest wxOrderRequest) {
        //-1.判断桌位是否占用
//        final ResponseData<Tables> tablesResponseData = orgService.selectTableById(wxOrderRequest.getShopId());
//        if (!tablesResponseData.getCode().equals(CommonErrorCode.SUCCESS.getCode())) {
//            throw new BusinessCommonException(tablesResponseData);
//        }
//        final Tables table = tablesResponseData.getResult();
//        if (!StringUtils.isEmpty(table.getOrderId())) {
//            throw new BusinessCommonException("500", "桌位已占用");
//        }
        //0. 业务开始
        val tradeOrderRequest = new PostTradeOrderRequest();
        BeanUtils.copyProperties(wxOrderRequest, tradeOrderRequest);
        tradeOrderRequest.setOrderType(DictionaryConstant.ORDER_TYPE_WXDC.getCode());
        
        //1.判断会员卡号是否为空，如果不为空则计算优惠信息
        memberDiscountHandle(tradeOrderRequest);
    
        //生成订单前锁定库存
        String orderNumber = remoteOrderService.queryOrderNumber().getResult();
        inventoryService.lockInventory(wxOrderRequest.getOrgId(),wxOrderRequest.getShopId(),orderNumber,wxOrderRequest.getOrderDetails());
        tradeOrderRequest.setOrderNumber(orderNumber);
        
        //2.生成充值订单
        val wxOrderResponseData = remoteOrderService.saveWxOrder(tradeOrderRequest);
        if (null == wxOrderResponseData || !ApplicationConstants.SUCCESS_CODE.equals(wxOrderResponseData.getCode())) {
            throw new BusinessCommonException(wxOrderResponseData);
        }
        
        //3.修改桌位占用情况
//        table.setOrderId(wxOrderResponseData.getResult().getOrderNumber());
//        orgService.updateTable(table);
        return wxOrderResponseData.getResult();
    }
    
    /**
     * 统一订单生成方法
     *
     * @param unionPayOrderRequest
     * @return
     */
    public PostUnionPayOrderResponse saveUnionPayOrder(PostUnionPayOrderRequest unionPayOrderRequest) {
        val tradeOrderRequest = new PostTradeOrderRequest();
        BeanUtils.copyProperties(unionPayOrderRequest, tradeOrderRequest);
        tradeOrderRequest.setOrderType(DictionaryConstant.ORDER_TYPE_ZC.getCode());
        
        //判断是否为沈阳饭卡支付
        //if (DictionaryConstant.PAY_TYPE_FKSY.getCode().equals(unionPayOrderRequest.getPayType())) {
        if(StringUtils.isEmpty(unionPayOrderRequest.getMemberCardNo()) && !StringUtils.isEmpty(unionPayOrderRequest.getHardwareCardNo())){
            DetailedMemberResponse detailedMemberData = PosMemberRedisUtils.getMemberByCardHidCode(unionPayOrderRequest.getHardwareCardNo());
            if(detailedMemberData == null) {
                detailedMemberData = remoteMemberService.getDetailByHidCode(unionPayOrderRequest.getHardwareCardNo()).getResult();
            }

            if(detailedMemberData == null) {
                throw new BusinessCommonException(MemberErrorCode.MEMBER_CARD_NOT_EXIST);
            }
            //获取员工卡号、会员卡编号(印刷,沈阳食堂使用)、会员卡hid编码(卡内,沈阳食堂使用)
            tradeOrderRequest.setCardHidCode(detailedMemberData.getCardHidCode());     //会员卡hid编码(卡内,沈阳食堂使用)
            tradeOrderRequest.setMemberCardNo(detailedMemberData.getMemberCode());    //东软员工号
            tradeOrderRequest.setCardNum(detailedMemberData.getCardNum());         //会员卡编号(印刷,沈阳食堂使用)
            tradeOrderRequest.setMemberName(detailedMemberData.getName());       //会员名称

        }
        
        //1.判断会员卡号是否为空，如果不为空则计算优惠信息
        memberDiscountHandle(tradeOrderRequest);
    
        //生成订单前锁定库存
        String orderNumber = "";
        if(StringUtils.isEmpty(tradeOrderRequest.getOrderNumber())){
            orderNumber = remoteOrderService.queryOrderNumber().getResult();
        }else{
            orderNumber = tradeOrderRequest.getOrderNumber();
        }
        inventoryService.lockInventory(unionPayOrderRequest.getSerialNo(),orderNumber,unionPayOrderRequest.getOrderDetails());
        tradeOrderRequest.setOrderNumber(orderNumber);
        
        //2.创建订单信息
        val unionPayOrderResponseData = remoteOrderService.saveUnionPayOrder(tradeOrderRequest);
        if (null == unionPayOrderResponseData || !ApplicationConstants.SUCCESS_CODE.equals(unionPayOrderResponseData.getCode())) {
            throw new BusinessCommonException(unionPayOrderResponseData);
        }
        //3.支付完成后将订单信息推送至打印服务
        if(unionPayOrderResponseData.getResult().getPayStatus().equals(DictionaryConstant.PAY_STATUS_YFK.getCode())){
            printerService.pushPrinterTaskByOrderNumber(unionPayOrderResponseData.getResult().getOrderNumber(),DictionaryConstant.PRINTER_OPERATION_TYPE_2.getCode());
        }
        //支付成功后扣减库存
        if(unionPayOrderResponseData.getResult().getPayStatus().equals(DictionaryConstant.PAY_STATUS_YFK.getCode())){
            inventoryService.lockInventoryByStatus(unionPayOrderRequest.getSerialNo(),orderNumber, InventoryConstant.LOCKER_DEDUCTED);
        }
        return unionPayOrderResponseData.getResult();
    }
    
    /**
     * 订单创建会员优惠及校验信息处理方法
     *
     * @param tradeOrderRequest
     */
    private void memberDiscountHandle(PostTradeOrderRequest tradeOrderRequest) {
        if (!promotionEnabled) {
            if (null != tradeOrderRequest.getDiscountRate()) {
                tradeOrderRequest.setRealPayAmount(tradeOrderRequest.getOrderAmount().multiply(tradeOrderRequest.getDiscountRate()).setScale(2, RoundingMode.UP));
            }
            if (null != tradeOrderRequest.getDiscountAmount()) {
                tradeOrderRequest.setRealPayAmount(tradeOrderRequest.getOrderAmount().subtract(tradeOrderRequest.getDiscountAmount()).setScale(2, RoundingMode.UP));
            }
            return;
        }
        if (null == tradeOrderRequest.getOrderAmount() && null != tradeOrderRequest.getOrderDetails()) {
            tradeOrderRequest.setOrderAmount(getOrderAmount(tradeOrderRequest.getOrderDetails()));
        }
//        if (!StringUtils.isEmpty(tradeOrderRequest.getMemberCardNo())) {
        GetPreferentialPriceRequest getPreferentialPriceRequest = new GetPreferentialPriceRequest();
        getPreferentialPriceRequest.setSerialNo(tradeOrderRequest.getSerialNo());
        getPreferentialPriceRequest.setOrderType(tradeOrderRequest.getOrderType());
        getPreferentialPriceRequest.setTotalPrice(tradeOrderRequest.getOrderAmount());
        getPreferentialPriceRequest.setMemberCardNum(tradeOrderRequest.getMemberCardNo());
        getPreferentialPriceRequest.setOrgId(tradeOrderRequest.getOrgId());
        getPreferentialPriceRequest.setShopId(tradeOrderRequest.getShopId());
        getPreferentialPriceRequest.setDiscount(null != tradeOrderRequest.getDiscountRate() ? tradeOrderRequest.getDiscountRate() : new BigDecimal("1"));
        getPreferentialPriceRequest.setFloorPrice(null != tradeOrderRequest.getDiscountAmount() ? tradeOrderRequest.getDiscountAmount() : new BigDecimal("0"));
        if (null != tradeOrderRequest.getOrderDetails()) {
            getPreferentialPriceRequest.setOrderItems(BeanUtil.parseList(tradeOrderRequest.getOrderDetails(), GetPreferentialPriceRequest.OrderItem.class));
        }
        ResponseData<GetSettlementResponse> getSettlementResponse = null;
        if(StringUtils.isEmpty(tradeOrderRequest.getSerialNo())){
            getSettlementResponse = remoteTradeSettlementService.querySettlementByShopId(tradeOrderRequest.getOrgId(),tradeOrderRequest.getShopId());
        }else{
            getSettlementResponse = remoteTradeSettlementService.querySettlement(tradeOrderRequest.getSerialNo());
        }
        if (null == getSettlementResponse || !ApplicationConstants.SUCCESS_CODE.equals(getSettlementResponse.getCode())) {
            throw new BusinessCommonException(getSettlementResponse);
        }
        getPreferentialPriceRequest.setSettlementType(getSettlementResponse.getResult().getSettlementType());
        getPreferentialPriceRequest.setPayType(tradeOrderRequest.getPayType());
        
        val getPreferentialPriceResponse = remotePromotionService.getDiscounts(getPreferentialPriceRequest);
        if (null == getPreferentialPriceResponse || !ApplicationConstants.SUCCESS_CODE.equals(getPreferentialPriceResponse.getCode())) {
            throw new BusinessCommonException(getPreferentialPriceResponse);
        }
        tradeOrderRequest.setOrderAmount(getPreferentialPriceResponse.getResult().getTotalPrice());
        tradeOrderRequest.setRealPayAmount(getPreferentialPriceResponse.getResult().getActualPrice());    //订单应付金额(实付金额)
        tradeOrderRequest.setDiscountAmount(getPreferentialPriceResponse.getResult().getTotalPrice().subtract(getPreferentialPriceResponse.getResult().getActualPrice()));            //订单优惠金额
        if (null != tradeOrderRequest.getOrderDetails() && tradeOrderRequest.getOrderDetails().size() > 0) {
            val PostOrderDetailRequest = new ArrayList<PostOrderDetailRequest>();
            if (null != getPreferentialPriceResponse.getResult().getOrderPreferentialItems()) {
                for (GetPreferentialPriceResponse.OrderPreferentialItem item : getPreferentialPriceResponse.getResult().getOrderPreferentialItems()) {
                    PostOrderDetailRequest postOrderDetailRequest = new PostOrderDetailRequest();
                    BeanUtils.copyProperties(item, postOrderDetailRequest);
                    postOrderDetailRequest.setDiscountAmount(BigDecimalUtils.roundByScale(item.getUnitPrice().subtract(item.getPreferentialUnitPrice())));
                    PostOrderDetailRequest.add(postOrderDetailRequest);
                }
                tradeOrderRequest.setOrderDetails(PostOrderDetailRequest);
            }
        }
//        }
    }
    
    
    /**
     * 获取订单应付金额
     *
     * @param orderDetails
     * @return
     */
    private BigDecimal getOrderAmount(List<PostOrderDetailRequest> orderDetails) {
        BigDecimal orderAmount = BigDecimal.valueOf(0);
        for (val temp : orderDetails) {
            orderAmount = orderAmount.add(BigDecimalUtils.roundByScale(temp.getUnitPrice().multiply(temp.getQuantity())));
        }
        return orderAmount;
    }
    
    /**
     * 订单支付完成方法
     *
     * @return
     */
    public PutOrderPaySuccessResponse updateOrderPaySuccessStatus(PutOrderPaySuccessRequest orderPaySuccessRequest) {
        //1.更新业务订单支付状态
        val orderPaySuccessResponseData = remoteOrderService.updateOrderPaySuccessStatus(orderPaySuccessRequest);
        if (null == orderPaySuccessResponseData || !ApplicationConstants.SUCCESS_CODE.equals(orderPaySuccessResponseData.getCode())) {
            throw new BusinessCommonException(orderPaySuccessResponseData);
        }
        //2.查询订单信息
        val queryShopOrderInfoResponseData = remoteOrderService.queryShopOrderInfo(orderPaySuccessRequest.getOrderNumber());
        if (null == queryShopOrderInfoResponseData || !ApplicationConstants.SUCCESS_CODE.equals(queryShopOrderInfoResponseData.getCode())) {
            throw new BusinessCommonException(queryShopOrderInfoResponseData);
        }
        GetOrderResponse orderResponse = queryShopOrderInfoResponseData.getResult();
        
        //3.更新会员卡积分信息
        if (!StringUtils.isEmpty(orderResponse.getMemberCardNo())) {
            memberHandle(orderResponse);
        }
        orderPaySuccessResponseData.getResult().setPaidTime(DateUtils.format(queryShopOrderInfoResponseData.getResult().getPaidTime(), DateUtils.FORMAT_LONG));
    
        //4.支付完成后将订单信息推送至打印服务
        printerService.pushPrinterTaskByOrderNumber(orderPaySuccessRequest.getOrderNumber(),DictionaryConstant.PRINTER_OPERATION_TYPE_2.getCode());
        
        //扣减库存
        inventoryService.lockInventoryByStatus(orderPaySuccessRequest.getSerialNo(),orderPaySuccessRequest.getOrderNumber(), InventoryConstant.LOCKER_DEDUCTED);
        return orderPaySuccessResponseData.getResult();
    }
    
    public void updateMemberHandle(GetOrderResponse orderResponse) {
        if (!StringUtils.isEmpty(orderResponse.getMemberCardNo())) {
            memberHandle(orderResponse);
        }
    }
    
    /**
     * 充值订单支付完成方法
     *
     * @return
     */
    public PutOrderPaySuccessResponse updateRechargeOrderPaySuccessStatus(PutOrderPaySuccessRequest orderPaySuccessRequest) {
        if(!SignUtils.isSignatureValidSHA256(orderPaySuccessRequest)){
            throw new BusinessCommonException(MemberErrorCode.SIGN_VERIFY_FAILED);
        }

        //2.查询订单信息
        val queryShopOrderInfoResponseData = remoteOrderService.queryShopOrderInfo(orderPaySuccessRequest.getOrderNumber());
        if (null == queryShopOrderInfoResponseData || !ApplicationConstants.SUCCESS_CODE.equals(queryShopOrderInfoResponseData.getCode())) {
            throw new BusinessCommonException(queryShopOrderInfoResponseData);
        }
        GetOrderResponse orderResponse = queryShopOrderInfoResponseData.getResult();
        
        //3.更新会员卡积分信息
        if (!StringUtils.isEmpty(orderResponse.getMemberCardNo())) {
            orderResponse.setPayType(DictionaryConstant.PAY_TYPE_XJ.getCode());
            memberHandle(orderResponse);
        }
        //1.更新业务充值订单支付状态
        val rechargeOrderResponseData = remoteOrderService.updateRechargeOrderPaySuccessStatus(orderPaySuccessRequest);
        if (null == rechargeOrderResponseData || !ApplicationConstants.SUCCESS_CODE.equals(rechargeOrderResponseData.getCode())) {
            throw new BusinessCommonException(rechargeOrderResponseData);
        }
        rechargeOrderResponseData.getResult().setMemberBalance(memberBalance);
        return rechargeOrderResponseData.getResult();
    }
    
    /**
     * 商户支付成功通知方法
     *
     * @return
     */
    public PostPaySuccessNotifyResponse paySuccessNotify(PostPaySuccessNotifyRequest paySuccessNotifyRequest) {
        //1.更新业务充值订单支付状态
        val paySuccessNotifyResponseData = remotePayNotifyService.paySuccessNotify(paySuccessNotifyRequest);
        if (null == paySuccessNotifyResponseData || !ApplicationConstants.SUCCESS.equals(paySuccessNotifyResponseData.getReturnCode())) {
            return paySuccessNotifyResponseData;
        }
        //2.查询订单信息
        val queryShopOrderInfoResponseData = remoteOrderService.queryShopOrderInfo(paySuccessNotifyRequest.getOrderNumber());
        GetOrderResponse orderResponse = queryShopOrderInfoResponseData.getResult();
        //3.用户付款成功，更新会员卡信息
        memberHandle(orderResponse);
    
        //4.支付完成后将订单信息推送至打印服务
        if(queryShopOrderInfoResponseData.getResult().getPayStatus().equals(DictionaryConstant.PAY_STATUS_YFK.getCode())){
            printerService.pushPrinterTaskByOrderNumber(paySuccessNotifyRequest.getOrderNumber(),DictionaryConstant.PRINTER_OPERATION_TYPE_2.getCode());
        }
        
        //扣减库存
        inventoryService.lockInventoryByStatus(orderResponse.getSerialNo(),orderResponse.getOrderNumber(), InventoryConstant.LOCKER_DEDUCTED);
        return paySuccessNotifyResponseData;
    }
    
    /**
     * 会员卡支付方法
     *
     * @param memberCardPayRequest
     * @return
     */
    public PutMemberCardPayResponse memberCardPay(PutMemberCardPayRequest memberCardPayRequest) {
        //检测签名
        if(!SignUtils.isSignatureValidSHA256(memberCardPayRequest)) {
            throw new BusinessCommonException(MemberErrorCode.SIGN_VERIFY_FAILED);
        }
        //0.卡内号与会员账号转换
        if(StringUtils.isEmpty(memberCardPayRequest.getMemberCardNo()) && !StringUtils.isEmpty(memberCardPayRequest.getHardwareCardNo())){
            DetailedMemberResponse detailedMemberData = PosMemberRedisUtils.getMemberByCardHidCode(memberCardPayRequest.getHardwareCardNo());
            if(detailedMemberData == null) {
                detailedMemberData = remoteMemberService.getDetailByHidCode(memberCardPayRequest.getHardwareCardNo()).getResult();
            }

            if(detailedMemberData == null) {
                throw new BusinessCommonException(MemberErrorCode.MEMBER_CARD_NOT_EXIST);
            }
            //注意：这里的使用查询的card_num对应唯一卡号而非MemberCode，防止MemberCode与MemberCardNo不同
            memberCardPayRequest.setMemberCardNo(detailedMemberData. getCardNum());
        }
        //1.查询交易系统订单信息
        val queryShopOrderInfoResponseData = remoteOrderService.queryShopOrderInfoByValidateCardPay(memberCardPayRequest.getSerialNo(), memberCardPayRequest.getOrderNumber());
        if (null == queryShopOrderInfoResponseData || !ApplicationConstants.SUCCESS_CODE.equals(queryShopOrderInfoResponseData.getCode())) {
            throw new BusinessCommonException(queryShopOrderInfoResponseData);
        }
        GetOrderResponse orderResponse = queryShopOrderInfoResponseData.getResult();
        
        //2.调用会员系统相关接口，完成扣款及积分相关操作
        MemberTransactionRequest memberTransactionRequest = new MemberTransactionRequest();
        memberTransactionRequest.setCardNum(memberCardPayRequest.getMemberCardNo());
        memberTransactionRequest.setCardPassword(memberCardPayRequest.getMemberCardPassword());
        memberTransactionRequest.setTransactionOrderNo(orderResponse.getOrderNumber());
        memberTransactionRequest.setTransactionAmount(orderResponse.getRealPayAmount());
        memberTransactionRequest.setTransactionMode(Integer.parseInt(DictionaryConstant.PAY_TYPE_HYK.getCode()));
        memberTransactionRequest.setTransactionTime(orderResponse.getPaidTime());
        
        val memberTradeResponse = remoteMemberService.trade(memberTransactionRequest);
        if (null == memberTradeResponse || !ApplicationConstants.SUCCESS_CODE.equals(memberTradeResponse.getCode())) {
            throw new BusinessCommonException(memberTradeResponse);
        }
//		val memberPointResponse = remoteMemberService.amount2Point(orderResponse.getRealPayAmount());
//		if (null == memberPointResponse || !ApplicationConstants.SUCCESS.equals(memberPointResponse)) {
//			throw new BusinessCommonException(memberPointResponse);
//		}
        Integer score = memberTradeResponse.getResult().getPoint();
        BigDecimal balance = memberTradeResponse.getResult().getBalance();
        
        //3.更新交易系统积分相关信息
        updateOrderScoreHandle(orderResponse.getOrderNumber(), score, balance, ApplicationConstants.TRUE, memberTradeResponse.getResult().getCreatedTime());
        
        val putMemberCardPayResponse = new PutMemberCardPayResponse();
        putMemberCardPayResponse.setScore(score);    //本次订单获赠积分
        putMemberCardPayResponse.setOrderAmount(orderResponse.getOrderAmount());
        putMemberCardPayResponse.setRealPayAmount(orderResponse.getRealPayAmount());
        putMemberCardPayResponse.setDiscountAmount(orderResponse.getDiscountAmount());
        putMemberCardPayResponse.setBalanceAmount(balance);    //会员卡余额
        putMemberCardPayResponse.setPaidTime(DateUtils.format(orderResponse.getPaidTime(), DateUtils.FORMAT_LONG));
    
        //4.支付完成后将订单信息推送至打印服务
        printerService.pushPrinterTaskByOrderNumber(orderResponse.getOrderNumber(),DictionaryConstant.PRINTER_OPERATION_TYPE_2.getCode());
        
    
        //扣减库存
        inventoryService.lockInventoryByStatus(orderResponse.getSerialNo(),orderResponse.getOrderNumber(), InventoryConstant.LOCKER_DEDUCTED);
        
        return putMemberCardPayResponse;
    }
    
    /**
     * 订单支付成功会员信息处理方法
     *
     * @param orderResponse
     */
    private void memberHandle(GetOrderResponse orderResponse) {
        if (StringUtils.isEmpty(orderResponse.getMemberCardNo())) {
            return;
        }
        
        DictionaryConstant dict = DictionaryConstant.getEnumByCode(DictionaryConstant.ORDER_TYPE.getCode(), orderResponse.getOrderType());
        switch (dict) {
            case ORDER_TYPE_ZC:
                MemberTransactionRequest memberTransactionRequest = new MemberTransactionRequest();
                memberTransactionRequest.setCardNum(StringUtils.isEmpty(orderResponse.getCardNum()) ? orderResponse.getMemberCardNo() : orderResponse.getCardNum());
                memberTransactionRequest.setTransactionOrderNo(orderResponse.getOrderNumber());
                memberTransactionRequest.setTransactionAmount(orderResponse.getRealPayAmount());
                memberTransactionRequest.setTransactionMode(Integer.valueOf(orderResponse.getPayType()));
                memberTransactionRequest.setTransactionTime(orderResponse.getPaidTime());
                
                val memberTradeResponse = remoteMemberService.trade(memberTransactionRequest);
                
                if (null == memberTradeResponse || !ApplicationConstants.SUCCESS_CODE.equals(memberTradeResponse.getCode())) {
                    throw new BusinessCommonException(memberTradeResponse);
                }
                updateOrderScoreHandle(orderResponse.getOrderNumber(), memberTradeResponse.getResult().getPoint() ,memberTradeResponse.getResult().getBalance(), ApplicationConstants.FALSE, null);
                break;
            case ORDER_TYPE_HYCZ:
                //会员卡充值订单,处理会员卡充值信息
                MemberRechargeRequest memberRechargeRequest = new MemberRechargeRequest();
                memberRechargeRequest.setCardNum(StringUtils.isEmpty(orderResponse.getCardNum()) ? orderResponse.getMemberCardNo() : orderResponse.getCardNum());
                memberRechargeRequest.setRechargeOrderNo(orderResponse.getOrderNumber());
                memberRechargeRequest.setRechargeAmount(orderResponse.getRealPayAmount());
                memberRechargeRequest.setRechargeMode(Integer.valueOf(orderResponse.getPayType()));
                memberRechargeRequest.setRechargeTime(orderResponse.getPaidTime());
                
                val memberRechargeResponse = remoteMemberService.recharge(memberRechargeRequest);
                if (null == memberRechargeResponse || !ApplicationConstants.SUCCESS_CODE.equals(memberRechargeResponse.getCode())) {
                    throw new BusinessCommonException(memberRechargeResponse);
                }
                memberBalance = String.valueOf(memberRechargeResponse.getResult());
    
                updateOrderScoreHandle(orderResponse.getOrderNumber(), null ,BigDecimal.valueOf(Double.parseDouble(memberBalance)), ApplicationConstants.FALSE, null);
                break;
            case ORDER_TYPE_WXDC:
                //微信点餐订单，处理会员卡积分信息(目前微信点餐暂无会员卡相关内容，可不做操作)
                System.out.println("微信点餐订单，处理会员卡积分信息");
                break;
        }
    }
    
    /**
     * 更新订单获赠积分使用方法
     */
    private void updateOrderScoreHandle(String orderNumber, Integer score,BigDecimal balance, Boolean isPay, Date paidTime) {
        if ((null != score && score > 0) || isPay) {
            val orderScoreRequest = new PutOrderScoreRequest();
            orderScoreRequest.setOrderNumber(orderNumber);
            orderScoreRequest.setScore(score);
            orderScoreRequest.setIsPay(isPay);
            orderScoreRequest.setPaidTime(paidTime);
            orderScoreRequest.setBalance(balance);
            remoteOrderService.updateOrderScore(orderScoreRequest);
        }
    }
    
    /**
     * 订单撤销方法(未支付的订单取消，已支付的订单退款)
     *
     * @return
     */
    public PutUnionReverseOrderResponse reverseOrder(PutReverseOrderRequest reverseOrderRequest) {
        val reverseOrderResponseData = remoteOrderService.reverseOrder(reverseOrderRequest);
        if (null == reverseOrderResponseData || !ApplicationConstants.SUCCESS_CODE.equals(reverseOrderResponseData.getCode())) {
            throw new BusinessCommonException(reverseOrderResponseData);
        }
        //2.交易系统处理退款申请成功,如果会员卡不为空,处理会员积分退还
        if (!StringUtils.isEmpty(reverseOrderResponseData.getResult().getMemberCardNo()) && !StringUtils.isEmpty(reverseOrderResponseData.getResult().getPayType())) {
            MemberRefundRequest memberRefundRequest = new MemberRefundRequest();
            val refundResponse = reverseOrderResponseData.getResult();
            memberRefundRequest.setCardNum(refundResponse.getMemberCardNo());
            memberRefundRequest.setRefundOrderNo(reverseOrderRequest.getOrderNumber());
            memberRefundRequest.setRefundAmount(refundResponse.getRefundAmount());
            memberRefundRequest.setTransactionMode(Integer.valueOf(refundResponse.getPayType()));
            memberRefundRequest.setRefundTime(refundResponse.getRefundTime());
            remoteMemberService.refund(memberRefundRequest);
        }
        //取消库存
        inventoryService.lockInventoryByStatus(reverseOrderRequest.getSerialNo(),reverseOrderRequest.getOrderNumber(), InventoryConstant.LOCKER_CANCEL);
        return new PutUnionReverseOrderResponse(reverseOrderResponseData.getResult().getIsSuccess());
    }
    
    /**
     * 调用交易系统的查询聚合支付三方平台的方法
     *
     * @return ResponseData<GetOrderPayStatusResponse>
     */
    public ResponseData<GetOrderPayStatusResponse> queryOrderPayStatusByThirdPlatform(GetOrderPayStatusRequest orderPayStatusRequest) {
        val getOrderPayStatusResponse = remoteOrderService.queryOrderPayStatusByThirdPlatform(orderPayStatusRequest.getOrderNumber(), orderPayStatusRequest.getSerialNo());
        if (null == getOrderPayStatusResponse || !ApplicationConstants.SUCCESS_CODE.equals(getOrderPayStatusResponse.getCode())) {
            throw new BusinessCommonException(getOrderPayStatusResponse);
        }
        //1.支付完成后将订单信息推送至打印服务
        if(getOrderPayStatusResponse.getResult().getPayStatus().equals(DictionaryConstant.PAY_STATUS_YFK.getCode())){
            printerService.pushPrinterTaskByOrderNumber(orderPayStatusRequest.getOrderNumber(),DictionaryConstant.PRINTER_OPERATION_TYPE_2.getCode());
            inventoryService.lockInventoryByStatus(orderPayStatusRequest.getSerialNo(),orderPayStatusRequest.getOrderNumber(), InventoryConstant.LOCKER_DEDUCTED);
        }
        return getOrderPayStatusResponse;
    }
    
    /**
     * 订单信息创建方法
     *
     * @return
     */
    public PostRecordOrderResponse saveRecordOrder(PostRecordOrderRequest recordOrderRequest) {
        //1.调用执行任务
        RecordOrderTask recordOrderTask = new RecordOrderTask();
        recordOrderTask.setRecordOrderRequest(recordOrderRequest);
        taskExecutor.getExecutorService().submit(recordOrderTask);
        
        //2.返回数据接收成功通知
        PostRecordOrderResponse recordOrderResponse = new PostRecordOrderResponse();
        recordOrderResponse.setIsSuccess(ApplicationConstants.TRUE);
        return recordOrderResponse;
    }
    
    /**
     * 订单补录方法
     */
    private ResponseData<PostTradeRecordOrderResponse> recordOrderHandle(PostTradeRecordOrderRequest tradeRecordOrderRequest) {
        //生成订单前锁定库存
        inventoryService.lockInventory(tradeRecordOrderRequest.getSerialNo(),tradeRecordOrderRequest.getOrderNumber(),tradeRecordOrderRequest.getOrderDetails());
        val recordOrderResponseData = remoteOrderService.recordOrder(tradeRecordOrderRequest);
        //扣减库存
        inventoryService.lockInventoryByStatus(tradeRecordOrderRequest.getSerialNo(),tradeRecordOrderRequest.getOrderNumber(), InventoryConstant.LOCKER_DEDUCTED);
        return recordOrderResponseData;
    }
}
