package com.kingdee.eas.custom.shrToOA;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.bsf.service.app.IHRMsfService;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.util.app.ContextUtil;
import com.kingdee.shr.elecontract.util.URLUtils;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import java.io.FileInputStream;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.*;


import java.util.Map;

/**
 * @Description 获取单点oa地址
 * @Date 2025/1/8 17:01
 * @Created by Heyuan
 */
public class GetSsoOAUrl implements IHRMsfService {
    private static Logger logger = Logger.getLogger(GetSsoOAUrl.class);
    private static Properties prop = new Properties();
    private static String propPath = System.getProperty("EAS_HOME") + "/server/properties/scy/OASSOConfig.properties";

    static {
        try {
            prop.load(new FileInputStream(propPath));
        } catch (IOException e) {
            logger.error("获取配置文件报错: " + e.getMessage());
            e.printStackTrace();
        }
    }

    @Override
    public Object process(Context ctx,
                          Map<String, Object> params) throws EASBizException, BOSException {
        String ssoPath = (String) params.get("ssoPath");
        Map<String, String> result = new HashMap<>();
        String ssoOAUrl = null;
        try {
            if (StringUtils.isBlank(ssoPath)) {
                throw new BOSException("单点地址不能为空!");
            }
            String token = getToken(ctx);
            ssoOAUrl = MessageFormat.format(ssoPath, token);
            result.put("result", "success");
            result.put("data", ssoOAUrl);
        } catch (BOSException e) {
            e.printStackTrace();
            result.put("result", "error");
            result.put("summary", e.getMessage());
        }
        return result;
    }

    /**
     * 获取 token
     */
    public String getToken(Context ctx) throws BOSException {
        String getSsoTokenUrl = prop.getProperty("getSsoTokenUrl");
        String ssoAppid = prop.getProperty("ssoAppid");
        StringBuilder errorMsg = new StringBuilder();
        if (StringUtils.isBlank(getSsoTokenUrl)) {
            errorMsg.append("获取sso接口地址不能为空!\n");
        }
        if (StringUtils.isBlank(ssoAppid)) {
            errorMsg.append("ssoAppid不能为空!\n");
        }
        if (errorMsg.length() > 0) {
            throw new BOSException(errorMsg.toString());
        }

        String loginId = ContextUtil.getCurrentUserInfo(ctx).getNumber();
        Map<String, String> params = new HashMap<>();
        params.put("appid", ssoAppid);
        params.put("loginid", loginId);
        String getUrl = URLUtils.assembleUrl(getSsoTokenUrl, params);
        logger.error("getToken getUrl: " + getUrl);
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(getUrl)
                .get()
                .addHeader("Accept", "*/*")
                .addHeader("Accept-Encoding", "gzip, deflate, br")
                .addHeader("User-Agent", "PostmanRuntime-ApipostRuntime/1.1.0")
                .addHeader("Connection", "keep-alive")
                .addHeader("content-type", "multipart/form-data; boundary=---011000010111000001101001")
                .build();
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                return response.body().string();
            } else {
                throw new BOSException("获取ssoToken超时");
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new BOSException("获取ssoToken报错: " + e.getMessage());
        }
    }
}
