package com.unis.crk.utils;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class ddmPostCall {


    public JSONObject callDmm(String url, Map<String, String> srt){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("success", false);
        Map<String, String> headerParams=new HashMap<>();
 /*
        参数名	    参数类型	是否必填	参数描述
        accessKeyId	string	是       ipaas分配的秘钥
        sign		string	是       根据秘钥计算的签名
        timestamp	string	是       日期时间:YYYYMMDDHHMMSS
        userId		string	是       操作人*/
        HttpHeaders headers = new HttpHeaders();
        String timestamp = Calendar.getInstance().getTimeInMillis() + "";
        headers.add("accessKeyId", srt.get("accessKeyId"));
        String s=srt.get("accessKeyId")+srt.get("accessKeySecret")+timestamp;
        headers.add("sign",  md5(s));
        headers.add("userId", srt.get("userId"));
        headers.add("timestamp", timestamp);
        Map<String, Object> body=new HashMap<>();
        body.put("$pageNum",1);
        body.put("$pageSize",2000);
        body.put("modifiedTime",srt.get("modifiedTime"));
        body.put("$scopeField",srt.get("field_name"));
        System.out.println("body:"+body.toString());
        System.out.println("headers:"+headers.toString());
        RestTemplate restTemplate = new RestTemplate();

        HttpEntity httpEntity = new HttpEntity(body, headers);
        ResponseEntity<String> entity = null;
        try {
            entity = restTemplate.postForEntity(url, httpEntity, String.class);
        } catch (HttpClientErrorException e) {
            throw new RuntimeException("连接错误，请检查地址或者网络或系统参数");
        }

        jsonObject.put("entity",entity);

        return jsonObject;
    }

    private static  String md5(String plainText) {
        Object var2 = null;

        byte[] secretBytes;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            secretBytes = md.digest();
        } catch (NoSuchAlgorithmException var6) {
            throw new RuntimeException("没有md5这个算法！");
        }

        String md5code = (new BigInteger(1, secretBytes)).toString(16);
        int length = md5code.length();

        for(int i = 0; i < 32 - length; ++i) {
            md5code = "0" + md5code;
        }

        return md5code;
    }


}
