package com.ms.biz.tool;

import cn.hutool.crypto.SecureUtil;
import com.ms.biz.common.UniqueKeyMultiValueMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Set;

/**
 * 调用分销代理服务（DS）工具模板类
 * 表单形式
 */
@Slf4j
@Component
public class DsFormRequestTemplate {

    @Autowired
    private CloudRequestTemplate cloudRequestTemplate;

    @Value("${jx.ds.host-prod}")
    private String dsHostProd;

    @Value("${jx.ds.host-test}")
    private String dsHostTest;

    @Value("${jx.ds.token-prod}")
    private String dsTokenProd;

    @Value("${jx.ds.token-test}")
    private String dsTokenTest;

    private String dsHost;
    private String dsToken;

    public <T> String execute(String url, T body) throws Exception {
        // 选择环境
        if (StringUtils.isEmpty(dsHost)) {
            if (SystemTool.isProdEnv()) {
                // 当前为生产环境
                dsHost = dsHostProd;
                dsToken = dsTokenProd;
            } else {
                dsHost = dsHostTest;
                dsToken = dsTokenTest;
            }
        }

        // 构建头部
        HttpHeaders headers = new HttpHeaders();
        // 微应用固定传msddMicro
        headers.set("x-app-name", "msddMicro");
        // 业务系统使用表单方式，没用json方式
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        // 表单形式下，只能用MultiValueMap<String,String>
        MultiValueMap<String,String> params = (UniqueKeyMultiValueMap<String,String>)body;
        // 构建签名
        Set<String> keySet = params.keySet();
        String[] keyArray = keySet.toArray(new String[0]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        sb.append(dsToken);
        for (String s : keyArray) {
            sb.append(s).append(params.getFirst(s));
        }
        sb.append(dsToken);
        String sign = SecureUtil.md5(sb.toString());
        headers.set("x-dd-micro-app-sign", sign);

        return cloudRequestTemplate.executePost(dsHost + url, params, headers);
    }

}
