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.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;

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

@Slf4j
public class MkUtil {

    @Value("${mk.appCode}")
    private final static String appCode = "AP52Y01LHHTAP9";

    @Value("${mk.appSecret}")
    private final static String appSecret = "N4WuERLteAUPaWebnsHy";

    private final Object $lock = new Object[0];

    private static final Long EXPIRES_IN = 1800000L;

    public static Map initTokenHeader(){

            Map header = new HashMap();

            String tokenId = UtilToken.get("invalid-tokenId-mk");
            String entCode = UtilToken.get("invalid-entCode-mk");

            if (StringUtils.isNotBlank(tokenId) && StringUtils.isNotBlank(entCode)) {
                header.put("tokenId",tokenId);
                header.put("entCode",entCode);

                return header;
            } else {
                //每刻登录认证
                Map body = new HashMap();

                long timeMillis = System.currentTimeMillis();
                body.put("appCode",appCode);
                body.put("secret",getSecret(appCode,appSecret,timeMillis));
                body.put("timestamp",timeMillis);

                Map result = (Map) JSONObject.parse(UtilHttp.doPost("https://ng.maycur.com/api/openapi/auth/login", null, null, body));

                Map data = UtilMap.getMap(result, "data");

                tokenId = UtilMap.getString(data, "tokenId");
                entCode = UtilMap.getString(data, "entCode");

                log.info("每刻tokenId, {}", tokenId);
                log.info("每刻entCode, {}", entCode);

                UtilToken.put("invalid-tokenId-mk", tokenId, EXPIRES_IN);
                UtilToken.put("invalid-entCode-mk", entCode, EXPIRES_IN);

                header.put("tokenId",tokenId);
                header.put("entCode",entCode);

                return header;
            }

    }

    private static String getSecret(String appCode, String appSecret, long timeMillis){
        log.info("time：{}",timeMillis);

        String s = DigestUtils.sha256Hex(appSecret + ":" + appCode + ":" + timeMillis);
        log.info("s:{}",s);

        return s;
    }


}
