package org.springblade.common.notify.dingding.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class DingDingAccessTokenHandler {

    private static final String GET_TOKEN_URL = "https://oapi.dingtalk.com/gettoken?corpid=%s&corpsecret=%s";

    @Value("${msg.notify.dingding.corpId:ding1eed08fccc7d748835c2f4657eb6378f}")
    private String corpId = "ding1eed08fccc7d748835c2f4657eb6378f"; //企业ID

    @Value("${msg.notify.dingding:nQ2Q3zLKl96BRulQj3S2u9FHGXy6B1Bs3DHGN_o-Doup5icaZ_YAJu4tDXnhbHso}")
    private String corpSecrect = "nQ2Q3zLKl96BRulQj3S2u9FHGXy6B1Bs3DHGN_o-Doup5icaZ_YAJu4tDXnhbHso"; //企业秘钥

    //获取钉钉的accessToken值
    public String getAccessToken() throws Exception {
        String url = String.format(GET_TOKEN_URL, corpId, corpSecrect);
        HttpClient httpclient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet(url);
        HttpResponse response = httpclient.execute(httpget);
        log.info("调用钉钉接口的入参是：{}", url);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            JSONObject obj = JSON.parseObject(result);
            String accessToken = obj.getString("access_token");
            if (StringUtils.isBlank(accessToken)) {
                log.error("DingDingAccessTokenHandler.getAccessToken can't parse accessToken. result = {}", result);
            }
            return accessToken;
        } else {
            if (response.getEntity() != null) {
                log.error("DingDingAccessTokenHandler.getAccessToken failure, " + EntityUtils
                        .toString(response.getEntity(), "utf-8"));
            }
            return null;
        }
    }

}
