package nckd.jimin.jyyy.bd.common.oauth;

import com.alibaba.fastjson.JSONObject;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dc.api.model.Account;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.login.thirdauth.app.AppAuthResult;
import kd.bos.login.thirdauth.app.ThirdAppAuthtication;
import kd.bos.login.thirdauth.app.UserType;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.sdk.util.KHttpClientUtils;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import nckd.base.helper.CommonHelperUtils;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 泛微OA：E10单点登录拦截，验证token用户
 * @author wanghaiwu_kd
 * @date 2025/04/16
 */
public class FanWeiSSOAuthtication extends ThirdAppAuthtication {
    private static Log logger = LogFactory.getLog(FanWeiSSOAuthtication.class);
    /**
     * 判断该接口请求是否需要通过此插件认证
     */
    @Override
    public boolean isNeedHandle(HttpServletRequest request, Account account) {
        //加密的数据信息
        String token = request.getParameter("eteams_token");
        if(StringUtils.isNotBlank(token)){
            return true;
        }
        return false;
    }

    /**
     *用户身份解析
     */
    @Override
    public AppAuthResult appAuthtication(HttpServletRequest request, Account account) {
        AppAuthResult result = new AppAuthResult();
        result.setSucceed(false);
        try{
            //获取请求连接中的token
            String token = request.getParameter("eteams_token");
            if(StringUtils.isBlank(token)){
                logger.info("FanWeiSSOAuthtication：eteams_token is null");

                result.setErrorMessage("FanWeiSSOAuthtication：eteams_token is null");
                return result;
            }

            String selectField = "nckd_entryentity.nckd_key, nckd_entryentity.nckd_value";

            QFilter qFilter = new QFilter("number", QCP.equals, "fanwei");
            DynamicObject commonParam = BusinessDataServiceHelper.loadSingle("nckd_commonparams", selectField, qFilter.toArray());
            if (ObjectUtils.isEmpty(commonParam)) {
                logger.info("FanWeiSSOAuthtication：nckd_commonparams is null");

                result.setErrorMessage("FanWeiSSOAuthtication：未配置泛微相关参数nckd_commonparams");
                return result;
            }

            DynamicObjectCollection entryentity = commonParam.getDynamicObjectCollection("nckd_entryentity");
            Map<String, String> mapentity = entryentity.stream().collect(Collectors.toMap(k -> k.getString("nckd_key"), v -> v.getString("nckd_value")));

            if(mapentity == null ){
                logger.info("FanWeiSSOAuthtication：nckd_entryentity is null");

                result.setErrorMessage("FanWeiSSOAuthtication：未配置泛微相关参数");
                return result;
            }

            String userUrl = mapentity.get("getuserinfo");
            if(StringUtils.isEmpty(userUrl)){
                logger.info("FanWeiSSOAuthtication：getuserinfo is null");

                result.setErrorMessage("FanWeiSSOAuthtication：未配置泛微相关参数getuserinfo");
                return result;
            }

            String privateKey = mapentity.get("privatekey");
            if(StringUtils.isEmpty(privateKey)){
                logger.info("FanWeiSSOAuthtication：privatekey is null");

                result.setErrorMessage("FanWeiSSOAuthtication：未配置泛微相关参数privatekey");
                return result;
            }

            String syscode = mapentity.get("syscode");
            if(StringUtils.isEmpty(syscode)){
                logger.info("FanWeiSSOAuthtication：syscode is null");

                result.setErrorMessage("FanWeiSSOAuthtication：未配置泛微相关参数syscode");
                return result;
            }

            String isDecode = mapentity.get("isdecode");

            String ssouser_dev = mapentity.get("ssouser_dev");
            String user = "";

            String apiResult = "";

            Map<String, String> header = new HashMap<>();
            header.put("Content-Type", "application/json; charset=UTF-8");

            //获取token
            try {
                userUrl = userUrl + "?eteam_token=" + token + "&xybs=" + syscode;

                logger.info("获取泛微用户url：" + userUrl);
                String bodyString = CommonHelperUtils.buildEsbApiBodyJSON(null);

                apiResult = KHttpClientUtils.postjson(userUrl, header, bodyString);
            } catch (IOException e) {
                logger.info(e.getMessage());

                logger.info("FanWeiSSOAuthtication：getuserinfo fail");

                result.setErrorMessage("FanWeiSSOAuthtication：获取用户异常" + e.getMessage());
                return result;
            }

            if(kd.bos.util.StringUtils.isEmpty(apiResult)){
                logger.info("FanWeiSSOAuthtication：getuserinfo fail");

                result.setErrorMessage("FanWeiSSOAuthtication：获取用户异常");
                return result;
            }

            logger.info("FanWeiSSOAuthtication token url：" + apiResult);

            String userJSONString = "";
            if(isDecode != null && "true".equals(isDecode)) {
                userJSONString = new String(FanWeiRSAUtils.decryptByKey(FanWeiRSAUtils.getPrivateKey(Base64.decodeBase64(privateKey))
                        , Base64.decodeBase64(apiResult.getBytes("UTF-8"))));
            }

            logger.info("FanWeiSSOAuthtication user：" + userJSONString);

            userJSONString = userJSONString.substring(1, userJSONString.length() - 1).replace("\\", "");

            logger.info("FanWeiSSOAuthtication user replace：" + userJSONString);

            JSONObject userInfo = JSONObject.parseObject(userJSONString);
            if(userInfo.get("jobNum") == null){
                logger.info("FanWeiSSOAuthtication：getuserinfo fail");

                result.setErrorMessage("FanWeiSSOAuthtication：获取用户异常");
                return result;
            }

            user = userInfo.getString("jobNum");

            if(StringUtils.isNotEmpty(ssouser_dev)){
                user = ssouser_dev;

            }
            result.setUserFlag(user);
            result.setUserType(UserType.USER_NAME);
            result.setSucceed(true);
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }
}