package com.kingdee.eas.custom.sso;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kingdee.shr.api.Response;
import com.kingdee.shr.api.SHRClient;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.http.HttpException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @Description 批量审批单点类
 * @Date 2024/10/30 11:22
 * @Created by Heyuan
 */
public class BatchApprove extends HttpServlet {
    private static Logger logger = Logger.getLogger(BatchApprove.class);
    private Properties prop = new Properties();
    private String propPath = System.getProperty("EAS_HOME") + "/server/properties/scy/OASSOConfig.properties";
    //osf服务名称
    private final String SERVICENAME = "batchApproveEx";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        logger.error("BatchApprove -> doGet");
        //doPost(req, resp);
        BufferedReader streamReader = null;
        String resultStr = null;
        prop.load(new FileInputStream(propPath));
        Map result = new HashMap();
        StringBuilder errorMsg = new StringBuilder();
        String loginId = null;
        //处理跨域问题
        String origin = req.getHeader("Origin");
        String method = req.getMethod();
        System.out.println("method " + method);
        logger.error("origin " + origin);
        if (StringUtils.isBlank(origin)) {
            resp.addHeader("Access-Control-Allow-Origin", "*");

        } else {
            resp.addHeader("Access-Control-Allow-Origin", origin);
        }
        resp.addHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
        resp.addHeader("Access-Control-Allow-Headers", "Content-Type");
        try {
            loginId = req.getParameter("loginId");
            if (StringUtils.isBlank(loginId)) {
                errorMsg.append("账号不能为空!\n");
            }
            logger.error("BatchApprove ->loginId " + loginId);
            String serverName = prop.getProperty("serverName");
            if (StringUtils.isBlank(serverName)) {
                errorMsg.append("shr地址为空，请检查配置文件： " + propPath + "\n");
            }
            //shr测试服务地址
            String shrAddr = serverName + "/shr";
            String assignmentIds = req.getParameter("assignmentIds");
            if (StringUtils.isNotBlank(assignmentIds)) {
                assignmentIds = URLEncoder.encode(assignmentIds, "utf-8");
            } else {
                errorMsg.append("工作流任务id不能为空!\n");
            }
            String opinion = req.getParameter("opinion");
            if (StringUtils.isNotBlank(opinion)) {
                opinion = URLEncoder.encode(opinion, "utf-8");
            } else {
                errorMsg.append("审批意见不能为空!\n");
            }
            if (errorMsg.length() > 0) {
                throw new Exception(errorMsg.toString());
            }
            //接口调用者工号,跟OA账号一致(审批流程时会判断调用者是否为流程审批人)
            Map<String, Object> param = new HashMap();
            param.put("assignmentIds", assignmentIds);
            param.put("opinion", opinion);
            SHRClient shrClient = new SHRClient();
            Response response = shrClient.executeServiceByName(shrAddr, SERVICENAME, param, loginId);
            logger.error(response.getData());
            result.put("data", JSONObject.parseArray(response.getData().toString()));
            result.put("success", true);
            result.put("message", "执行成功");
            resp.setStatus(200);
        } catch (Exception e) {
            e.printStackTrace();
            resp.setStatus(500);
            String error = e.getMessage();
            result.put("data", "");
            result.put("success", false);
            if (e instanceof HttpException && error.contains("login shr fail")) {
                result.put("message", "账号不存在 " + loginId);
            } else {
                result.put("message", error);
            }
        } finally {
            resultStr = JSON.toJSONString(result);
            try {
                if (streamReader != null) {
                    streamReader.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        PrintWriter writer = resp.getWriter();
        resp.setContentType("application/json");
        writer.write(resultStr);
        writer.close();
    }

    @Override
    protected void doOptions(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String origin = request.getHeader("Origin");
        String method = request.getMethod();
        System.out.println("method " + method);
        logger.error("origin " + origin);
        if (StringUtils.isBlank(origin)) {
            response.setHeader("Access-Control-Allow-Origin", "*");
        } else {
            response.setHeader("Access-Control-Allow-Origin", origin);
        }
        // 设置跨域相关的响应头
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type");
        response.setHeader("Access-Control-Max-Age", "3600"); // 缓存时间（秒）
        response.setStatus(HttpServletResponse.SC_OK); // 返回 200 状态码
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        logger.error("BatchApprove -> doPost");
        BufferedReader streamReader = null;
        String resultStr = null;
        prop.load(new FileInputStream(propPath));
        Map result = new HashMap();
        StringBuilder errorMsg = new StringBuilder();
        String loginId = null;
        //处理跨域问题
        String origin = req.getHeader("Origin");
        String method = req.getMethod();
        System.out.println("method " + method);
        logger.error("origin " + origin);
        if (StringUtils.isBlank(origin)) {
            resp.addHeader("Access-Control-Allow-Origin", "*");

        } else {
            resp.addHeader("Access-Control-Allow-Origin", origin);
        }
        resp.addHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
        resp.addHeader("Access-Control-Allow-Headers", "Content-Type");
        try {
            //接收json数据
            streamReader = new BufferedReader(new InputStreamReader(req.getInputStream(), "UTF-8"));
            StringBuilder responseStrBuilder = new StringBuilder();
            String inputStr;
            while ((inputStr = streamReader.readLine()) != null) {
                responseStrBuilder.append(inputStr);
            }
            String dataStr = responseStrBuilder.toString();
            logger.error("dataStr: " + dataStr);
            if (StringUtils.isBlank(dataStr)) {
                throw new Exception("参数不能为空!");
            }
            JSONObject params = JSON.parseObject(dataStr);
            loginId = params.getString("loginId");
            if (StringUtils.isBlank(loginId)) {
                errorMsg.append("账号不能为空!\n");
            }
            logger.error("BatchApprove ->loginId " + loginId);
            String serverName = prop.getProperty("serverName");
            if (StringUtils.isBlank(serverName)) {
                errorMsg.append("shr地址为空，请检查配置文件： " + propPath + "\n");
            }
            //shr测试服务地址
            String shrAddr = serverName + "/shr";
            String assignmentIds = params.getString("assignmentIds");
            if (StringUtils.isNotBlank(assignmentIds)) {
                assignmentIds = URLEncoder.encode(assignmentIds, "utf-8");
            } else {
                errorMsg.append("工作流任务id不能为空!\n");
            }
            String opinion = params.getString("opinion");
            if (StringUtils.isNotBlank(opinion)) {
                opinion = URLEncoder.encode(opinion, "utf-8");
            } else {
                errorMsg.append("审批意见不能为空!\n");
            }
            if (errorMsg.length() > 0) {
                throw new Exception(errorMsg.toString());
            }
            //接口调用者工号,跟OA账号一致(审批流程时会判断调用者是否为流程审批人)
            Map<String, Object> param = new HashMap();
            param.put("assignmentIds", assignmentIds);
            param.put("opinion", opinion);
            SHRClient shrClient = new SHRClient();
            Response response = shrClient.executeServiceByName(shrAddr, SERVICENAME, param, loginId);
            logger.error(response.getData());
            result.put("data", JSONObject.parseArray(response.getData().toString()));
            result.put("success", true);
            result.put("message", "执行成功");
            resp.setStatus(200);
        } catch (Exception e) {
            e.printStackTrace();
            resp.setStatus(500);
            String error = e.getMessage();
            result.put("data", "");
            result.put("success", false);
            if (e instanceof HttpException && error.contains("login shr fail")) {
                result.put("message", "账号不存在 " + loginId);
            } else {
                result.put("message", error);
            }
        } finally {
            resultStr = JSON.toJSONString(result);
            try {
                if (streamReader != null) {
                    streamReader.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        PrintWriter writer = resp.getWriter();
        resp.setContentType("application/json");
        writer.write(resultStr);
        writer.close();
    }
}
