package com.weaver.seconddev.njwebservice.util;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.weaver.common.i18n.tool.util.I18nContextUtil;
import com.weaver.common.i18n.tool.util.Util;
import com.weaver.verupgrade.conn.CONN_TYPE;
import com.weaver.verupgrade.conn.RecordSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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


/**
 * @Author liang.cheng
 * @Date 2025/1/7 2:41 PM
 * @Description: access_token 获取
 * @Version 1.0
 */
public class AccessTokenUtil {

    private final static Logger log = LoggerFactory.getLogger(AccessTokenUtil.class);

    private static String CORP_ID = "9d18deb9bbeb98f7a2402808f8bb8ce8";

    //private static String APP_KEY = "179a9854c471d161db69ec9f16c6e1e";
    private static String APP_KEY = "437dd08a2cd0018bf1242128cab4224c";

    //private static String APP_SECRET = "9aa17e9391d8fdf4be44f78e2a26be30";
    private static String APP_SECRET = "3e86b82ada2b72fdd3d7929d5623b04f";

    private static String HOST = "http://10.6.24.64:20600/papi/openapi";

    /**
     * 获取AccessToken
     * @return
     * @throws Exception
     */
    public static String getToken() throws Exception {

        // 获取code
        String codeUrl = HOST + "/oauth2/authorize?corpid=" + CORP_ID + "&response_type=code&state=a21";
        String codeResponse = HttpUtil.get(codeUrl);
        System.out.println(codeResponse);

        JSONObject jsonObject = JSONObject.parseObject(codeResponse);
        Object errcode = jsonObject.get("errcode");
        Object code = jsonObject.get("code");
        log.error("本次获取code值"+code+"==> errcode"+errcode);

        // 根据code 获取token。
        String tokenUrl = HOST + "/oauth2/access_token";
        Map<String, Object> tokanParam = new HashMap<>(4);
        tokanParam.put("app_key", APP_KEY);
        tokanParam.put("app_secret", APP_SECRET);
        tokanParam.put("grant_type", "authorization_code");
        tokanParam.put("code", code);

        String tokenResponse = HttpUtil.post(tokenUrl, tokanParam);
        log.error("tokenResponse" + tokenResponse);

        JSONObject tokenResponseObj = JSONObject.parseObject(tokenResponse);
        return Optional.ofNullable(tokenResponseObj.get("accessToken")).map(Object::toString).orElse(new String());
    }


    public static String getAccessToken(String tenantKey) {

        String accesstoken = "";
        String sql = "select accesstoken from e10_common.dbo.uf_tenant_mt where  zzkey='"+tenantKey+"' and delete_type ='0'";
        RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
        String poolname = CONN_TYPE.ebuilder.getType();
        rs.setTenantKey(tenantKey);
        rs.executeSql(sql, poolname);
        if (rs.next()) {
            accesstoken = Util.null2String(rs.getString("accesstoken"));
        }
        return accesstoken;
    }
}
