package com.ms.biz.tool;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
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.StringUtils;

import java.util.*;

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

    @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 String execute(String url, Map<String, Object> body) throws Exception {
        // 选择环境
        if (StringUtils.isEmpty(dsHost)) {
            if (SystemTool.isProdEnv()) {
                // 当前为生产环境
                dsHost = dsHostProd;
                dsToken = dsTokenProd;
            } else {
                dsHost = dsHostProd;
                dsToken = dsTokenProd;
            }
        }
        System.out.println(dsHost + url);

        // 构建头部
        HttpHeaders headers = new HttpHeaders();
        // 微应用固定传msddMicro
        headers.set("x-app-name", "msddMicro");
        // 使用json方式更符合外部服务管理
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HashMap<String,Object> params = (HashMap<String,Object>)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) {
            if (!Objects.isNull(params.get(s))) {
                String value = JSON.toJSONString(params.get(s), SerializerFeature.MapSortField);
                value = CommonTool.removeQuotes(value);
                sb.append(s).append(value);
            }
        }
        sb.append(dsToken);
        log.info("row str:" + sb);
        String sign = SecureUtil.md5(sb.toString());
        log.info("sign str:" + sign);
        headers.set("x-dd-micro-app-sign", sign);
        log.info("body str:" + JSON.toJSONString(params, SerializerFeature.MapSortField));
        return cloudRequestTemplate.executePost(dsHost + url, JSON.toJSONString(params, SerializerFeature.MapSortField), headers);
    }

}
