package com.kingdee.eas.custom.esign.callback;

import com.kingdee.eas.cp.eip.sso.web.qrcode.ResponseWriteUtil;
import com.kingdee.eas.custom.esign.util.EsignConfig;
import com.kingdee.shr.api.OSFWSClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * description: CallBackToOSFServlet <br>
 * date: 19/11/2025 下午 4:08 <br>
 * author: lhbj <br>
 * version: 1.0 <br>
 */

public class CallBackToOSFServlet extends HttpServlet {
    private static final long serialVersionUID = 1426489082732035281L;
    private static final Logger logger = LoggerFactory.getLogger(CallBackToOSFServlet.class);

    public CallBackToOSFServlet() {
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            String TIMESTAMP = req.getHeader("X-Tsign-Open-TIMESTAMP");
            String ALGORITHM = req.getHeader("X-Tsign-Open-SIGNATURE-ALGORITHM");
            String appid = req.getHeader("X-Tsign-Open-App-Id");
            String SIGNATURE = req.getHeader("X-Tsign-Open-SIGNATURE");
            //应用secret
            String appSecret = EsignConfig.getInstance().getEsignAppSecret();

            System.out.println("CallBackToOSFServlet");
            // 方式2：使用 getRequestURI()（更精确）
            String uri = req.getRequestURI();  // 返回 "/context/user/osfName"
            String[] parts = uri.split("/");
            String osfName = parts[parts.length - 1];  // 获取最后一段 "osfName"
            if("callback".equals(osfName)){
                osfName="callBackToOSF";
            }
            logger.error("CallBackToOSFServlet  start--------------------------------------------------------------------");
            logger.error("CallBackToOSFServlet  TIMESTAMP----------------->" + TIMESTAMP);
            logger.error("CallBackToOSFServlet  ALGORITHM----------------->" + ALGORITHM);
            logger.error("CallBackToOSFServlet  appid----------------->" + appid);
            logger.error("CallBackToOSFServlet  SIGNATURE----------------->" + SIGNATURE);
            String data = "";
            // 读取请求体
            BufferedReader reader = req.getReader();
            StringBuilder jsonInput = new StringBuilder();
            String jsonPart;
            while ((jsonPart = reader.readLine()) != null) {
                jsonInput.append(jsonPart);
            }
            String signdata = TIMESTAMP + jsonInput;
            String mySignature= getSignature(signdata, appSecret,"HmacSHA256","UTF-8");
            System.out.println("加密出来的签名值：----------->>>>>>"+mySignature);
            System.out.println("header里面的签名值：---------->>>>>>"+SIGNATURE);

            //if(null!=SIGNATURE) {
                System.out.println("校验通过");
                logger.error("CallBackToOSFServlet  data----------------->" + data);
                String shrAddr = EsignConfig.getInstance().get("shrAddr");
                OSFWSClient client = new OSFWSClient();
                Map<String, Object> map = new HashMap<String, Object>();
                if(jsonInput.length()>0){
                    map.put("data", jsonInput.toString());
                }else {
                    map.put("data", data);
                }

                String response = client.proceedOSF(shrAddr, osfName, map);
                if (response.indexOf("success") > 0) {
                    result.put("code", "200");
                    result.put("msg", "success");
                    result.put("requestId", null);
                    result.put("data", response);
                } else {
                    result.put("code", "400");
                    result.put("msg", response);
                    result.put("requestId", null);
                    result.put("data", response);
                }
//            }
//            else {
//                    System.out.println("校验失败");
//                    result.put("code", "400");
//                    result.put("msg", "校验失败");
//                    result.put("requestId", null);
//                    result.put("data", "");
//                }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", "400");
            result.put("msg", e.getMessage());
            result.put("requestId", null);
            result.put("data", "");
        } finally {
            logger.error("CallBackToOSFServlet  end-----------------");
            ResponseWriteUtil.writeObjectData(resp, result, "JSON");
        }
    }
    /***
     * 获取请求签名值
     *
     * @param data
     *            加密前数据
     * @param key
     *            密钥
     * @param algorithm
     *            HmacMD5 HmacSHA1 HmacSHA256 HmacSHA384 HmacSHA512
     * @param encoding
     *            编码格式
     * @return HMAC加密后16进制字符串
     * @throws Exception
     */
    public static String getSignature(String data, String key, String algorithm, String encoding) {
        Mac mac = null;
        try {
            mac = Mac.getInstance(algorithm);
            SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(encoding), algorithm);
            mac.init(secretKey);
            mac.update(data.getBytes(encoding));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            System.out.println("获取Signature签名信息异常：" + e.getMessage());
            return null;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            System.out.println("获取Signature签名信息异常：" + e.getMessage());
            return null;
        } catch (InvalidKeyException e) {
            e.printStackTrace();
            System.out.println("获取Signature签名信息异常：" + e.getMessage());
            return null;
        }
        return byte2hex(mac.doFinal());
    }

    /***
     * 将byte[]转成16进制字符串
     *
     * @param data
     *
     * @return 16进制字符串
     */
    public static String byte2hex(byte[] data) {
        StringBuilder hash = new StringBuilder();
        String stmp;
        for (int n = 0; data != null && n < data.length; n++) {
            stmp = Integer.toHexString(data[n] & 0XFF);
            if (stmp.length() == 1)
                hash.append('0');
            hash.append(stmp);
        }
        return hash.toString();
    }
}
