package com.weaver.seconddev.chapanda.esign.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.weaver.seconddev.chapanda.esign.constant.Constants;
import okhttp3.*;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Component
public class Esb2EsignSyncSealsUtil {
    private final static Logger log = LoggerFactory.getLogger(Esb2EsignSyncSealsUtil.class);

    public String queryEsignSealTemplate(String querySealsUrl){
        String bodyData = "";
        String xTimevaleSignature = encryptionHmacSHA256(bodyData);
        log.error("xTimevaleSignature:"+xTimevaleSignature);
        String msg = doGetEsignQuerySeals(xTimevaleSignature,querySealsUrl);
        log.error("msg:"+msg);
        return msg;
    }

    public JSONArray querySealsArray(String msg,String organizeNo){
        JSONArray ebArray = new JSONArray();
        log.error("msg:"+msg);
        if(StringUtils.isNotBlank(msg)){
            JSONObject msgJson = JSONObject.parseObject(msg);
            if(msgJson.containsKey("errCode")){
                String errCode = msgJson.getString("errCode");
                if("0".equals(errCode)){
                    if(msgJson.containsKey("data")){
                        JSONObject dataJson = msgJson.getJSONObject("data");
                        if(dataJson.containsKey("seals")){
                            JSONArray sealsArray = dataJson.getJSONArray("seals");
                            for (int i = 0; i < sealsArray.size(); i++) {
                                JSONObject sealJson = sealsArray.getJSONObject(i);
                                String sealType = sealJson.getString("sealType");
                                String status = sealJson.getString("status");
                                String sealid = sealJson.getString("sealId");
                                String alias = sealJson.getString("alias");

                                log.error("sealType:{}",sealType);
                                if("1".equals(sealType) || "3".equals(sealType)){

                                    JSONObject ebJson = new JSONObject();
                                    ebJson.put("yzzl","0");
                                    ebJson.put("sealid",sealid);
                                    ebJson.put("orgno",organizeNo);
                                    ebJson.put("sealname",alias);
                                    ebJson.put("sealstatus",status);
                                    ebJson.put("sealtype",sealType);
                                    ebJson.put("sealno",sealid);

                                    ebArray.add(ebJson);
                                }
                            }
                        }
                    }
                }
            }
        }
        return ebArray;
    }

    /***
     *
     * @param xTimevaleSignature
     * @return
     */
    public String doGetEsignQuerySeals(String xTimevaleSignature,String querySealsUrl){
        String bodyData = "";
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        try {
            Request request = new Request.Builder()
                    .url(Constants.eSignHost+querySealsUrl)
                    .method("GET", null)
                    .addHeader("x-timevale-project-id", Constants.xTimevaleProjectId)
                    .addHeader("x-timevale-signature", xTimevaleSignature)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            int code = response.code();
            bodyData =  response.body().string();
            log.error("code:{}",code);
            log.error("bodyData:{}",bodyData);
        } catch (IOException e) {
            log.error("e:"+e.getMessage());
            throw new RuntimeException(e);
        }
        return bodyData;
    }

    /**
     *
     * @param bodyData
     * @param xTimevaleSignature
     * @return
     */
    public String doPostEsignSealsTemplate(String bodyData,String xTimevaleSignature){
        String msg = "";
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, bodyData);
        try {
            Request request = new Request.Builder()
                    .url(Constants.eSignHost+Constants.queryTemplateUrl)
                    .method("POST", body)
                    .addHeader("x-timevale-project-id", Constants.xTimevaleProjectId)
                    .addHeader("x-timevale-signature", xTimevaleSignature)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            int code = response.code();
            log.error("code:"+code);
            if(code == 200){
                msg = response.body().string();
            }
            log.error("msg:"+msg);
        } catch (IOException e) {
            log.error("e:"+e.getMessage());
            throw new RuntimeException(e);
        }
        return msg;
    }


    /***
     *
     * @param bodyData
     * @return
     */
    public String encryptionHmacSHA256(String bodyData){
        String encryptionData = "";
//        String secretKey = "7f067a08f5c675137e6e72aa298e2c07";
        // 要签名的数据
//        JSONObject dataObject = new JSONObject();
//        dataObject.put("templateId","JMHT-ZXSJ");
//        String data = "{\"templateId\":\"JMHT-ZXSJ\"}" ;
        try {
            // 初始化Mac对象
            Mac sha256Hmac = Mac.getInstance("HmacSHA256");
            SecretKeySpec secretKeySpec = new SecretKeySpec(Constants.secretKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
            sha256Hmac.init(secretKeySpec);
            byte[] result = sha256Hmac.doFinal(bodyData.getBytes(StandardCharsets.UTF_8));
            encryptionData = Hex.encodeHexString(result);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        }
        return encryptionData;
    }



}
