package com.freemud.application.sdk.api.ordercenter.service;

import com.freemud.application.sdk.api.base.BaseRequest;
import com.freemud.application.sdk.api.ordercenter.config.OrderCenterProperties;
import com.freemud.application.sdk.api.ordercenter.constant.InterfaceAddressConstant;
import com.freemud.application.sdk.api.ordercenter.enums.ResponseResultEnum;
import com.freemud.application.sdk.api.ordercenter.request.*;
import com.freemud.application.sdk.api.ordercenter.request.carpark.ParkingOrderAffirmReq;
import com.freemud.application.sdk.api.ordercenter.request.carpark.ParkingOrderCancelReq;
import com.freemud.application.sdk.api.ordercenter.request.carpark.ParkingOrderCreateReq;
import com.freemud.application.sdk.api.ordercenter.request.create.BatchQueryByCodesReq;
import com.freemud.application.sdk.api.ordercenter.request.create.CreateFatherSonOrderReq;
import com.freemud.application.sdk.api.ordercenter.request.create.CreateOrderRequest;
import com.freemud.application.sdk.api.ordercenter.response.*;
import com.freemud.application.sdk.api.ordercenter.response.carpark.OrderResp;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.AfterSalesOrderResp;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.OrderInfoReqs;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.QueryByCodeResponse;
import com.freemud.application.sdk.api.ordercenter.util.ResponseUtil;
import com.freemud.application.sdk.api.util.RequestThirdPartyUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Objects;

import static com.freemud.application.sdk.api.ordercenter.constant.InterfaceAddressConstant.*;

/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @version V1.0
 * @Title: ${FILE_NAME}
 * @Package com.freemud.mail.core
 * @Description: ${TODO}(用一句话描述该文件做什么)
 * @author: aiqi.gong
 * @date: 2019/1/6 12:26
 * @Copyright: 2018 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */
@Service
@Slf4j
public class OrderSdkService {


    @Autowired
    @Qualifier("orderRestTemplate")
    private RestTemplate restTemplate;
    @Autowired
    private OrderCenterProperties orderCenterProperties;


    public static final String SUCCESS_RESPONSE_CODE = "100";

    /**
     * 创建订单
     */
    public BaseResponse<OrderInfoReqs> createOrder(CreateOrderRequest request, String trackingNo) {
        OrderBaseResp<OrderInfoReqs> responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, InterfaceAddressConstant.CREATE_ORDER,
                createBaseRequest(request, trackingNo), new ParameterizedTypeReference<OrderBaseResp<OrderInfoReqs>>() {
                });
        return responseHandle(responseDTO);
    }

    /**
     * 创建订单 - 开放平台
     */
    public BaseResponse<OrderInfoReqs> createOrderByPlatform(CreateOrderRequest request, String trackingNo) {
        OrderBaseResp<OrderInfoReqs> responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, InterfaceAddressConstant.CREATE_ORDER,
                createBaseRequest(request, trackingNo), new ParameterizedTypeReference<OrderBaseResp<OrderInfoReqs>>() {
                });
        return responseHandleByPlatForm(responseDTO);
    }

    /**
     * 创建父子订单
     */
    public BaseResponse<List<OrderInfoReqs>> createFatherSonOrder(CreateFatherSonOrderReq request, String trackingNo) {
        OrderBaseResp<List<OrderInfoReqs>> responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, InterfaceAddressConstant.CREATE_FATHER_ORDER,
                createBaseRequest(request, trackingNo), new ParameterizedTypeReference<OrderBaseResp<List<OrderInfoReqs>>>() {
                });
        return responseHandle(responseDTO);
    }

    /**
     * 查询单个订单详情
     *
     * @param orderId              订单号
     * @param withOperationHistory 是否带操作历史 0:不带 1:带
     * @param trackingNo           交易号
     * @return
     */
    public QueryByCodeResponse getOrderInfo(String orderId, Integer withOperationHistory, String trackingNo) {
        String url = InterfaceAddressConstant.GET_ORDER_INFO + "?orderCode=" + orderId;
        if (withOperationHistory != null && withOperationHistory == 1) {
            url = url + "?withOperationHistory" + withOperationHistory;
        }
        QueryByCodeResponse responseDTO = RequestThirdPartyUtils.httpGetReqComplex(restTemplate, url,
                createBaseRequest(null, trackingNo), new ParameterizedTypeReference<QueryByCodeResponse>() {
                });
        return responseDTO;
    }


    /**
     * 查询单个订单详情
     *
     * @param orderClient          下单渠道
     * @param orderCode            订单号
     * @param thirdOrderCode       第三方订单号
     * @param withOperationHistory 是否带操作历史 0:不带 1:带
     * @param trackingNo           交易号
     * @return
     */
    public QueryByCodeResponse getOrderInfo(String orderClient, String orderCode, String thirdOrderCode, Integer withOperationHistory, String trackingNo) {
        String url = InterfaceAddressConstant.GET_ORDER_INFO + "?";
        if (orderClient != null) {
            url = url + "orderClient=" + orderClient + "&";
        }
        if (orderCode != null) {
            url = url + "orderCode=" + orderCode + "&";
        }
        if (thirdOrderCode != null) {
            url = url + "thirdOrderCode=" + thirdOrderCode + "&";
        }
        if (withOperationHistory != null && withOperationHistory == 1) {
            url = url + "withOperationHistory=" + withOperationHistory;
        }
        QueryByCodeResponse responseDTO = RequestThirdPartyUtils.httpGetReqComplex(restTemplate, url,
                createBaseRequest(null, trackingNo), new ParameterizedTypeReference<QueryByCodeResponse>() {
                });
        return responseDTO;
    }


    /**
     * 修改订单extinfo信息
     */
    public BaseResponse editOrder(UpdateOrderReq request, String trackingNo) {
        OrderBaseResp responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, InterfaceAddressConstant.EDIT_ORDER,
                createBaseRequest(request, trackingNo), new ParameterizedTypeReference<OrderBaseResp>() {
                });
        return responseHandle(responseDTO);
    }

    /**
     * 订单支付确认（支付成功接口更新支付状态）
     */
    public BaseResponse<PaySuccessResp> paySuccess(PaySuccessReq request, String trackingNo) {
        String url = InterfaceAddressConstant.PAY_SUCCESS;

        if (StringUtils.isNotEmpty(request.getCompleteOrderCode())) {
            url = InterfaceAddressConstant.FATHER_ORDER_PAY_SUCCESS;
        }
        OrderBaseResp<PaySuccessResp> responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, url,
                createBaseRequest(request, trackingNo), new ParameterizedTypeReference<OrderBaseResp<PaySuccessResp>>() {
                });
        return responseHandle(responseDTO);
    }


    /**
     * 删除订单
     */
    public BaseResponse deleteOrder(OrderDeleteReq request, String trackingNo) {
        OrderBaseResp responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, InterfaceAddressConstant.DELETE_ORDER,
                createBaseRequest(request, trackingNo), new ParameterizedTypeReference<OrderBaseResp>() {
                });
        return responseHandle(responseDTO);
    }

    /**
     * 取消订单
     */
    public BaseResponse cancelOrder(OrderCancelReq request, String trackingNo) {
        OrderBaseResp responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, InterfaceAddressConstant.CANCEL_ORDER,
                createBaseRequest(request, trackingNo), new ParameterizedTypeReference<OrderBaseResp>() {
                });
        return responseHandle(responseDTO);
    }

    /**
     * 创建售后单
     */
    public BaseResponse createAfterSalesOrder(CreateAfterSalesOrder request, String trackingNo) {
        OrderBaseResp responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, InterfaceAddressConstant.CREATE_AFTER_SALES_ORDER,
                createBaseRequest(request, trackingNo), new ParameterizedTypeReference<OrderBaseResp>() {
                });
        return responseHandle(responseDTO);
    }

    /**
     * 根据订单查询当前排队位置
     */
    public BaseResponse<Integer> queryQueueIndex(String orderCode, String trackingNo) {
        String url = InterfaceAddressConstant.QUERY_QUEUE_INDEX + "?orderCode=" + orderCode;
        OrderBaseResp<Integer> responseDTO = RequestThirdPartyUtils.httpGetReqComplex(restTemplate, url,
                createBaseRequest(null, trackingNo), new ParameterizedTypeReference<OrderBaseResp<Integer>>() {
                });
        return responseHandle(responseDTO);
    }

    /**
     * 获取门店排队人数
     */
    public BaseResponse<Integer> queryQueueSize(String partnerId, String storeId, String trackingNo) {
        String url = InterfaceAddressConstant.QUERY_QUEUE_SIZE + "?partnerId=" + partnerId + "&storeId=" + storeId;
        OrderBaseResp<Integer> responseDTO = RequestThirdPartyUtils.httpGetReqComplex(restTemplate, url,
                createBaseRequest(null, trackingNo), new ParameterizedTypeReference<OrderBaseResp<Integer>>() {
                });
        return responseHandle(responseDTO);
    }

    /**
     * 根据用户综合条件查询
     */
    public BaseResponse<QueryOrderForUserResp> queryOrderForUser(OrderUserConditionsReq request, String trackingNo) {
        OrderBaseResp<QueryOrderForUserResp> responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, InterfaceAddressConstant.QUERY_ORDER_FOR_USER,
                createBaseRequest(request, trackingNo), new ParameterizedTypeReference<OrderBaseResp<QueryOrderForUserResp>>() {
                });
        return responseHandle(responseDTO);
    }

    /**
     * 根据订单编号查询订单状态跟踪信息
     */
    public BaseResponse<List<OrderTraceInfoResp>> queryTrackInfo(String orderCode, String trackingNo) {
        String url = InterfaceAddressConstant.QUERY_TRACK_INFO + "?orderCode=" + orderCode;
        OrderBaseResp<List<OrderTraceInfoResp>> responseDTO = RequestThirdPartyUtils.httpGetReqComplex(restTemplate, url, createBaseRequest(null, trackingNo), new ParameterizedTypeReference<OrderBaseResp<List<OrderTraceInfoResp>>>() {
        });
        return responseHandle(responseDTO);
    }


    /**
     * 门店pos拉取订单
     */
    public BaseResponse<PullOrderResponse> pullOrders(PullOrdersReq request, String trackingNo) {
        OrderBaseResp<PullOrderResponse> responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, InterfaceAddressConstant.PULL_ORDERS,
                createBaseRequest(request, trackingNo), new ParameterizedTypeReference<OrderBaseResp<PullOrderResponse>>() {
                });
        return responseHandle(responseDTO);
    }

    /**
     * 接单
     */
    public BaseResponse acceptOrder(POSOrderOperationBaseReq request, String trackingNo) {
        OrderBaseResp responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, InterfaceAddressConstant.ACCEPT_ORDER,
                createBaseRequest(request, trackingNo), new ParameterizedTypeReference<OrderBaseResp>() {
                });
        return responseHandle(responseDTO);
    }

    /**
     * 制作完成
     */
    public BaseResponse prepareComplete(POSOrderOperationBaseReq request, String trackingNo) {
        OrderBaseResp responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, InterfaceAddressConstant.MAKE_FINISH,
                createBaseRequest(request, trackingNo), new ParameterizedTypeReference<OrderBaseResp>() {
                });
        return responseHandle(responseDTO);
    }

    /**
     * 接单直接发货
     */
    public BaseResponse directDelivery(POSOrderOperationBaseReq request, String trackingNo) {
        OrderBaseResp responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, InterfaceAddressConstant.SEND_ORDER,
                createBaseRequest(request, trackingNo), new ParameterizedTypeReference<OrderBaseResp>() {
                });
        return responseHandle(responseDTO);
    }

    /**
     * 无配送完成
     */
    public BaseResponse completeDelivery(POSOrderOperationBaseReq request, String trackingNo) {
        OrderBaseResp responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, InterfaceAddressConstant.DELIVERY_COMPLETE_ORDER,
                createBaseRequest(request, trackingNo), new ParameterizedTypeReference<OrderBaseResp>() {
                });
        return responseHandle(responseDTO);
    }

    /**
     * 通用订单状态修改
     */
    public BaseResponse updateOrderState(OrderChangeStateReq request, String trackingNo) {
        OrderBaseResp responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, InterfaceAddressConstant.UPDATE_ORDER_STATE,
                createBaseRequest(request, trackingNo), new ParameterizedTypeReference<OrderBaseResp>() {
                });
        return responseHandle(responseDTO);
    }

    /**
     * 已配送完成
     */
    public BaseResponse prepareCompleteDelivery(POSOrderOperationBaseReq request, String trackingNo) {
        OrderBaseResp responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, InterfaceAddressConstant.PREPARE_COMPLETE_ORDER,
                createBaseRequest(request, trackingNo), new ParameterizedTypeReference<OrderBaseResp>() {
                });
        return responseHandle(responseDTO);
    }

    /**
     * 售后单审核-同意并退货完成
     */
    public BaseResponse adultApproveWithGoodsReturned(AfterSalesOperateReq request, String trackingNo) {
        OrderBaseResp responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, InterfaceAddressConstant.REFUND_RETURN,
                createBaseRequest(request, trackingNo), new ParameterizedTypeReference<OrderBaseResp>() {
                });
        return responseHandle(responseDTO);
    }

    /**
     * 售后单审核-同意并退款完成
     */
    public BaseResponse adultApproveWithRefundComplete(AfterSalesOperateReq request, String trackingNo) {
        OrderBaseResp responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, InterfaceAddressConstant.REFUND_COMPLETE,
                createBaseRequest(request, trackingNo), new ParameterizedTypeReference<OrderBaseResp>() {
                });
        return responseHandle(responseDTO);
    }

    /**
     * 售后单审核-退款完成
     */
    public BaseResponse adultWithRefundComplete(AfterSalesOperateReq request, String trackingNo) {
        OrderBaseResp responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, InterfaceAddressConstant.ADULT_REFUND_COMPLETE,
                createBaseRequest(request, trackingNo), new ParameterizedTypeReference<OrderBaseResp>() {
                });
        return responseHandle(responseDTO);
    }

    /**
     * 售后单审核-拒绝申请
     */
    public BaseResponse adultReject(AfterSalesOperateReq request, String trackingNo) {
        OrderBaseResp responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, InterfaceAddressConstant.REFUND_REJECT,
                createBaseRequest(request, trackingNo), new ParameterizedTypeReference<OrderBaseResp>() {
                });
        return responseHandle(responseDTO);
    }


    /**
     * 根据综合条件查询订单
     */
    public BaseResponse<QueryOrderForUserResp> queryOrderByConditions(OrderConditionsReq request, String trackingNo) {
        OrderBaseResp<QueryOrderForUserResp> responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, InterfaceAddressConstant.QUERY_ORDER_BY_CONDITIONS,
                createBaseRequest(request, trackingNo), new ParameterizedTypeReference<OrderBaseResp<QueryOrderForUserResp>>() {
                });
        return responseHandle(responseDTO);
    }


    /**
     * 修改订单配送信息
     */
    public BaseResponse updateDeliveryInfo(OrderExpressReq request, String trackingNo) {
        OrderBaseResp responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, InterfaceAddressConstant.UPDATE_DELIVERY_INFO,
                createBaseRequest(request, trackingNo), new ParameterizedTypeReference<OrderBaseResp>() {
                });
        return responseHandle(responseDTO);
    }

    /**
     * 统计门店订单数据
     */
    public BaseResponse<StoreOrderStatisticResp> queryStatisticStoreOrder(StoreOrderStatisticReq request, String trackingNo) {
        OrderBaseResp<StoreOrderStatisticResp> responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, InterfaceAddressConstant.STORE_ORDER_STATISTIC,
                createBaseRequest(request, trackingNo), new ParameterizedTypeReference<OrderBaseResp<StoreOrderStatisticResp>>() {
                });
        return responseHandle(responseDTO);
    }

    /**
     * 综合条件查询下载订单
     */
    public QueryOrderByConditionsResonse orderDownload(OrderConditionsReq request, String trackingNo) {
        QueryOrderByConditionsResonse responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, InterfaceAddressConstant.QUERY_ORDER_BY_CONDITIONS,
                createBaseRequest(request, trackingNo), new ParameterizedTypeReference<QueryOrderByConditionsResonse>() {
                });
        return responseDTO;
    }

    /**
     * POS拉单
     *
     * @param request
     * @param trackingNo
     * @return
     */
    public BaseResponse<BatchQueryResp> batchQuery(BatchQueryReq request, String trackingNo) {
        BatchQueryBaseResponse<QueryOrderForUserResp> responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, InterfaceAddressConstant.BATCH_QUERY,
                createBaseRequest(request, trackingNo), new ParameterizedTypeReference<BatchQueryBaseResponse<QueryOrderForUserResp>>() {
                });
        return createBatchQueryResponse(responseDTO);
    }

    private BaseResponse<BatchQueryResp> createBatchQueryResponse(BatchQueryBaseResponse<QueryOrderForUserResp> responseDTO) {
        if (responseDTO == null) {
            return null;
        }
        BaseResponse<BatchQueryResp> response = new BaseResponse<>();
        response.setVer(responseDTO.getVer());
        response.setCode(responseDTO.getCode());
        response.setMessage(responseDTO.getMessage());
        QueryOrderForUserResp resultDTO = responseDTO.getResult();
        if (resultDTO == null) {
            return response;
        }
        BatchQueryResp result = new BatchQueryResp();
        result.setItemList(resultDTO.getItemList());
        result.setPageNum(resultDTO.getPageNum());
        result.setPageSize(resultDTO.getPageSize());
        result.setPages(resultDTO.getPages());
        result.setTotal(resultDTO.getTotal());
        result.setNextOrderCode(responseDTO.getNextOrderCode());
        result.setNextStartTimestamp(responseDTO.getNextStartTimestamp());
        response.setResult(result);
        return response;
    }

    /**
     * 根据活动查询订单
     *
     * @param request
     * @param trackingNo
     * @return
     */
    public BaseResponse<QueryOrderForUserResp> queryOrderByDiscount(OrderDiscountReq request, String trackingNo) {
        OrderBaseResp<QueryOrderForUserResp> responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, InterfaceAddressConstant.QUERY_ORDER_BY_DISCOUNT,
                createBaseRequest(request, trackingNo), new ParameterizedTypeReference<OrderBaseResp<QueryOrderForUserResp>>() {
                });
        return responseHandle(responseDTO);
    }

    /**
     * 获取申请退单订单接口
     *
     * @param orderRefundQueryReq
     * @param trackingNo
     * @return
     */
    public BaseResponse<AfterSalesPageResp> queryAfterSalesList(OrderRefundQueryReq orderRefundQueryReq, String trackingNo) {
        OrderBaseResp<AfterSalesPageResp> responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, InterfaceAddressConstant.QUERY_AFTER_SALES_ORDER,
                createBaseRequest(orderRefundQueryReq, trackingNo), new ParameterizedTypeReference<OrderBaseResp<AfterSalesPageResp>>() {
                });
        return responseHandle(responseDTO);
    }

    /**
     * POS拉售后单
     *
     * @param BatchQueryAfterSalesReq
     * @param trackingNo
     */
    public BaseResponse<BatchQueryAfterSalesResp> batchQueryAfterSales(BatchQueryAfterSalesReq BatchQueryAfterSalesReq, String trackingNo) {
        BatchQueryAfterSalesBaseResponse<AfterSalesPageResp> responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, InterfaceAddressConstant.BATCH_QUERY_AFTER_SALES,
                createBaseRequest(BatchQueryAfterSalesReq, trackingNo), new ParameterizedTypeReference<BatchQueryAfterSalesBaseResponse<AfterSalesPageResp>>() {
                });
        return createBaseResponse(responseDTO);
    }

    /**
     * 根据订单号查询售后单
     * @param partnerId
     * @param orderCode
     * @return
     */
    public BaseResponse<List<AfterSalesOrderResp>> queryAfterSaleByOrderCode(String partnerId,String orderCode){
        QueryAfterSalesByOrderCodeReq queryAfterSalesByOrderCodeReq = new QueryAfterSalesByOrderCodeReq();
        queryAfterSalesByOrderCodeReq.setOrderCode(orderCode);
        queryAfterSalesByOrderCodeReq.setPartnerId(partnerId);
        OrderBaseResp<List<AfterSalesOrderResp>> responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, InterfaceAddressConstant.QUERY_AFTER_SALES_BY_ORDERCODE,
                createBaseRequest(queryAfterSalesByOrderCodeReq, ""), new ParameterizedTypeReference<OrderBaseResp<List<AfterSalesOrderResp>>>() {
                });
        return responseHandle(responseDTO);

    }

    private BaseResponse<BatchQueryAfterSalesResp> createBaseResponse(BatchQueryAfterSalesBaseResponse<AfterSalesPageResp> responseDTO) {
        if (responseDTO == null) {
            return responseHandle(null);
        }
        OrderBaseResp<BatchQueryAfterSalesResp> response = new OrderBaseResp<>();
        response.setVer(responseDTO.getVer());
        response.setCode(responseDTO.getCode());
        response.setMessage(responseDTO.getMessage());
        BatchQueryAfterSalesResp result = new BatchQueryAfterSalesResp();
        result.setNextOrderCode(responseDTO.getNextOrderCode());
        result.setNextStartTimestamp(responseDTO.getNextStartTimestamp());

        AfterSalesPageResp resultDTO = responseDTO.getResult();
        if (resultDTO == null) {
            response.setResult(result);
            return responseHandle(response);
        }
        result.setItemList(resultDTO.getItemList());
        result.setPageNum(resultDTO.getPageNum());
        result.setPageSize(resultDTO.getPageSize());
        result.setPages(resultDTO.getPages());
        result.setTotal(resultDTO.getTotal());
        response.setResult(result);
        return responseHandle(response);
    }


    /**
     * 批量查询订单状态
     *
     * @param queryOrdersStateReq
     * @param trackingNo
     * @return
     */
    public BaseResponse<List<QueryOrderStateResp>> queryOrdersState(QueryOrdersStateReq queryOrdersStateReq, String trackingNo) {
        OrderBaseResp<List<QueryOrderStateResp>> responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, InterfaceAddressConstant.QUERY_ORDERS_STATE,
                createBaseRequest(queryOrdersStateReq, trackingNo), new ParameterizedTypeReference<OrderBaseResp<List<QueryOrderStateResp>>>() {
                });
        return responseHandle(responseDTO);
    }

    /**
     * 批量查询订单明细
     *
     * @param request
     * @param trackingNo
     * @return
     */
    public BaseResponse<List<OrderInfoReqs>> batchQueryByCodes(BatchQueryByCodesReq request, String trackingNo) {
        OrderBaseResp<List<OrderInfoReqs>> responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, InterfaceAddressConstant.BATCH_ORDER_BY_CODES,
                createBaseRequest(request, trackingNo), new ParameterizedTypeReference<OrderBaseResp<List<OrderInfoReqs>>>() {
                });
        return responseHandle(responseDTO);
    }


    private <T> BaseResponse<T> responseHandle(OrderBaseResp<T> responseDTO) {
        if (responseDTO == null) {
            return ResponseUtil.error(ResponseResultEnum.SYSTEM_BUSINESS_ERROR.getCode(), ResponseResultEnum.SYSTEM_BUSINESS_ERROR.getMessage());
        }
        if (!Objects.equals(SUCCESS_RESPONSE_CODE, responseDTO.getCode())) {
            return ResponseUtil.error(ResponseResultEnum.SYSTEM_BUSINESS_ERROR.getCode(), responseDTO.getMessage());
        }
        BaseResponse<T> result = new BaseResponse<>();
        result.setCode(responseDTO.getCode());
        result.setMessage(responseDTO.getMessage());
        result.setResult(responseDTO.getResult());
        result.setVer(responseDTO.getVer());
        return result;
    }

    private <T> BaseResponse<T> responseHandleByPlatForm(OrderBaseResp<T> responseDTO) {
        if (responseDTO == null) {
            return ResponseUtil.error(ResponseResultEnum.SYSTEM_BUSINESS_ERROR.getCode(), ResponseResultEnum.SYSTEM_BUSINESS_ERROR.getMessage());
        }
        BaseResponse<T> result = new BaseResponse<>();
        result.setCode(responseDTO.getCode());
        result.setMessage(responseDTO.getMessage());
        result.setResult(responseDTO.getResult());
        result.setVer(responseDTO.getVer());
        return result;
    }

    /**
     * @param
     * @param trackingNo
     * @return
     */
    public BaseResponse updateThirdOrderCode(SdkNewOrderUpdateThirdOrderCodeReq sdkNewOrderUpdateThirdOrderCodeReq, String trackingNo) {
        OrderBaseResp responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, InterfaceAddressConstant.UPDATE_THIRD_ORDER_CODE,
                createBaseRequest(sdkNewOrderUpdateThirdOrderCodeReq, trackingNo), new ParameterizedTypeReference<OrderBaseResp>() {
                });
        return responseHandle(responseDTO);
    }

    /**
     * 更新订单异常信息
     * @param updateAbnormalState
     * @return
     */
    public BaseResponse updateAbnormalState(SdkUpdateAbnormalState updateAbnormalState) {
        OrderBaseResp responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, InterfaceAddressConstant.UPDATE_ABNORMAL_STATE,
                createBaseRequest(updateAbnormalState, ""), new ParameterizedTypeReference<OrderBaseResp>() {
                });
        return responseHandle(responseDTO);
    }

    /**
     * 查询关联订单信息
     *
     * @param request
     * @param trackingNo
     * @return
     */
    public BaseResponse<List<OrderInfoReqs>> queryRelatedOrderByCode(QueryRelatedOrderByCodeReq request, String trackingNo) {
        StringBuilder urlString = new StringBuilder(InterfaceAddressConstant.QUERY_RELATED_ORDER_BY_CODE)
                .append("?orderCode=").append(request.getOrderCode());
        OrderBaseResp<List<OrderInfoReqs>> responseDTO = RequestThirdPartyUtils.httpGetReqComplex(restTemplate, urlString.toString(),
                createBaseRequest(null, trackingNo), new ParameterizedTypeReference<OrderBaseResp<List<OrderInfoReqs>>>() {
                });
        return responseHandle(responseDTO);
    }

    private <T> BaseRequest<T> createBaseRequest(T req, String trackingNo) {
        BaseRequest<T> request = new BaseRequest<>();
        request.setRequestBody(req);
        request.setAppName(orderCenterProperties.getAppName());
        request.setBaseUrl(orderCenterProperties.getBaseUrl());
        request.setTrackingNo(trackingNo);
        return request;
    }

    /**
     * 围餐订单完成
     * @param groupOrderAffirmReq
     * @param trackingNo
     * @return
     */
    public BaseResponse<PaySuccessResp> affirmGroupOrder(GroupOrderAffirmReq groupOrderAffirmReq, String trackingNo){
        OrderBaseResp<PaySuccessResp> orderBaseResp = RequestThirdPartyUtils.httpJsonReqComplexNew(this.restTemplate, InterfaceAddressConstant.GROUP_AFFIRM, createBaseRequest(groupOrderAffirmReq, trackingNo), new ParameterizedTypeReference<OrderBaseResp<PaySuccessResp>>() {});
        return responseHandle(orderBaseResp);
    }

    /**
     * 围餐创建订单
     * @param createOrderRequest
     * @param trackingNo
     * @return
     */
    public BaseResponse<OrderInfoReqs> createGroupOrder(GroupCreateOrderRequest createOrderRequest,String trackingNo){
        OrderBaseResp<OrderInfoReqs> orderBaseResp = RequestThirdPartyUtils.httpJsonReqComplexNew(this.restTemplate, InterfaceAddressConstant.GROUP_CREATE, createBaseRequest(createOrderRequest, trackingNo), new ParameterizedTypeReference<OrderBaseResp<OrderInfoReqs>>() {});
        return responseHandle(orderBaseResp);
    }

    /**
     * 修改订单(围餐)
     * @param groupOrderAffirmReq
     * @param trackingNo
     * @return
     */
    public QueryByCodeResponse updateGroupOrder(GroupOrderUpdateReq groupOrderAffirmReq, String trackingNo){
        QueryByCodeResponse queryByCodeResponse = RequestThirdPartyUtils.httpJsonReqComplexNew(this.restTemplate, InterfaceAddressConstant.GROUP_UPDATEORDER, createBaseRequest(groupOrderAffirmReq, trackingNo), new ParameterizedTypeReference<QueryByCodeResponse>() {});
        return queryByCodeResponse;
    }

    /**
     * 清空订单商品
     * @param groupOrderAffirmReq
     * @param trackingNo
     * @return
     */
    public BaseResponse<PaySuccessResp> clearGroupOrder(GroupOrderClearReq groupOrderAffirmReq,String trackingNo){
        StringBuilder urlString = new StringBuilder(InterfaceAddressConstant.GROUP_CLEARITEMS);
        urlString.append("?");
                if(StringUtils.isNotEmpty(groupOrderAffirmReq.getOrderCode())){
                    urlString.append("&orderCode=")
                            .append(groupOrderAffirmReq.getOrderCode());
                }
                if(groupOrderAffirmReq.getOrderClient() != null && groupOrderAffirmReq.getOrderClient() != 0){
                    urlString.append("&orderClient=")
                            .append(groupOrderAffirmReq.getOrderClient());
                }
                if(StringUtils.isNotEmpty(groupOrderAffirmReq.getPartnerId())){
                    urlString.append("&partnerId=")
                            .append(groupOrderAffirmReq.getPartnerId());
                }
                if(StringUtils.isNotEmpty(groupOrderAffirmReq.getThirdOrderCode())){
                    urlString.append("&thirdOrderCode=")
                            .append(groupOrderAffirmReq.getThirdOrderCode());
                }
                urlString.deleteCharAt(urlString.indexOf("&"));
        OrderBaseResp<PaySuccessResp> orderBaseResp = RequestThirdPartyUtils.httpGetReqComplex(this.restTemplate, urlString.toString(), createBaseRequest(null, trackingNo), new ParameterizedTypeReference<OrderBaseResp<PaySuccessResp>>() {});
        return responseHandle(orderBaseResp);
    }

    /**
     * 围餐订单清台关闭未支付订单
     */
    public BaseResponse<PaySuccessResp> groupClose(GroupDiningCloseReq request, String trackingNo) {
        String url = InterfaceAddressConstant.GROUP_CLOSE;
        OrderBaseResp<PaySuccessResp> responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, url,
                createBaseRequest(request, trackingNo), new ParameterizedTypeReference<OrderBaseResp<PaySuccessResp>>() {
                });
        return responseHandle(responseDTO);
    }

    /**
     * 会员订单支付成功使用
     * /order/v2/affirm 订单确认（从订单未支付或下单状态变成订单完成）
     */
    public BaseResponse<PaySuccessResp> orderAffirm(OrderAffirmReq request, String trackingNo){
        String url = InterfaceAddressConstant.ORDER_AFFIRM;
        OrderBaseResp<PaySuccessResp> responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, url,
                createBaseRequest(request, trackingNo), new ParameterizedTypeReference<OrderBaseResp<PaySuccessResp>>() {
                });
        return responseHandle(responseDTO);
    }

    /**
     * 根据用户ID 查询30分钟内未支付并且有券的 订单
     *
     * @param userId              用户ID
     * @param trackingNo           交易号
     * @return
     */
    public BaseResponse<QueryOrderForUserResp> queryOrderWithCoupon(String userId, String trackingNo) {
        String url = InterfaceAddressConstant.QUERY_ORDER_WITH_COUPON + "?userId=" + userId;
        OrderBaseResp<QueryOrderForUserResp> responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, url,
                createBaseRequest(null, trackingNo), new ParameterizedTypeReference<OrderBaseResp<QueryOrderForUserResp>>() {
                });
        return responseHandle(responseDTO);
    }

    /**
     * @param
     * @param trackingNo
     * @return
     */
    public BaseResponse updateDownstreamThirdOrderCode(UpdateDownstreamOrderCodeReq updateDownstreamOrderCodeReq, String trackingNo) {
        OrderBaseResp responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, InterfaceAddressConstant.UPDATE_DOWNSTREAM_THIRD_ORDER_CODE,
                createBaseRequest(updateDownstreamOrderCodeReq, trackingNo), new ParameterizedTypeReference<OrderBaseResp>() {
                });
        return responseHandle(responseDTO);
    }

    /**
     * 查询单个订单详情
     *
     * @param downstreamPosCode          下单渠道
     * @param downstreamThirdOrderCode            订单号
     * @param trackingNo           交易号
     * @return
     */
    public QueryByCodeResponse getOrderInfoByDownstream(String downstreamPosCode, String downstreamThirdOrderCode, String trackingNo) {
        String url = InterfaceAddressConstant.GET_ORDER_INFO_DOWNSTREAM + "?";
        url = url + "downstreamPosCode=" + downstreamPosCode + "&" + "downstreamThirdOrderCode=" + downstreamThirdOrderCode + "&";
        QueryByCodeResponse responseDTO = RequestThirdPartyUtils.httpGetReqComplex(restTemplate, url,
                createBaseRequest(null, trackingNo), new ParameterizedTypeReference<QueryByCodeResponse>() {
                });
        return responseDTO;
    }

    /**
     * 新增结算信息,保存虚拟商品订单异步发券券信息
     * @return
     */
    public BaseResponse createSettlement(OrderSettlementReq request, String trackingNo) {
        String url = InterfaceAddressConstant.CREATE_SETTLEMENT;
        OrderBaseResp<PaySuccessResp> responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, url,
                createBaseRequest(request, trackingNo), new ParameterizedTypeReference<OrderBaseResp<PaySuccessResp>>() {
                });
        return responseHandle(responseDTO);
    }


    /**
     * 停车场 创建订单
     */
    public BaseResponse parking_v2_create(ParkingOrderCreateReq request, String trackingNo) {
        OrderBaseResp<OrderResp> responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, PARKING_V2_CREATE,
                createBaseRequest(request, trackingNo), new ParameterizedTypeReference<OrderBaseResp<OrderResp>>() {
                });
        return responseHandle(responseDTO);
    }


    /**
     * /parking/v2/affirm
     * 完成停车订单
     */
    public BaseResponse parking_v2_affirm(ParkingOrderAffirmReq request, String trackingNo) {
        OrderBaseResp<OrderResp> responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, PARKING_V2_AFFIRM,
                createBaseRequest(request, trackingNo), new ParameterizedTypeReference<OrderBaseResp<OrderResp>>() {
                });
        return responseHandle(responseDTO);
    }

    /**
     * /parking/v2/cancel
     * 审核不通过
     */
    public BaseResponse parking_v2_cancel(ParkingOrderCancelReq request, String trackingNo) {
        OrderBaseResp<OrderResp> responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, PARKING_V2_CANCEL,
                createBaseRequest(request, trackingNo), new ParameterizedTypeReference<OrderBaseResp<OrderResp>>() {
                });
        return responseHandle(responseDTO);
    }

}
