package com.weaver.seconddev.chapanda.feishu.util;

import com.alibaba.fastjson.JSONObject;
import com.weaver.common.cache.base.BaseCache;
import com.weaver.seconddev.chapanda.feishu.cache.FeishuTokenCacheKey;
import com.weaver.seconddev.chapanda.feishu.constant.Constants;
import com.weaver.seconddev.chapanda.feishu.module.FeishuTokenModuleKey;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class Esb2FeishuTokenUtil {
    private final static Logger log = LoggerFactory.getLogger(Esb2FeishuTokenUtil.class);

    @Autowired
    private BaseCache baseCache;

    public int earlySecond = 120;

    public String getToken() {
        String token = (String) baseCache.get(FeishuTokenModuleKey.FENSHUTOKEN_DATACENTER, FeishuTokenCacheKey.FEISHU_TOKEN);
        if (StringUtils.isBlank(token)) {
            JSONObject returnData = getAccessToken();
            if(returnData.containsKey("tenantAccessToken")){
                token = returnData.getString("tenantAccessToken");
                int expire = returnData.getInteger("expire");
                if(expire > 0){
                    baseCache.set(FeishuTokenModuleKey.FENSHUTOKEN_DATACENTER, FeishuTokenCacheKey.FEISHU_TOKEN, token, expire);
                }
            }
        }
        return token;
    }

    public JSONObject getAccessToken() {

        // https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal
        JSONObject returnData = new JSONObject();
        JSONObject dataJson = new JSONObject();
        dataJson.put("app_id", Constants.app_id);
        dataJson.put("app_secret", Constants.app_secret);

//        dataJson.put("app_id", "cli_a8d0ee6b667dd00e");
//        dataJson.put("app_secret", "UjShC4eY7vCgHsQvFWZZleVdCqSEWGD0");

        try {
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
            RequestBody body = RequestBody.create(mediaType, dataJson.toJSONString());
            Request request = new Request.Builder()
                    .url(Constants.feishuHost+Constants.tokenUrl)
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json; charset=utf-8")
                    .build();
            Response response = client.newCall(request).execute();
            int code = response.code();
            String msg = response.body().string();

            if(code == 200){
                if(StringUtils.isNotBlank(msg)){
                    JSONObject returnJson = JSONObject.parseObject(msg);
                    if(returnJson.containsKey("code")){
                        String dataCode = returnJson.getString("code");
                        if("0".equals(dataCode)){
                            String tenantAccessToken = returnJson.getString("tenant_access_token");
                            int expire = returnJson.getInteger("expire");

                            returnData.put("tenantAccessToken",tenantAccessToken);
                            returnData.put("expire",expire - earlySecond);
                        }
                    }
                }
            }else{
                log.error("msg:{}",msg);
            }
        } catch (Exception e) {
            log.error("e:{}",e.getMessage());
            e.printStackTrace();
        }
        return returnData;
    }

}
