package com.malk.siku.utils;

import com.alibaba.fastjson.JSONObject;
import com.malk.utils.UtilHttp;
import com.malk.utils.UtilMap;
import com.malk.utils.UtilToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * 企业滴滴
 */
@Slf4j
public class QyddUtil {
    private static String client_id = "3295ee5021a0dd6436d18f56e7c761c6";
    private static String client_secret = "fe5539d17722035cba70a2e6220c43a4";
    private static String phone = "18857526310";
    private static String signKey = "038bD3BAb4a25D84dc96";
    private static String grant_type = "client_credentials";
    private static String company_id = "1125994055637379";
    private static String host = "api.es.xiaojukeji.com";

    private static final Long EXPIRES_IN = 1800000L;

    public static String getToken(){
        String accessToken = "";

        String token = UtilToken.get("invalid-token-qydd");

        if (StringUtils.isNotBlank(token)) {
            accessToken = token;
        } else {
            //企业滴授权认证
            long timeMillis = System.currentTimeMillis();

            Map<String, Object> body = new HashMap<>();
            body.put("client_id", client_id);
            body.put("client_secret", client_secret);
            body.put("grant_type", grant_type);
            body.put("phone", phone);
            body.put("timestamp", timeMillis);

            String sign = genSign(body, signKey, 0);

            System.out.println("sign:"+sign);
            System.out.println("timestamp:" + timeMillis);

            body.put("sign", sign);
            Map result = (Map) JSONObject.parse(UtilHttp.doPost("https://" + host + "/river/Auth/authorize", null, null, body));

            log.info("result:{}",result);

            accessToken = UtilMap.getString(result, "access_token");

            UtilToken.put("invalid-token-qydd", accessToken, EXPIRES_IN);
        }

        return accessToken;
    }

    public static Map BudgetCenterAdd(Map body){
        body.put("client_id",client_id);
        body.put("company_id",company_id);
        body.put("access_token",getToken());
        body.put("timestamp",System.currentTimeMillis()/1000);
        String sign = genSign(body, signKey, 0);
        body.put("sign",sign);
        String s = UtilHttp.doPost("https://" + host + "/river/BudgetCenter/add", null, null, body);

        log.info("result:{}",s);

        Map result = (Map)JSONObject.parse(s);

        return result;
    }

    public static Map BudgetCenterEdit(Map body){
        body.put("client_id",client_id);
        body.put("company_id",company_id);
        body.put("access_token",getToken());
        body.put("timestamp",System.currentTimeMillis()/1000);
        String sign = genSign(body, signKey, 0);
        body.put("sign",sign);
        String s = UtilHttp.doPost("https://" + host + "/river/BudgetCenter/edit", null, null, body);

        log.info("result:{}",s);

        Map result = (Map)JSONObject.parse(s);

        return result;
    }

    //java md5算法
    public static String md5(String plainText) {
        byte[] secretBytes = null;
        try {
            MessageDigest md  = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes("utf-8"));
            secretBytes = md.digest();
        }
        catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("no such algorithm！");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }


        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;
    }
    //java sha256算法
    public static String sha256Hex(String input) {
        try {
            // 创建一个MessageDigest实例，并指定使用SHA-256算法
            MessageDigest digest = MessageDigest.getInstance("SHA-256");

            // 将输入字符串转换为字节数组，并更新摘要
            byte[] hash = digest.digest(input.getBytes(StandardCharsets.UTF_8));

            // 将字节数组转换为十六进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }

            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static String genSign(Map<String, Object> params, String signKey, Integer signMethod) {
        params.put("sign_key", signKey);
        String result = "";
        try {
            List<Map.Entry<String, Object>> infoIds = new ArrayList<Map.Entry<String, Object>>(params.entrySet());
            Collections.sort(infoIds, new Comparator<Map.Entry<String, Object>>() {
                public int compare(Map.Entry<String, Object> o1, Map.Entry<String, Object> o2) {
                    return (o1.getKey()).compareTo(o2.getKey());
                }
            });
            // 构造签名键值对的格式
            for (Map.Entry<String, Object> item : infoIds) {
                if (item.getKey() != null || item.getKey() != "") {
                    String key = item.getKey();
                    String val = (item.getValue()+"").trim();
                    if (result == "") {
                        result += key + "=" + val;
                    } else {
                        result += "&" + key + "=" + val;
                    }
                }
            }
            //System.out.println(result);
        } catch(Exception e) {
            throw new RuntimeException("error");
        }
        if(signMethod == 1) {
            return sha256Hex(result);
        }
        return md5(result);
    }


}
