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

import com.neusoft.smart.pos.constants.DictionaryConstant;
import com.neusoft.smart.pos.dto.order.request.PostCreateOrderRequest;
import com.neusoft.smart.pos.dto.order.request.PutCancelOrderRequest;
import com.neusoft.smart.pos.dto.order.response.GetOrderDetailsResponse;
import com.neusoft.smart.pos.dto.order.response.GetOrderPayStatusResponse;
import com.neusoft.smart.pos.dto.order.response.PostOrderResponse;
import com.neusoft.smart.pos.dto.payorder.request.PostCreatePayOrderRequest;
import com.neusoft.smart.pos.dto.trade.request.*;
import com.neusoft.smart.pos.dto.trade.response.*;
import com.neusoft.smart.pos.framework.dto.ResponseData;
import com.neusoft.smart.pos.framework.exception.BusinessCommonException;
import com.neusoft.smart.pos.framework.utils.DateUtils;
import com.neusoft.smart.pos.framework.utils.ListUtils;
import com.neusoft.smart.pos.framework.utils.LocalDateTimeUtils;
import com.neusoft.smart.pos.framework.utils.SignUtils;
import com.neusoft.smart.pos.order.constants.TradeErrorCode;
import com.neusoft.smart.pos.order.persistent.domain.OrderTransaction;
import com.neusoft.smart.pos.order.repository.OrderTransactionRepository;
import com.neusoft.smart.pos.order.service.OrderService;
import com.neusoft.smart.pos.order.utils.WXTokenUtils;
import com.neusoft.smart.pos.payment.constants.PaymentErrorCode;
import com.neusoft.smart.pos.payment.persistent.ext.domain.ThirdPlatformReverseOrder;
import com.neusoft.smart.pos.payment.service.PaymentService;
import com.neusoft.smart.pos.payorder.constants.PayErrorCode;
import com.neusoft.smart.pos.payorder.persistent.domain.PayOrder;
import com.neusoft.smart.pos.payorder.persistent.domain.TradeMchPayDetail;
import com.neusoft.smart.pos.payorder.persistent.domain.TradeSettlementInfo;
import com.neusoft.smart.pos.payorder.repository.MchPayChannelRepository;
import com.neusoft.smart.pos.payorder.repository.PayChannelRepository;
import com.neusoft.smart.pos.payorder.repository.PayTypeDictRepository;
import com.neusoft.smart.pos.payorder.repository.TradeMchPayDetailRepository;
import com.neusoft.smart.pos.payorder.service.PayOrderService;
import com.neusoft.smart.pos.payorder.service.TradeSettlementQueryService;
import com.neusoft.smart.pos.trade.service.PayChannelService;
import com.neusoft.smart.pos.utils.PosDeviceRedisUtils;
import com.neusoft.smart.pos.utils.SequenceUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.val;
import org.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

@Api(value = "订单管理使用rest接口", description = "订单管理使用rest接口")
@RestController
@RequestMapping(path = "/order")
@Validated
public class OldOrderController {

    public static final String DEFAULT_WX_REDIRECT_URI = "http://qrauth.neusoftubione.com/jumpota.html";

    @Value("${smart.pos.constant.wechatOrderUrl}")
    private String wechatOrderUrl;

    @Autowired
    private OrderService orderService;// = ServiceFactory.getOrderServiceInstance(null,null);

    @Autowired
    private PayOrderService payOrderService;

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private PayChannelService payChannelService;

    @Autowired
    private TradeSettlementQueryService tradeSettlementQueryService;

    @Autowired
    private PayTypeDictRepository payTypeDictRepository;

    @Autowired
    private MchPayChannelRepository mchPayChannelRepository;

    @Autowired
    private OrderTransactionRepository orderTransactionRepository;

    @Autowired
    private TradeMchPayDetailRepository tradeMchPayDetailRepository;

    @Autowired
    private PayChannelRepository payChannelRepository;

    ////////////////////////////////////////// 原来的(北国)接口 ///////////////////////////////////////////
    @ApiOperation(value = "订单及预付单生成统一接口", notes = "订单及预付单生成统一方法")
    @PostMapping("/unionPayOrder")
    public ResponseData<PostUnionPayOrderResponse> saveUnionPayOrder(@RequestBody PostTradeOrderRequest tradeOrderRequest) {
        PostCreateOrderRequest createOrderRequest = new PostCreateOrderRequest();
        BeanUtils.copyProperties(tradeOrderRequest, createOrderRequest);
        createOrderRequest.setOrderAmount(tradeOrderRequest.getOrderAmount().longValue()*100);
        createOrderRequest.setOrderDetails(ListUtils.convertListToList(tradeOrderRequest.getOrderDetails(), com.neusoft.smart.pos.dto.order.request.PostOrderDetailRequest.class));

        //根据设备SN校正orgId和shopId
        if(tradeOrderRequest.getSerialNo() != null && !tradeOrderRequest.getSerialNo().isEmpty()) {
            //1.查询订单信息，并进行校验
            val deviceInfo = PosDeviceRedisUtils.getDeviceInfoBySerialNo(tradeOrderRequest.getSerialNo());
            if (null == deviceInfo) {
                throw new BusinessCommonException(TradeErrorCode.DEVICE_ORG_EMPTY);
            }

            createOrderRequest.setOrgId(deviceInfo.getOrganizationId());
            createOrderRequest.setShopId(deviceInfo.getStoreId());
        }

        //如果订单类型参数为空，默认为普通订单
        if(tradeOrderRequest.getOrderType() == null || tradeOrderRequest.getOrderType().isEmpty()){
            createOrderRequest.setOrderType(DictionaryConstant.ORDER_TYPE_ZC.getCode());
        }

        //序列号规则集团ID+门店ID+订单类型
        createOrderRequest.setSeqNo(SequenceUtils.getOrderSequenceNoForDay(createOrderRequest.getOrgId() + "_" + createOrderRequest.getShopId() + "_" + createOrderRequest.getOrderType()));

        //生成订单
        PostOrderResponse postOrderResponse = orderService.createOrder(createOrderRequest);

        //创建支付订单
        //有折扣的先创建支付类型为折扣的支付单
        if(tradeOrderRequest.getDiscountAmount().longValue() > 0) {
            PayOrder resultDiscountPayOrder = createSimplePayOrder(postOrderResponse.getOrderNumber(), DictionaryConstant.PAY_TYPE_DISCOUNT.getCode(), tradeOrderRequest.getDiscountAmount().longValue()*100, null);
            boolean bResult = payOrderService.paySuccess(resultDiscountPayOrder.getTradeId(), resultDiscountPayOrder.getmOrderNumber(), new Date());
            if (!bResult) {
                //
            }
        }
        PostCreatePayOrderRequest createPayOrderRequest = new PostCreatePayOrderRequest();
        createPayOrderRequest.setOrderNumber(postOrderResponse.getOrderNumber());
        createPayOrderRequest.setPayType(tradeOrderRequest.getPayType());
        createPayOrderRequest.setPayAmount(tradeOrderRequest.getOrderAmount().subtract(tradeOrderRequest.getDiscountAmount()).longValue()*100);
        createPayOrderRequest.setRequestDetailInfo("");
        PayOrder payOrder = createPayOrderInfo(createPayOrderRequest);
        orderService.computeOrderStatus(createPayOrderRequest.getOrderNumber());

        //支付
        String prePayResult = "";
        // 判断是否需要调用第三方支付接口
        val payTypeDict = payTypeDictRepository.queryEnablePayTypeDict(payOrder.getPayType());
        val mchPayChannel = mchPayChannelRepository.queryMchPayChannelByMcodeWithBlob(payOrder.getMcode(),payTypeDict.getPayPlatformType());
        if(null != mchPayChannel){
            JSONObject jsonObject = new JSONObject();
            if(!StringUtils.isEmpty(tradeOrderRequest.getScanCode())) {
                jsonObject.put("scanCode", tradeOrderRequest.getScanCode());
            }
            if(!StringUtils.isEmpty(tradeOrderRequest.getOpenId())) {
                jsonObject.put("openId", tradeOrderRequest.getOpenId());
            }
            payOrder.setRequestDetailInfo(jsonObject.toString());
            prePayResult = paymentService.createPayOrder(payOrder);
            if (prePayResult != null) {
                payOrderService.updatePayOrder(payOrder);
            } else {
                throw new BusinessCommonException(PayErrorCode.TRADE_SETTLEMENT_INFO_EMPTY);
            }
            orderService.computeOrderStatus(payOrder.getmOrderNumber());
        }

        //response赋值
        PostUnionPayOrderResponse unionPayOrderResponse = new PostUnionPayOrderResponse();
        BeanUtils.copyProperties(postOrderResponse, unionPayOrderResponse);
        unionPayOrderResponse.setDiscountAmount(new BigDecimal(postOrderResponse.getDiscountAmount()).divide(new BigDecimal(100)));
        unionPayOrderResponse.setOrderAmount(new BigDecimal(postOrderResponse.getOrderAmount()).divide(new BigDecimal(100)));
        unionPayOrderResponse.setRealPayAmount(unionPayOrderResponse.getOrderAmount().subtract(unionPayOrderResponse.getDiscountAmount()));
        if(null != mchPayChannel) {
            JSONObject object = new JSONObject(prePayResult);
            String payCode;
            try {
                payCode = object.getString("codeUrl");
            } catch (Exception e) {
                payCode = "";
            }
            unionPayOrderResponse.setPayCode(payCode);
        }
        unionPayOrderResponse.setPayStatus(payOrder.getPayStatus());
        unionPayOrderResponse.setPaidTime(DateUtils.format(payOrder.getPayTime(),DateUtils.FORMAT_LONG));
        return new ResponseData<>(unionPayOrderResponse);
    }

    // 与orderController中的createSimplePayOrder代码一致
    private PayOrder createSimplePayOrder(String orderNumber, String payType, long couponsAmount,String requestDetailInfo) {
        PostCreatePayOrderRequest createPayOrderRequest = new PostCreatePayOrderRequest();
        createPayOrderRequest.setPayType(payType);
        createPayOrderRequest.setOrderNumber(orderNumber);
        createPayOrderRequest.setPayAmount(couponsAmount);
        createPayOrderRequest.setRequestDetailInfo(requestDetailInfo);
        return createPayOrderInfo(createPayOrderRequest);
    }

    // 与orderController中的createPayOrderInfo代码一致
    private PayOrder createPayOrderInfo(PostCreatePayOrderRequest createPayOrderRequest){
        PayOrder payOrder = new PayOrder();
        BeanUtils.copyProperties(createPayOrderRequest, payOrder);
        payOrder.setmOrderNumber(createPayOrderRequest.getOrderNumber());
        val orderMaster = orderService.getOrderMasterByOrderNumber(createPayOrderRequest.getOrderNumber());
        //3.查询商户结算及聚合支付平台商户信息
        TradeSettlementInfo tradeSettlementInfo = tradeSettlementQueryService.queryTradeSettlementInfo(orderMaster.getOrgId(), orderMaster.getShopId());
        if (null == tradeSettlementInfo) {
            throw new BusinessCommonException(PayErrorCode.TRADE_SETTLEMENT_INFO_EMPTY);
        }

        //4.查询商户是否开通此支付方式渠道
        tradeSettlementQueryService.verifyShopPayChannelByPayType(orderMaster.getOrgId(), orderMaster.getShopId(), createPayOrderRequest.getPayType());

        //5.根据支付方式查询支付信息
        val payTypeDict = tradeSettlementQueryService.queryEnablePayTypeDict(createPayOrderRequest.getPayType());

        //7.获得openId
        val tradeMchPayChannel = payChannelRepository.queryShopPayChannelByPayType(orderMaster.getOrgId(),orderMaster.getShopId(),createPayOrderRequest.getPayType());
        if(null == tradeMchPayChannel){
            throw new BusinessCommonException(TradeErrorCode.PAY_CHANNEL_IS_NOT_OPEN);
        }
        String openIdTemp;
        String openId;
        String openIdCode;
        net.sf.json.JSONObject payInfoJsonObject  = net.sf.json.JSONObject.fromObject(payOrder.getRequestDetailInfo());
        try {
            openId = payInfoJsonObject.getString("openId");
        } catch (Exception e) {
            openId = null;
        }
        try {
            openIdCode = payInfoJsonObject.getString("openIdCode");
        } catch (Exception e) {
            openIdCode = null;
        }
        if (!org.apache.commons.lang3.StringUtils.isEmpty(openIdCode) && org.apache.commons.lang3.StringUtils.isEmpty(openId)) {
            openIdTemp = WXTokenUtils.getOpenId(tradeMchPayChannel.getAppid(), tradeMchPayChannel.getAppSecretKey(), openIdCode);
        } else {
            openIdTemp = openId;
        }

        payOrder.setMcode(tradeSettlementInfo.getMcode());
        payOrder.setDescription("商品支付订单");
        payOrder.setPayTypeName(DictionaryConstant.getEnumByCode(DictionaryConstant.PAY_TYPE.getCode(), createPayOrderRequest.getPayType()).getValue());
        payOrder.setNotifyUrl(payTypeDict.getNotifyUrl());
        payOrder.setTimeExpire(DateUtils.format(orderMaster.getTimeExpire()));
//        payOrder.setPayIp(ip); // TODO 微信公众号支付需要ip，需接口传入
        payOrder.setOpenId(openIdTemp);
        payOrder.setTradeType(DictionaryConstant.WX_TRADE_TYPE_NATIVE.getCode()); // TODO 微信公众号支付用WX_TRADE_TYPE_JSAPI，从接口区分
        payOrder.setDeviceId(orderMaster.getSerialNo());
        payOrder.setDeviceName(orderMaster.getDeviceName());
        TradeMchPayDetail tradeMchPayDetail = tradeMchPayDetailRepository.queryOrderByOrderNumber(orderMaster.getOrgId(), orderMaster.getShopId(), createPayOrderRequest.getPayType());
        if (null != tradeMchPayDetail) {
            payOrder.setStoreId(tradeMchPayDetail.getStoreId());
            payOrder.setPid(tradeMchPayDetail.getPid());
        }
        if(DictionaryConstant.ORDER_TYPE_HYCZ.getCode().equals(orderMaster.getOrderType())){
            if(payOrder.getRequestDetailInfo()!=null && !"".equals(payOrder.getRequestDetailInfo())) {
                try {
                    payOrder.setCardNum(payInfoJsonObject.getString("cardNum"));
                } catch (Exception e) {
                    throw new BusinessCommonException(TradeErrorCode.MEMBER_CARD_IS_EMPTY);
                }
            }else{
                throw new BusinessCommonException(TradeErrorCode.MEMBER_CARD_IS_EMPTY);
            }
        }

        PayOrder resultPayOrder = payOrderService.createPayOrder(payOrder);
        return resultPayOrder;
    }

    @ApiOperation(value = "第三方支付单撤销接口", notes = "根据商户号订单编号撤销预付单信息方法")
    @PutMapping("/reverseOrder")
    public ResponseData<PutReverseOrderResponse> reverseOrder(@RequestBody PutReverseOrderRequest reverseOrderRequest) {
        PutReverseOrderResponse reverseOrderResponse = new PutReverseOrderResponse();
        // 根据orderNumber获得payOrder
        List<PayOrder> payOrderList = payOrderService.queryPayOrderList(reverseOrderRequest.getOrderNumber());
        if(null != payOrderList && payOrderList.size() > 0){
            PayOrder payOrder = payOrderList.get(payOrderList.size()-1);
            reverseOrderResponse.setPayType(payOrder.getPayType());
            //第三方预付单撤销
            ThirdPlatformReverseOrder thirdPlatformReverseOrder = paymentService.reversePayOrder(payOrder);
            if(null != thirdPlatformReverseOrder && thirdPlatformReverseOrder.getReverseStatus().equals("1")){
                throw new BusinessCommonException(TradeErrorCode.PAY_PLATFORM_REVERSE_ORDER_ERROR);
            }
            reverseOrderResponse.setIsSuccess(true);
            reverseOrderResponse.setRefundAmount(new BigDecimal(payOrder.getRefundedAmount().toString()).divide(new BigDecimal(100)));
            reverseOrderResponse.setRefundTime(new Date());
            //更新支付单状态
            payOrder.setPayStatus(DictionaryConstant.PAY_STATUS_YQX.getCode());//状态为关闭
            payOrder.setUpdatedAt(new Date());
            payOrderService.updatePayOrder(payOrder);
            //订单状态更新
            orderService.computeOrderStatus(payOrder.getmOrderNumber());
        } else {
            throw new BusinessCommonException(TradeErrorCode.PAY_PLATFORM_REVERSE_ORDER_ERROR);
        }
        return new ResponseData<>(reverseOrderResponse);
    }

    @ApiOperation(value = "查询聚合支付平台订单支付状态接口", notes = "根据订单编号查询第三方平台支付状态方法")
    @GetMapping("/queryOrderPayStatusByThirdPlatform")
    public ResponseData<com.neusoft.smart.pos.dto.trade.response.GetOrderPayStatusResponse> queryOrderPayStatusByThirdPlatform(@RequestParam(value="orderNumber",defaultValue = "") String orderNumber , @RequestParam(value="serialNo",defaultValue = "") String serialNo) {
        // 根据orderNumber获得payOrder
        List<PayOrder> payOrderList = payOrderService.queryPayOrderList(orderNumber);
        if(null == payOrderList || payOrderList.size() <= 0){
            throw new BusinessCommonException(TradeErrorCode.PAY_ORDER_QUERY_ERROR);
        }
        String tradeId = payOrderList.get(payOrderList.size()-1).getTradeId();
        val response = payOrderService.queryOrderPayStatusByThirdPlatform(serialNo , tradeId);
        boolean bResult = false;
        if(DictionaryConstant.PAY_STATUS_YFK.getCode().equals(response.getPayStatus())){
            bResult = payOrderService.paySuccess(tradeId, orderNumber, DateUtils.parse(response.getPaidTime()));
        }else if(DictionaryConstant.PAY_STATUS_YQX.getCode().equals(response.getPayStatus())){
            bResult = payOrderService.updatePayOrderStatus(tradeId, DictionaryConstant.PAY_STATUS_YQX.getCode());
        }

        if(bResult) {
            orderService.computeOrderStatus(orderNumber);
        }else{
            throw new BusinessCommonException(TradeErrorCode.PAY_ORDER_UPDATE_ERROR);
        }

        com.neusoft.smart.pos.dto.trade.response.GetOrderPayStatusResponse returnResponse = new com.neusoft.smart.pos.dto.trade.response.GetOrderPayStatusResponse();
        BeanUtils.copyProperties(response, returnResponse);
        return new ResponseData<>(returnResponse);
    }

    @ApiOperation(value = "订单支付完成接口", notes = "根据订单编号更新订单支付状态方法")
    @PutMapping("/orderPaySuccess")
    public ResponseData<PutOrderPaySuccessResponse> updateOrderPaySuccessStatus(@Valid @RequestBody PutOrderPaySuccessRequest orderPaySuccessRequest, BindingResult bindingResult) {
        // 根据orderNumber获得payOrder
        List<PayOrder> payOrderList = payOrderService.queryPayOrderList(orderPaySuccessRequest.getOrderNumber());
        if(null == payOrderList || payOrderList.size() <= 0){
            throw new BusinessCommonException(TradeErrorCode.PAY_ORDER_QUERY_ERROR);
        }
        PayOrder payOrder = payOrderList.get(payOrderList.size()-1);
        Date payTime = new Date();
        boolean bResult = payOrderService.paySuccess(payOrder.getTradeId(), payOrder.getmOrderNumber(), payTime,
                orderPaySuccessRequest.getOriTraceNo(), orderPaySuccessRequest.getOriBatchNo(), orderPaySuccessRequest.getRetrvlRefNo(),
                orderPaySuccessRequest.getTransDate(), orderPaySuccessRequest.getRetrvlRefNo());

        PutOrderPaySuccessResponse response = new PutOrderPaySuccessResponse(bResult);
        response.setPaidTime(DateUtils.formatDate(payTime,DateUtils.FORMAT_LONG));
        orderService.computeOrderStatus(payOrder.getmOrderNumber());
        return new ResponseData<>(response);
    }

    @ApiOperation(value = "订单支付状态查询接口", notes = "根据订单编号查询用户支付状态方法")
    @GetMapping("/orderPayStatus")
    public ResponseData<com.neusoft.smart.pos.dto.trade.response.GetOrderPayStatusResponse> queryOrderPayStatus(@Valid @ModelAttribute GetOrderPayStatusRequest orderPayStatusRequest, BindingResult bindingResult, HttpServletRequest request) {
        return new ResponseData<>(orderService.queryOrderPayStatus(orderPayStatusRequest.getSerialNo(),orderPayStatusRequest.getOrderNumber()));
    }

    @ApiOperation(value = "订单支付取消接口", notes = "根据订单编号取消订单支付方法")
    @PutMapping("/cancelOrder")
    public ResponseData<PutCancelOrderPayResponse> cancelOrder(@Valid @RequestBody PutCancelOrderPayRequest cancelOrderPayRequest, BindingResult bindingResult) {
        //1.查询订单信息是否存在
        val orderMaster = orderService.getOrderMasterByOrderNumber(cancelOrderPayRequest.getOrderNumber());
        if(null == orderMaster){
            throw new BusinessCommonException(TradeErrorCode.ORDER_INFO_NOT_EXIST);
        }

        //2.判断订单状态是否为待支付状态
        if(!DictionaryConstant.ORDER_STATUS_DFK.getCode().equals(orderMaster.getOrderStatus())){
            throw new BusinessCommonException(TradeErrorCode.CANCEL_ORDER_FAIL_STATUS);
        }

        //3.订单生成5分钟内不能取消(微信取消订单硬性规则)
        val betweenMinutes = LocalDateTimeUtils.betweenMinutes(LocalDateTimeUtils.convertDateToLocalDateTime(orderMaster.getCreatedAt()),LocalDateTimeUtils.getNow());
        if(betweenMinutes <= 5){
            throw new BusinessCommonException(TradeErrorCode.CANCEL_ORDER_FAIL_TIME);
        }

        //4.查询是否生成预付单
        List<PayOrder> payOrders = payOrderService.queryPayOrderList(cancelOrderPayRequest.getOrderNumber());
        if(null != payOrders && payOrders.size() > 0){
            for (PayOrder payOrder: payOrders ) {
                payOrderService.cancelPayOrder(payOrder.getTradeId());
            }
        }

        //5.更新订单状态
        PutCancelOrderRequest putCancelOrderRequest = new PutCancelOrderRequest();
        BeanUtils.copyProperties(cancelOrderPayRequest, putCancelOrderRequest);
        val result = orderService.cancelOrder(putCancelOrderRequest);
        PutCancelOrderPayResponse response = new PutCancelOrderPayResponse(result.getIsSuccess());
        return new ResponseData<>(response);
    }

    @ApiOperation(value = "订单商品明细查询", notes = "订单商品明细查询")
    @GetMapping("/orderDetails")
    public ResponseData<GetOrderDetailsResponse> queryOrderDetails(@Valid @ModelAttribute GetOrderDetailsRequest orderDetailsRequest, BindingResult bindingResult) {
        return new ResponseData<>(orderService.getOrderGoodsListByOrderNumber(orderDetailsRequest.getOrderNumber()));
    }

    //////////////////////////////// 不知道哪里使用 /////////////////////////////////////////////////////
    @ApiOperation(value = "查询聚合支付平台订单支付状态接口", notes = "根据订单编号查询第三方平台支付状态方法")
    @GetMapping("/queryTradeOrderPayStatusByThirdPlatform")
    public ResponseData<GetOrderPayStatusResponse> queryTradeOrderPayStatusByThirdPlatform(@RequestParam(value="orderNumber",defaultValue = "") String orderNumber , @RequestParam(value="tradeId",defaultValue = "") String tradeId , @RequestParam(value="serialNo",defaultValue = "") String serialNo) {
        val response = payOrderService.queryOrderPayStatusByThirdPlatform(serialNo , tradeId);
        boolean bResult = false;
        if(DictionaryConstant.PAY_STATUS_YFK.getCode().equals(response.getPayStatus())){
            bResult = payOrderService.paySuccess(tradeId, orderNumber, DateUtils.parse(response.getPaidTime()));
        }else if(DictionaryConstant.PAY_STATUS_YQX.getCode().equals(response.getPayStatus())){
            bResult = payOrderService.updatePayOrderStatus(tradeId, DictionaryConstant.PAY_STATUS_YQX.getCode());
        }

        if(bResult) {
            orderService.computeOrderStatus(orderNumber);
        }else{
            throw new BusinessCommonException(TradeErrorCode.PAY_ORDER_UPDATE_ERROR);
        }
        return new ResponseData<>(response);
    }

    @ApiOperation(value = "订单编号查询接口", notes = "订单编号查询接口")
    @GetMapping("/orderNumber")
    public ResponseData<String> queryOrderNumber() {
        return new ResponseData<>(orderService.queryOrderNumber());
    }

    @ApiOperation(value = "订单打印状态更新接口", notes = "根据订单编号更新打印状态方法")
    @PutMapping("/printerFlag")
    public ResponseData<PutPrinterFlagResponse> updatePrinterFlag(@Valid @RequestBody PutPrinterFlagRequest printerFlagRequest, BindingResult bindingResult) {
        return new ResponseData<>(orderService.updatePrinterFlag(printerFlagRequest));
    }

//
//    @ApiOperation(value = "订单生成使用接口", notes = "订单生成使用方法")
//    @PostMapping("/order")
//    public ResponseData<PostOrderResponse> saveOrder(@RequestBody PostTradeOrderRequest tradeOrderRequest) {
//        return new ResponseData<>(orderService.saveOrder(tradeOrderRequest));
//    }
//

//
//    @ApiOperation(value = "微信订单生成接口", notes = "微信订单生成方法")
//    @PostMapping("/wxOrder")
//    public ResponseData<PostWxOrderResponse> saveWxOrder(@RequestBody PostTradeOrderRequest tradeOrderRequest) {
//        return new ResponseData<>(orderService.saveWxOrder(tradeOrderRequest));
//    }
//
//    @ApiOperation(value = "会员卡充值订单生成接口", notes = "会员卡充值订单生成方法")
//    @PostMapping("/rechargeOrder")
//    public ResponseData<PostRechargeOrderResponse> saveRechargeOrder(@RequestBody PostTradeOrderRequest tradeOrderRequest) {
//        return new ResponseData<>(orderService.saveRechargeOrder(tradeOrderRequest));
//    }
//
//    @ApiOperation(value = "预付单生成接口(第三方支付)", notes = "预付单生成接口(第三方支付)方法")
//    @PostMapping("/payOrder")
//    public ResponseData<PostPayOrderResponse> savePayOrder(@Valid @RequestBody PostPayOrderRequest payOrderRequest, BindingResult bindingResult) {
//        return new ResponseData<>(orderService.createPayOrder(payOrderRequest));
//    }
//
//    @ApiOperation(value = "微信预付单生成接口(第三方支付)", notes = "微信预付单生成接口(第三方支付)方法")
//    @PostMapping("/wxPayOrder")
//    public ResponseData<GetWxPayOrderResponse> saveWxPayOrder(@Valid @RequestBody PostWxPayOrderRequest wxPayOrderRequest, BindingResult bindingResult, HttpServletRequest request) {
//        String ip = LocalIpUtils.getIp2(request);
////		String ip = "42.248.62.163";
//        return new ResponseData<>(orderService.createWxPayOrder(wxPayOrderRequest,ip));
//    }
//

//
//    @ApiOperation(value = "充值订单支付完成接口", notes = "根据订单编号更新订单支付状态方法")
//    @PutMapping("/rechargeOrderPaySuccess")
//    public ResponseData<PutOrderPaySuccessResponse> updateRechargeOrderPaySuccessStatus(@Valid @RequestBody PutOrderPaySuccessRequest orderPaySuccessRequest, BindingResult bindingResult) {
//        return new ResponseData<>(orderService.updateOrderPaySuccessStatus(orderPaySuccessRequest,DictionaryConstant.ORDER_TYPE_HYCZ.getCode()));
//    }
//
//    @ApiOperation(value = "订单支付完成接口", notes = "根据订单编号更新订单支付状态方法")
//    @PutMapping("/wxOrderPaySuccess")
//    public ResponseData<PutWxOrderPaySuccessResponse> updateWxOrderPaySuccessStatus(@Valid @RequestBody PutWxOrderPaySuccessRequest wxOrderPaySuccessRequest, BindingResult bindingResult) {
//        return new ResponseData<>(orderService.updateOrderPaySuccessStatusByOrderNumber(wxOrderPaySuccessRequest));
//    }
//
    @ApiOperation(value = "订单信息查询接口", notes = "门店订单信息查询方法")
    @GetMapping("/order")
    public ResponseData<GetOrderResponse> queryShopOrderInfo(@RequestParam(value="orderNumber",defaultValue = "") String orderNumber) {
        if(StringUtils.isEmpty(orderNumber)){
            throw new BusinessCommonException(TradeErrorCode.ORDER_NUMBER_IS_EMPTY);
        }
        val orderMaster = orderService.getOrderMasterByOrderNumber(orderNumber);
        if(null == orderMaster){
            throw new BusinessCommonException(TradeErrorCode.ORDER_INFO_NOT_EXIST);
        }
        GetOrderResponse orderResponse = new GetOrderResponse();
        BeanUtils.copyProperties(orderMaster,orderResponse);
        return new ResponseData<>(orderResponse);
    }

    @ApiOperation(value = "订单商品明细查询", notes = "订单商品明细查询")
    @GetMapping("/orderInfoByOrderNumber")
    public ResponseData<GetOrderInfoByOrderNumberResponse> queryOrderInfoByOrderNumber(@RequestParam(value="orderNumber",defaultValue = "") String orderNumber) {
        //1.查询订单信息
        if(StringUtils.isEmpty(orderNumber)){
            throw new BusinessCommonException(TradeErrorCode.ORDER_NUMBER_IS_EMPTY);
        }
        val orderMaster = orderService.getOrderMasterByOrderNumber(orderNumber);
        if(null == orderMaster){
            throw new BusinessCommonException(TradeErrorCode.ORDER_INFO_NOT_EXIST);
        }
        GetOrderInfoByOrderNumberResponse orderResponse = new GetOrderInfoByOrderNumberResponse();
        BeanUtils.copyProperties(orderMaster,orderResponse);

        //2.查询订单明细信息
        orderService.getOrderGoodsListByOrderNumber(orderNumber);
        List<OrderTransaction> orderTransactionList = orderTransactionRepository.queryOrderDetails(orderNumber);
        List<GetOrderInfoByOrderNumberResponse.OrderDetail> orderDetailList = ListUtils.convertListToList(orderTransactionList,GetOrderInfoByOrderNumberResponse.OrderDetail.class);
        orderResponse.setOrderDetailList(orderDetailList);
        return new ResponseData<>(orderResponse);
    }
//
//    @ApiOperation(value = "订单获赠积分更新接口", notes = "根据订单编号订单获赠积分更新方法")
//    @PutMapping("/orderScore")
//    public ResponseData<PutOrderScoreResponse> updateOrderScore(@Valid @RequestBody PutOrderScoreRequest orderScoreRequest, BindingResult bindingResult) {
//        return new ResponseData<>(orderService.updateOrderScore(orderScoreRequest));
//    }
//
//    @ApiIgnore
//    @GetMapping("/orderByValidateCardPay")
//    public ResponseData<GetOrderResponse> queryShopOrderInfoByValidateCardPay(@RequestParam(value="serialNo",defaultValue = "") String serialNo,@RequestParam(value="orderNumber",defaultValue = "") String orderNumber) {
//        return new ResponseData<>(orderService.queryShopOrderInfoByValidateCardPay(serialNo,orderNumber));
//    }
//

//
//    @ApiOperation(value = "一码付支付接口", notes = "根据用户浏览器区分来源调用聚合支付平台不同支付")
//    @GetMapping("/oneCodePayOrder")
//    public void oneCodePayOrder(@RequestParam(value="serialNo",defaultValue = "") String serialNo , @RequestParam(value="orderNumber",defaultValue = "") String orderNumber , HttpServletRequest request , HttpServletResponse response) throws IOException {
//        String payCode = orderService.oneCodePayOrder(serialNo, orderNumber, request);
//        if (!payCode.equals("")) response.sendRedirect(payCode);
//    }
//
//    @ApiOperation(value = "订单支付状态查询接口", notes = "根据订单编号查询用户支付状态方法")
//    @GetMapping("/wxOrderPayStatus")
//    public ResponseData<GetWxOrderPayStatusResponse> queryWxOrderPayStatus(@Valid @ModelAttribute GetWxOrderPayStatusRequest wxOrderPayStatusRequest, BindingResult bindingResult) {
//        return new ResponseData<>(orderService.queryWxOrderPayStatus(wxOrderPayStatusRequest));
//    }
//
    @RequestMapping(value = "/wxOrderPage",method = RequestMethod.GET)
    public ModelAndView wxOrderPage(@RequestParam(value="shopId",defaultValue = "0") Integer shopId, @RequestParam(value="table",defaultValue = "0") String table, HttpServletRequest request){
//		String orderUrl = "http://fmneupos.malls.iformall.com/wechatOrder/index.html";
        String url = "";
        LinkedHashMap<String, String> params = new LinkedHashMap<>();
        String userAgent = request.getHeader("user-agent").toLowerCase();
        if(userAgent.contains("micromessenger")){//微信客户端

            String orderUrl = "http://qrauth.neusoftubione.com/jumpota.html";
            params.put("appid", payChannelService.queryAppIdByShopId(shopId));
            params.put("redirect_uri", DEFAULT_WX_REDIRECT_URI);
            params.put("response_type", "code");
            params.put("scope", "snsapi_base");

            if(shopId != 0) {
                params.put("shopId", Integer.toString(shopId));
            }
            if(!"0".equals(table)) {
                params.put("tableId", table);
            }

            url = "redirect:https://open.weixin.qq.com/connect/oauth2/authorize?"+ SignUtils.buildUrlParametersStr(params) +"#wechat_redirect";
        } else {
            if(shopId != 0) {
                params.put("shopId", Integer.toString(shopId));
            }
            if(!"0".equals(table)) {
                params.put("tableId", table);
            }
            url = "redirect:" + wechatOrderUrl + "?" + SignUtils.buildUrlParametersStr(params) + "#/splash";
        }
//		String url = "redirect:https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appId+"&redirect_uri="+ URLEncoder.encode(orderUrl)+"&response_type=code&scope=snsapi_base&state="+table+"#wechat_redirect";

        return new ModelAndView(url);
    }
//
//    @ApiOperation(value = "POS机订单补录接口", notes = "POS机订单补录方法")
//    @PostMapping("/recordOrder")
//    public ResponseData<PostTradeRecordOrderResponse> recordOrder(@RequestBody PostTradeRecordOrderRequest tradeRecordOrderRequest) {
//        return new ResponseData<>(orderService.saveRecordOrder(tradeRecordOrderRequest));
//    }
//
//    @ApiOperation(value = "根据菜品查询员工订单信息", notes = "根据菜品查询员工订单信息")
//    @GetMapping("/orderMembers")
//    public ResponseData<PaginationExtendBean<GetOrderMemberResponse>> queryOrderMembers(@Valid @ModelAttribute GetOrderMembersRequest orderDetailsRequest, BindingResult bindingResult) {
//        Integer orgId = RequestHeaderUtil.getOrgIdByRole(orderDetailsRequest.getOrgId());
//        if(null == orgId){
//            throw new BusinessCommonException(CommonErrorCode.PERMISSION_ERROR);
//        }
//        return new ResponseData<>(orderService.queryOrderMembers(orderDetailsRequest));
//    }
//

//

//
//
}
