package cn.com.poc.thirdparty.resource.demand.dgTools;

import cn.com.poc.common.constant.FmxParamConfigConstant;
import cn.com.poc.common.utils.ListUtils;
import cn.com.poc.common.utils.http.LocalHttpClient;
import cn.com.poc.thirdparty.resource.demand.ai.route.DgtoolsApiRoute;
import cn.com.poc.thirdparty.resource.demand.dgTools.request.AbstractParam;
import cn.com.poc.thirdparty.resource.demand.dgTools.request.AbstractRequest;
import cn.com.poc.thirdparty.resource.demand.dgTools.request.ProjectTokenRequest;
import cn.com.poc.thirdparty.resource.demand.dgTools.result.AbstractResult;
import cn.com.poc.thirdparty.resource.demand.dgTools.result.DgtoolsApiResult;
import cn.com.poc.thirdparty.resource.demand.dgTools.utils.AesEncodeUtil;
import cn.com.yict.framemax.core.exception.BusinessException;
import cn.com.yict.framemax.core.i18n.I18nMessageException;
import cn.com.yict.framemax.data.model.PagingInfo;
import cn.com.yict.framemax.frame.service.FmxParamConfigService;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.StringEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

@Component
public class DgtoolsAbstractHttpClient {

    private static FmxParamConfigService fmxParamConfigService;

    @Value("${dgtools.domain.url}")
    private String dgtoolsDomainurl;

    public static void main(String[] args) {
        ProjectTokenRequest projectTokenParam = new ProjectTokenRequest();
        projectTokenParam.setProjectKey("Y20tEqfwegXTzEeqd3vV");
        projectTokenParam.setProjectSecret("ZGIwZTBkYTczZTE2NDdjNjk0YWQ0MjgwZGI1NDg5OGE=");
        System.out.println(JSON.toJSONString(projectTokenParam));
        String encrypt = AesEncodeUtil.encrypt("K7jWSua03IXe1X3J", "BQrhhRHLRMnF2pABNQl9MPxK", JSON.toJSONString(projectTokenParam));
        System.out.println(encrypt);
    }

    /**
     * setting方式注入静态属性
     *
     * @param fmxParamConfigService
     */
    @Autowired
    public void setFmxParamConfigService(FmxParamConfigService fmxParamConfigService) {
        DgtoolsAbstractHttpClient.fmxParamConfigService = fmxParamConfigService;
    }

    /**
     * 调用中台接口通用请求
     * <br/>注：基于fastjson对JSON数据转换
     *
     * @param url             请求全路径
     * @param abstractRequest 请求实体，需要继承响应体泛型的AbstractRequest
     * @param headers         请求头列表
     */
    public <T extends AbstractResult> T doRequest(String url, AbstractRequest<T> abstractRequest, List<Header> headers) {
        return doRequest(url, abstractRequest, headers, null);
    }

    /**
     * 调用中台接口通用请求
     * <br/>注：基于fastjson对JSON数据转换
     *
     * @param url             请求全路径
     * @param abstractRequest 请求实体，需要继承响应体泛型的AbstractRequest
     * @param headers         请求头列表
     * @param pagingInfo      分页信息
     */
    public <T extends AbstractResult> T doRequest(String url, AbstractRequest<T> abstractRequest, List<Header> headers, PagingInfo pagingInfo) {


        Class<T> responseClass = abstractRequest.getResponseClass();

        Map<String, String> paramConfigMap = getParamConfigMap();

        String privateKey = paramConfigMap.get(FmxParamConfigConstant.Dgtools.PRIVATE_KEY);
        if (StringUtils.isEmpty(privateKey)) {
            throw new I18nMessageException("exception/private.key.of.the.marketing.platform.configuration.project.is.empty");
        }

        String vi = paramConfigMap.get(FmxParamConfigConstant.Dgtools.VI);
        if (StringUtils.isEmpty(vi)) {
            throw new I18nMessageException("exception/decryption.offset.of.the.marketing.platform.configuration.is.empty");
        }

        //生成请求实体
        AbstractParam abstractParam = new AbstractParam();
        System.out.println(JSON.toJSONString(abstractRequest));
        String encrypt = AesEncodeUtil.encrypt(vi, privateKey, JSON.toJSONString(abstractRequest));
        abstractParam.setBusinessEntity(abstractRequest);
        abstractParam.setSign(encrypt);
        abstractParam.setAcctId(abstractRequest.getAcctId());
        abstractParam.setTimestamp(String.valueOf(Calendar.getInstance().getTimeInMillis()));

        String json = JSON.toJSONString(abstractParam);

        RequestBuilder post = RequestBuilder.post();
        //自定义添加header
        if (ListUtils.isNotEmpty(headers)) {
            for (Header header : headers) {
                post.addHeader(header);
            }
        }
        // 配置分页参数
        if (pagingInfo != null) {
            url = url + "?pageSize=" + pagingInfo.getPageSize() + "&pageNo=" + pagingInfo.getPageNo();
        }

        HttpUriRequest httpUriRequest = post
                .setHeader(DgtoolsApiRoute.JSON_HEADER)
                .setUri(dgtoolsDomainurl + DgtoolsApiRoute.BASE_URL + url)
                .setEntity(new StringEntity(json, StandardCharsets.UTF_8))
                .build();
        DgtoolsApiResult dgtoolsApiResult = LocalHttpClient.executeJsonResult(httpUriRequest, DgtoolsApiResult.class);

        if (dgtoolsApiResult == null) {
            throw new I18nMessageException("exception/middle.server.is.unresponsive.or.has.timed.out");
        }

        if (!dgtoolsApiResult.isSuccess()) {
            //调用服务超时 2000毫秒
            throw new BusinessException(dgtoolsApiResult.getMessage());
        }
        if (dgtoolsApiResult.getPagingInfo() != null) {
            pagingInfo.setTotalRows(dgtoolsApiResult.getPagingInfo().getTotalRows());
            pagingInfo.setPageSize(dgtoolsApiResult.getPagingInfo().getPageSize());
        }
        return JSON.parseObject(JSON.toJSONString(dgtoolsApiResult.getData()), responseClass);

    }

    /**
     * 根据前缀获取配置表的数据
     *
     * @return
     */
    private Map<String, String> getParamConfigMap() {
        //获取统一id
        return fmxParamConfigService.getStartsWith(FmxParamConfigConstant.Prefix.DG_TOOLS);
    }

    public <T extends AbstractResult> String buildJson(AbstractRequest<T> abstractRequest) {
        Map<String, String> paramConfigMap = getParamConfigMap();

        String privateKey = paramConfigMap.get(FmxParamConfigConstant.Dgtools.PRIVATE_KEY);
        if (StringUtils.isEmpty(privateKey)) {
            throw new I18nMessageException("exception/private.key.of.the.marketing.platform.configuration.project.is.empty");
        }

        String vi = paramConfigMap.get(FmxParamConfigConstant.Dgtools.VI);
        if (StringUtils.isEmpty(vi)) {
            throw new I18nMessageException("exception/decryption.offset.of.the.marketing.platform.configuration.is.empty");
        }

        //生成请求实体
        AbstractParam abstractParam = new AbstractParam();
        System.out.println(JSON.toJSONString(abstractRequest));
        String encrypt = AesEncodeUtil.encrypt(vi, privateKey, JSON.toJSONString(abstractRequest));
        abstractParam.setBusinessEntity(abstractRequest);
        abstractParam.setSign(encrypt);
        abstractParam.setAcctId(abstractRequest.getAcctId());
        abstractParam.setTimestamp(String.valueOf(Calendar.getInstance().getTimeInMillis()));

        String json = JSON.toJSONString(abstractParam);
        return json;
    }

}
