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

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONArray;
import kd.bos.exception.KDBizException;

import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.sdk.util.KHttpClientUtils;
import kd.bos.util.StringUtils;
import nckd.base.helper.CommonHelperUtils;

import java.util.HashMap;
import java.util.Map;

public class FanWeiUtils {
    private static final Log logger = LogFactory.getLog(FanWeiUtils.class);

    public static String getFanWeiToken(String url) {
        try {
            Map<String, String> mapentity = CommonHelperUtils.getCommonParams("fanwei-prod");
            if(mapentity == null){
                return null;
            }
            String param_corpid = mapentity.get("corpid");
            String param_response = mapentity.get("response_type");
            String param_state = mapentity.get("state");
            String param_app_key = mapentity.get("app_key");
            String param_grant_type = mapentity.get("grant_type");
            String param_app_secret = mapentity.get("app_secret");
            String param_code_url = mapentity.get("getcode");
            String param_token_url = mapentity.get("gettoken");
            String post_getspeaker_url = mapentity.get("getspeaker");
            String param_secretkey = mapentity.get("secret_key");
            String param_operator = mapentity.get("operator");

            if( StringUtils.isEmpty(param_corpid) || StringUtils.isEmpty(param_app_secret)
                    || StringUtils.isEmpty(param_code_url) || StringUtils.isEmpty(param_token_url)
                    ||  StringUtils.isEmpty(param_app_key)){
                return null;
            }

            String post_url = null;
            switch (url) {
                case "speaker":
                    post_url = post_getspeaker_url;break;
                default:
                    break;
            }

            //http://172.16.51.120:20600/papi/openapi/oauth2/authorize?corpid=ca9c4a14fe2e2d92d94125024c538ba3&response_type=code&state=jyyy

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

            //获取token
            StringBuilder authorizeUrl = new StringBuilder();
            authorizeUrl.append(param_code_url);
            authorizeUrl.append("?corpid=");
            authorizeUrl.append(param_corpid);
            authorizeUrl.append("&response_type=");
            authorizeUrl.append(param_response);
            authorizeUrl.append("&state=");
            authorizeUrl.append(param_state);

            String tokenPostData = getTokenData();

            logger.info("请求泛微 接口：" + authorizeUrl.toString() );
            //String code = KHttpClientUtils.get(authorizeUrl.toString());
            String code = KHttpClientUtils.postjson(authorizeUrl.toString().toString(),header,tokenPostData);
            logger.info("请求泛微 authorizeUrl Return：" + code );

            JSONObject codeJson  = JSONObject.parseObject(code);
            String codeString = codeJson.getString("code");
            if(StringUtils.isNotEmpty(codeString)){
                StringBuilder tokenUrl = new StringBuilder();
                tokenUrl.append(param_token_url);
                tokenUrl.append("?app_key=");
                tokenUrl.append(param_app_key);
                tokenUrl.append("&app_secret=");
                tokenUrl.append(param_app_secret);
                tokenUrl.append("&grant_type=");
                tokenUrl.append(param_grant_type);
                tokenUrl.append("&code=");
                tokenUrl.append(codeString);

                logger.info("请求泛微 接口：" + tokenUrl.toString() );
                String reToken = KHttpClientUtils.postjson(tokenUrl.toString(),header,tokenPostData);
                logger.info("请求泛微 TokenUrl Return：" + reToken );
                JSONObject tokenJson  = JSONObject.parseObject(reToken);
                String tokenString = tokenJson.getString("accessToken");
                if(StringUtils.isNotEmpty(tokenString)){
                    StringBuilder speakerUrl = new StringBuilder();
                    speakerUrl.append(post_url);
                    speakerUrl.append("?access_token=");
                    speakerUrl.append(tokenString);
                    speakerUrl.append("&secret_key=");
                    speakerUrl.append(param_secretkey);

                    String speakerJsonData = getSpeakerData(param_operator);
                    logger.info("请求OA 接口：" + speakerUrl.toString());
                    logger.info("请求OA data：" + speakerJsonData);

                    String result = KHttpClientUtils.postjson(speakerUrl.toString(), header, speakerJsonData);
                    logger.info("请求OA Speaker Return：" + result);
                    return result;
                }

            }
            return null;

        } catch (Exception e) {
            throw new KDBizException("请求OA接口失败：" + e.getMessage());
        }
    }

    public static String getSpeakerData(String operator)
    {
        // 构建 requestHead 对象
        JSONObject requestHead = new JSONObject();
        requestHead.put("mainBodyId", "JY");

        // 构建 pageInfo 对象
        JSONObject pageInfo = new JSONObject();
        pageInfo.put("pageNo", "1");
        pageInfo.put("pageSize", "1000");

        // 构建 header 对象
        JSONObject header = new JSONObject();
        header.put("operator", operator);

        // 构建 datajson 对象
        JSONObject datajsonParent = new JSONObject();
        JSONObject datajson = new JSONObject();
        datajson.put("mainTable", new JSONObject()); // mainTable 是一个空对象
        datajson.put("pageInfo", pageInfo);
        datajson.put("header", header);
        datajsonParent.put("datajson", datajson);

        // 构建 requestData 数组
        JSONArray requestData = new JSONArray();
        requestData.add(datajsonParent);

        // 构建最终的根 JSON 对象
        JSONObject rootJson = new JSONObject();
        rootJson.put("requestHead", requestHead);
        rootJson.put("requestData", requestData);

        return rootJson.toString();
    }

    public static String getTokenData(){
        JSONObject requestHead = new JSONObject();
        requestHead.put("mainBodyId", "JY");

        JSONObject rootJson = new JSONObject();
        rootJson.put("requestHead", requestHead);
        return rootJson.toString();
    }

}
