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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
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.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.InputStreamReader;
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");
            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);
            }

            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 if(response.indexOf("msg")>0){
                JSONObject object = JSON.parseObject(response);
                result.put("code", "400");
                result.put("msg", object.get("msg"));
                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);
            }
        } 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");
        }
    }
}
