package com.gtiit.shr.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author ramon.wang
 * @date Created in 18/07/2025 14:56
 * @description
 */
@Component
public class NewOaApiUtil {

    private static final HashMap<String, String> NEWSYSTEM_CACHE = new HashMap();

    @Autowired
    FinalParamUtil finalParamUtil;

    //TODO 后面这些参数需要写入到yml文件中，然后进行调用
//    private static final String OAURL = "https://sites.gtiit.edu.cn/oatest";

//    private static final String app_key = "b9693deee1dba5f70134e81161d7b31";

//    private static final String app_secret = "550856d7234a759b333a93aeb09739d3";

//    private static final String grant_type = "authorization_code";

//    private static final String corpid = "4bfaa311d6ac47f4822020e1ff3f2bf8";

//    private static final String response_type = "code";


    private Map<String, Object> getCode(String address) {
        Map<String, Object> codeBody = new HashMap();
        codeBody.put("corpid", this.finalParamUtil.getCorpid());
        codeBody.put("response_type", this.finalParamUtil.getResponseType());
        codeBody.put("state", "");
        String jsonString = JSONObject.toJSONString(codeBody);
        String data = HttpRequest.post(address + "/papi/openapi/oauth2/authorize").body(jsonString).execute().body();
        System.out.println("getCode()--new：" + data);
        Map<String, Object> datas = JSONUtil.parseObj(data);
        return datas;
    }

    public Map<String, Object> getoken(String address) {
        Map<String, Object> codeMap = this.getCode(address);
        String code = (String) codeMap.get("code");
        Map<String, Object> tokenBody = new HashMap();
        tokenBody.put("app_key", this.finalParamUtil.getAppKey());
        tokenBody.put("app_secret", this.finalParamUtil.getAppSecret());
        tokenBody.put("grant_type", this.finalParamUtil.getGrantType());
        tokenBody.put("code", code);
        String jsonString = JSONObject.toJSONString(tokenBody);
        //access_token过期时间
        NEWSYSTEM_CACHE.put("EXPIRE_TIME", String.valueOf(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(2)));
        String data = HttpRequest.post(address + "/papi/openapi/oauth2/access_token").header("Content-Type", "application/json").body(jsonString).execute().body();
        System.out.println("getoken()--new：" + data);
        Map<String, Object> datas = JSONUtil.parseObj(data);
        NEWSYSTEM_CACHE.put("ACCESS_TOKEN", StrUtil.nullToEmpty((String) datas.get("accessToken")));
        return datas;
    }

    public String restful(String api, Map jsonParams, String menthType) {
        //获取accesstoken
        String accessToken = (String) NEWSYSTEM_CACHE.get("ACCESS_TOKEN");
        //判断accesstoken是否过期，2小时过期
        Boolean isExpire = Boolean.FALSE;
        if (!StrUtil.isEmpty(NEWSYSTEM_CACHE.get("EXPIRE_TIME"))) {
            long expireTime = Long.valueOf(NEWSYSTEM_CACHE.get("EXPIRE_TIME"));
            if (System.currentTimeMillis() > expireTime) {
                isExpire = Boolean.TRUE;
            }
        }
        if (StrUtil.isEmpty(accessToken) || isExpire) {
            accessToken = (String) this.getoken(this.finalParamUtil.getNewoaUrl()).get("accessToken");
        }
        jsonParams.put("access_token", accessToken);
        String jsonString = JSONObject.toJSONString(jsonParams);
        if ("sendAPIByAddAdmin".equals(menthType)) {
            return this.newSendAPIByAddAdmin(this.finalParamUtil.getNewoaUrl() + api, jsonString);
        } else if ("sendAPIByAddPosition".equals(menthType)) {
            return this.newSendAPIByAddPosition(this.finalParamUtil.getNewoaUrl() + api, jsonString);
        } else {
            return "sendAPIByAddPerson".equals(menthType) ? this.newsendAPIByAddPerson(this.finalParamUtil.getNewoaUrl() + api, jsonString) : "未找到相关调用代码";
        }
    }

    private String newSendAPIByAddAdmin(String api, String jsonParams) {
        String data = HttpRequest.post(api).header("Content-Type", "application/json").body(jsonParams).execute().body();
        System.out.println("Restful()--new--admin：" + data);
        return data;
    }

    private String newSendAPIByAddPosition(String api, String jsonParams) {
        String data = HttpRequest.post(api).header("Content-Type", "application/json").body(jsonParams).execute().body();
        System.out.println("Restful()--new--position：" + data);
        return data;
    }

    private String newsendAPIByAddPerson(String api, String jsonParams) {
        String data = HttpRequest.post(api).header("Content-Type", "application/json").body(jsonParams).execute().body();
        System.out.println("Restful()--new--person：" + data);
        return data;
    }
}
