package cn.freemud.platform.sdk.common.service;

/**
 * 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/3/18 18:07
 * @Copyright: 2018 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */

import cn.freemud.platform.sdk.common.log.BusinessSign;
import cn.freemud.platform.sdk.common.log.ErrorLog;
import cn.freemud.platform.sdk.common.log.ThirdPartyLog;
import cn.freemud.platform.sdk.common.util.CustomBeanUtil;
import cn.freemud.platform.sdk.hualala.request.HuaLaLaCommonRequest;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

public class CloudService {
    @Autowired
    @Qualifier("hualalaRestTemplate")
    private RestTemplate restTemplate;

    public CloudService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }


    public <T, R> R doSend(String trackingNo, String url, T requestBody, Class<R> response) {
        long startTime = System.currentTimeMillis();
        ResponseEntity<String> entity = null;
        HttpHeaders headers = this.buildHttpHeader(MediaType.APPLICATION_FORM_URLENCODED, requestBody, trackingNo);
        HttpEntity<T> httpReq = new HttpEntity<T>((T) this.buildFormParams(requestBody), headers);
        try {
            entity = restTemplate.exchange(url, HttpMethod.POST, httpReq, String.class);
        } catch (Exception e) {
            ErrorLog.errorConvertJson("", "", trackingNo, "", startTime, System.currentTimeMillis(), url, entity, e);
        } finally {
            ThirdPartyLog.infoConvertJson(trackingNo, startTime, System.currentTimeMillis(), BusinessSign.API, url, "", requestBody, entity != null ? entity.getBody() : entity, "", "");
        }
        try {
            return entity != null ? JSONObject.parseObject(entity.getBody(), response) : response.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    public <T, R> R doSendFoJson(String trackingNo, String url, T requestBody, Class<R> response) {
        long startTime = System.currentTimeMillis();
        ResponseEntity<String> entity = null;
        HttpHeaders headers = this.buildHttpHeader(MediaType.APPLICATION_JSON_UTF8, requestBody, trackingNo);
        HttpEntity<T> httpReq = new HttpEntity<>(requestBody, headers);
        try {
            entity = restTemplate.exchange(url, HttpMethod.POST, httpReq, String.class);
        } catch (Exception e) {
            ErrorLog.errorConvertJson("", "", trackingNo, "", startTime, System.currentTimeMillis(), url, entity, e);
        } finally {
            ThirdPartyLog.infoConvertJson(trackingNo, startTime, System.currentTimeMillis(), BusinessSign.API, url, "", requestBody, entity != null ? entity.getBody() : entity, "", "");
        }
        try {
            return entity != null ? JSONObject.parseObject(entity.getBody(), response) : response.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }


    private <T> MultiValueMap<String, String> buildFormParams(T requestBody) {
        MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<>();
        Map<String, Object> javaBeanMap = CustomBeanUtil.java2Map(requestBody);
        javaBeanMap.forEach((k, v) -> {
            postParameters.add(k, v != null ? String.valueOf(v) : null);
        });
        return postParameters;
    }

    private <T> HttpHeaders buildHttpHeader(MediaType mediaType, T requestBody, String trackingNo) {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = mediaType;
        headers.setContentType(type);
        if (requestBody instanceof HuaLaLaCommonRequest) {
            HuaLaLaCommonRequest body = (HuaLaLaCommonRequest) requestBody;
            headers.add("groupID", body.getGroupID() + "");
            headers.add("shopID", body.getShopID() + "");
            headers.add("traceID", trackingNo);
        }
        return headers;
    }


}

