package yangtz.cs.liu.dingding.utils;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGetJsapiTicketRequest;
import com.dingtalk.api.response.OapiGetJsapiTicketResponse;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.taobao.api.ApiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 鉴权
 */
@Component
public class JSAPIUtils {

    @Autowired
    private AccessTokenUtils accessTokenUtils;
    @Autowired
    public RedisCache redisCache;

    /**
     * 获取jsapi_ticket
     * @return
     */
    public String getJsapiTicket(){
        String jsapiTicket = redisCache.getCacheObject("dd_jsapi_ticket");
        if (StringUtils.isEmpty(jsapiTicket)){
            String accesstoken = accessTokenUtils.getToken();
            try {
                DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/get_jsapi_ticket");
                OapiGetJsapiTicketRequest req = new OapiGetJsapiTicketRequest();
                req.setHttpMethod("GET");
                OapiGetJsapiTicketResponse rsp = client.execute(req, accesstoken);
                String rspTicket = rsp.getTicket();
                if (!StringUtils.isEmpty(rspTicket)) {
                    jsapiTicket = rspTicket;
                    // 将access_token存入redis
                    redisCache.setCacheObject("dd_jsapi_ticket", jsapiTicket, 2, TimeUnit.HOURS);
                }
            } catch (ApiException e) {
                e.printStackTrace();
                return "获取失败";
            }
        }
        return jsapiTicket;
    }
}
