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

import com.freemud.application.sdk.api.base.BaseRequest;
import com.freemud.application.sdk.api.log.ThirdPartyLog;
import com.freemud.application.sdk.api.ordercenter.config.OrderDownLoadCenterProperties;
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.OrderConditionsReq;
import com.freemud.application.sdk.api.ordercenter.request.QueryAfterSalesOrderConditionsReq;
import com.freemud.application.sdk.api.ordercenter.request.QueryOrderByScrollRequest;
import com.freemud.application.sdk.api.ordercenter.response.BaseDownLoadResponse;
import com.freemud.application.sdk.api.ordercenter.response.AfterSalesListResp;
import com.freemud.application.sdk.api.ordercenter.response.BaseResponse;
import com.freemud.application.sdk.api.ordercenter.response.OrderItemStatisticsResponse;
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.OrderStatisticsResp;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.QueryByCodeResponse;
import com.freemud.application.sdk.api.util.RequestThirdPartyUtils;
import lombok.extern.slf4j.Slf4j;
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;

/**
 * All rights Reserved, Designed By www.freemud.com
 *
 * @version V1.0
 * @Title:
 * @Package: com.freemud.application.sdk.api.ordercenter.service
 * @Descripttion:
 * @author: shuhu.hou
 * @date: 2019/8/1
 * @Copyright: 2017 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目.
 */
@Service
@Slf4j
public class OrderDownLoadSdkService {

    @Autowired
    @Qualifier("orderDownLoadRestTemplate")
    private RestTemplate restTemplate;
    @Autowired
    private OrderDownLoadCenterProperties orderCenterProperties;
    public static final String SUCCESS_RESPONSE_CODE = "100";

    /**
     * 根据综合条件查询订单
     */
    public BaseDownLoadResponse<List<OrderInfoReqs>> queryOrderByConditions(OrderConditionsReq request, String trackingNo) {
        long begin = System.currentTimeMillis();
        BaseDownLoadResponse<List<OrderInfoReqs>> responseDTO = RequestThirdPartyUtils.httpJsonReqComplexDownLoad(restTemplate, InterfaceAddressConstant.QUERY_ORDER_BY_CONDITIONS,
                createBaseRequest(request, trackingNo), new ParameterizedTypeReference<BaseDownLoadResponse<List<OrderInfoReqs>>>() {
                });
        ThirdPartyLog.infoConvertJson(begin, System.currentTimeMillis(), InterfaceAddressConstant.QUERY_ORDER_BY_CONDITIONS, request, responseMini(responseDTO));
        return responseHandle(responseDTO);
    }

    public BaseDownLoadResponse<List<OrderInfoReqs>> queryOrderByScroll(QueryOrderByScrollRequest request, String trackingNo) {
        long begin = System.currentTimeMillis();
        BaseDownLoadResponse<List<OrderInfoReqs>> responseDTO = RequestThirdPartyUtils.httpJsonReqComplexDownLoad(restTemplate, InterfaceAddressConstant.QUERY_ORDER_BY_SCROLL,
                createBaseRequest(request, trackingNo), new ParameterizedTypeReference<BaseDownLoadResponse<List<OrderInfoReqs>>>() {
                });
        ThirdPartyLog.infoConvertJson(begin, System.currentTimeMillis(), InterfaceAddressConstant.QUERY_ORDER_BY_SCROLL, request, responseMini(responseDTO));
        return responseHandle(responseDTO);
    }

    public BaseDownLoadResponse<List<OrderItemStatisticsResponse>> queryOrderItemStatistics(OrderConditionsReq request) {
        long begin = System.currentTimeMillis();
        BaseDownLoadResponse<List<OrderItemStatisticsResponse>> responseDTO = RequestThirdPartyUtils.httpJsonReqComplexDownLoad(restTemplate, InterfaceAddressConstant.QUERY_ORDER_ITEM_STATISTICS,
                createBaseRequest(request, ""), new ParameterizedTypeReference<BaseDownLoadResponse<List<OrderItemStatisticsResponse>>>() {
                });
        ThirdPartyLog.infoConvertJson(begin, System.currentTimeMillis(), InterfaceAddressConstant.QUERY_ORDER_BY_SCROLL, request, responseMini(responseDTO));
        return responseDTO;
    }

    /**
     * 分页查询售后单
     *
     * @param queryRequest
     * @param trackingNo
     * @return
     */
    public AfterSalesListResp queryAfterSalesOrderConditions(QueryAfterSalesOrderConditionsReq queryRequest, String trackingNo) {
        AfterSalesListResp responseDTO = RequestThirdPartyUtils.httpJsonReqComplexNew(restTemplate, InterfaceAddressConstant.QUERY_AFT_SALE_ORDER_LIST,
                createBaseRequest(queryRequest, trackingNo), new ParameterizedTypeReference<AfterSalesListResp>() {
                });
        return responseDTO;
    }

    /**
     * 售后单查询下载
     * @param request
     * @param trackingNo
     * @return
     */
    public BaseDownLoadResponse queryAfterSalesOrderByScrollId(QueryOrderByScrollRequest request, String trackingNo) {
        long begin = System.currentTimeMillis();
        BaseDownLoadResponse<List<AfterSalesOrderResp>> responseDTO = RequestThirdPartyUtils.httpJsonReqComplexDownLoad(restTemplate, InterfaceAddressConstant.QUERY_ORDER_AFTER_SALE_DOWN,
                createBaseRequest(request, trackingNo), new ParameterizedTypeReference<BaseDownLoadResponse<List<AfterSalesOrderResp>>>() {
                });
        ThirdPartyLog.infoConvertJson(begin, System.currentTimeMillis(), InterfaceAddressConstant.QUERY_ORDER_AFTER_SALE_DOWN, request, responseMini(responseDTO));
        return responseHandle(responseDTO);
    }

    /**
     * 根据订单号查询订单详情
     *
     * @param partnerId
     * @param orderCode
     * @param trackingNo
     * @return
     */
    public QueryByCodeResponse queryOrderByCode(String partnerId, String orderCode, String trackingNo) {
        String url = InterfaceAddressConstant.QUERY_ORDER_BY_CODE + "?orderCode=" + orderCode + "&partnerId=" + partnerId;
        QueryByCodeResponse queryResponse = RequestThirdPartyUtils.httpGetReqComplex(this.restTemplate, url
                , createBaseRequest(null, trackingNo), new ParameterizedTypeReference<QueryByCodeResponse>() {
                });
        return queryResponse;
    }

    BaseDownLoadResponse responseMini(BaseDownLoadResponse responseDTO){

        BaseDownLoadResponse baseDownLoadResponse = new BaseDownLoadResponse();

        if(responseDTO == null){
            return baseDownLoadResponse;
        }

        baseDownLoadResponse.setCode(responseDTO.getCode());
        baseDownLoadResponse.setMessage(responseDTO.getMessage());
        baseDownLoadResponse.setVer(responseDTO.getVer());
        baseDownLoadResponse.setScrollId(responseDTO.getScrollId());
        baseDownLoadResponse.setTotalNum(responseDTO.getTotalNum());
        baseDownLoadResponse.setNumber(responseDTO.getNumber());

        return baseDownLoadResponse;
    }

    /**
     * 小助手营业额统计查询
     */
    public BaseResponse<OrderStatisticsResp> queryOrderStatistics(OrderConditionsReq request, String trackingNo) {
        BaseResponse<OrderStatisticsResp> responseDTO = RequestThirdPartyUtils.httpJsonReqComplexDownLoad(restTemplate, InterfaceAddressConstant.QUERY_ORDER_STATISTICS,
                createBaseRequest(request, trackingNo), new ParameterizedTypeReference<BaseResponse<OrderStatisticsResp>>() {
                });
        return responseDTO;
    }

    private <T> BaseDownLoadResponse<T> responseHandle(BaseDownLoadResponse<T> responseDTO) {
        BaseDownLoadResponse baseDownLoadResponse = new BaseDownLoadResponse();
        if (responseDTO == null) {
            baseDownLoadResponse.setCode(ResponseResultEnum.SYSTEM_BUSINESS_ERROR.getCode());
            baseDownLoadResponse.setMessage(ResponseResultEnum.SYSTEM_BUSINESS_ERROR.getMessage());
            return baseDownLoadResponse;
        }
        if (!Objects.equals(SUCCESS_RESPONSE_CODE, responseDTO.getCode())) {
            baseDownLoadResponse.setCode(ResponseResultEnum.SYSTEM_BUSINESS_ERROR.getCode());
            baseDownLoadResponse.setMessage(responseDTO.getMessage());
            return baseDownLoadResponse;
        }
        BaseDownLoadResponse<T> result = new BaseDownLoadResponse<>();
        result.setCode(responseDTO.getCode());
        result.setMessage(responseDTO.getMessage());
        result.setResult(responseDTO.getResult());
        result.setVer(responseDTO.getVer());
        result.setScrollId(responseDTO.getScrollId());
        result.setTotalNum(responseDTO.getTotalNum());
        return result;
    }

    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;
    }



}
