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 com.weaver.seconddev.chapanda.esign.entity.OkHttpDto;
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 Esb2EsignDownlUrlUtil {
    private final static Logger log = LoggerFactory.getLogger(Esb2EsignDownlUrlUtil.class);

    public OkHttpDto queryDownlUrl(String signFlowId){
//        String downloadUrl = "";
        String bodyData = "";
        String xTimevaleSignature = encryptionHmacSHA256(bodyData);
        log.error("xTimevaleSignature:"+xTimevaleSignature);
        OkHttpDto okHttpDto  = doHttpPost(xTimevaleSignature,signFlowId);
//        if(StringUtils.isNotBlank(msg)){
//            downloadUrl = convertData(msg);
//        }
        return okHttpDto;
    }

    /**
     *
     * @param xTimevaleSignature
     * @param signFlowId
     * @return
     */
    private OkHttpDto doHttpPost(String xTimevaleSignature,String signFlowId){

        OkHttpDto okHttpDto = new OkHttpDto();
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        // $8d83de01-eac1-4057-8857-a052d8a7fa18$2199386656
        try {
            log.error("fileUrl:{}",Constants.eSignHost+Constants.getSignFlowDocUrls+"?signFlowId="+signFlowId);
            Request request = new Request.Builder()
                    .url(Constants.eSignHost+Constants.getSignFlowDocUrls+"?signFlowId="+signFlowId+"&intranetFlag=N")
                    .method("GET", null)
                    .addHeader("x-timevale-project-id", Constants.xTimevaleProjectId)
                    .addHeader("x-timevale-signature", xTimevaleSignature)
                    .build();
            Response response = client.newCall(request).execute();
            int code = response.code();
            String msg = response.body().string();
            log.error("code:{}",code);
            log.error("msg:{}",msg);
            okHttpDto.setResponseCode(code);
            okHttpDto.setResponseBody(msg);
            convertData(msg,okHttpDto);
        } catch (IOException e) {
            log.error("e:"+e.getMessage());
            throw new RuntimeException(e);
        }
        return okHttpDto;
    }

    /***
     *
     * @param bodyData
     * @return
     */
    private 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;
    }


//    public JSONArray appendSignersParty(String employeeMobile,String templateId,String sealId,String docFilekey,String creditCode,String qsrJobNum){
//        JSONArray signers = new JSONArray();
//        JSONObject detailJson = esb2EsignTemplateSealPostionUtil.getTemplateFormData(templateId,sealId,docFilekey);
//        JSONObject partyA = detailJson.getJSONObject("partyA");
//        JSONObject partyB = detailJson.getJSONObject("partyB");
//        JSONObject partyBJson = new JSONObject();
//        partyBJson.put("authorizationOrganizeNo","");
//        partyBJson.put("uniqueId",employeeMobile);
//        partyBJson.put("accountType",Constants.partyBaccountType);
//        partyBJson.put("autoSign",Constants.autoSign);
//        partyBJson.put("signDocDetails",partyB);
//        partyBJson.put("signOrder","1");
//
//        JSONObject partyAJson = new JSONObject();
//        partyAJson.put("authorizationOrganizeNo",creditCode);
//        partyAJson.put("uniqueId",qsrJobNum);
//        partyAJson.put("accountType",Constants.partyAaccountType);
//        partyAJson.put("autoSign",Constants.autoSign);
//        partyAJson.put("signDocDetails",partyA);
//        partyAJson.put("signOrder","2");
//
//        signers.add(partyBJson);
//        signers.add(partyAJson);
//        return signers;
//    }


    private void convertData(String reposponseBody,OkHttpDto okHttpDto){
        JSONObject bodyJson = JSONObject.parseObject(reposponseBody);
        int errCode = -100;
        if(bodyJson.containsKey("errCode")){
            errCode = bodyJson.getInteger("errCode");
            log.error("errCode:{}",errCode);
        }
        okHttpDto.setDataCode(errCode);
        String msg = "";
        if(bodyJson.containsKey("msg")){
            msg = bodyJson.getString("msg");
            log.error("msg:{}",msg);
        }
        okHttpDto.setDataMsg(msg);
        if(errCode == 0){
            JSONObject responseDataJson = new JSONObject();
            if(bodyJson.containsKey("data")){
                JSONObject dataJson = bodyJson.getJSONObject("data");

                if(dataJson.containsKey("status")){
                    String status = dataJson.getString("status");
                    if("2".equals(status)){
                        if(dataJson.containsKey("signDocUrlList")){
                            String signDocUrlListStr = dataJson.getString("signDocUrlList");
                            if(!"[]".equals(signDocUrlListStr)){
                                JSONArray signDocUrlList = dataJson.getJSONArray("signDocUrlList");
                                if(signDocUrlList.size() > 0){
                                    JSONObject signDocUrlJson = signDocUrlList.getJSONObject(0);
                                    String downloadDocUrl = "";
                                    if(signDocUrlJson.containsKey("downloadDocUrl")){
                                        downloadDocUrl = signDocUrlJson.getString("downloadDocUrl");
                                    }

                                    String docFileKey = "";
                                    if(signDocUrlJson.containsKey("docFileKey")){
                                        docFileKey = signDocUrlJson.getString("docFileKey");
                                    }

                                    String docName = "";
                                    if(signDocUrlJson.containsKey("docName")){
                                        docName = signDocUrlJson.getString("docName");
                                    }

                                    String docId = "";
                                    if(signDocUrlJson.containsKey("docId")){
                                        docId = signDocUrlJson.getString("docId");
                                    }

                                    responseDataJson.put("downloadDocUrl",downloadDocUrl);
                                    responseDataJson.put("docFileKey",docFileKey);
                                    responseDataJson.put("docName",docName);
                                    responseDataJson.put("docId",docId);
                                }
                            }
                        }
                    }else{
                        okHttpDto.setDataCode(500);
                        okHttpDto.setDataMsg("未签署完成");
                    }
                }
            }
            okHttpDto.setDataJson(responseDataJson);
        }
    }
}
