package com.galaxis.manatee.service;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.galaxis.manatee.constant.DingTalkConstant;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.net.URISyntaxException;
import java.time.LocalDateTime;

/**
 * @author zcj
 * @version 0.1
 * @date 2020/1/8 5:42 下午
 */
@Slf4j
@Service
public class DingTalkAuthorization {

    @Value(value = "${dingTalk.getTokenUri}")
    private String getTokenUri;

    /**
     * 自动获取钉钉授权
     * @throws URISyntaxException   URI异常
     */
    @Scheduled(fixedDelay = 7000000L)
    private void getToken() throws URISyntaxException {
        RestTemplate restTemplate=new RestTemplate();
        URI uri=new URI(getTokenUri+"?appkey="+ DingTalkConstant.DING_TALK_APP_KEY +"&appsecret="+DingTalkConstant.DING_TALK_APP_SECRET);
        DingTalkToken dingTalkToken=restTemplate.getForObject(uri,DingTalkToken.class);
        DingTalkConstant.DING_TALK_TOKEN =dingTalkToken.getAccessToken();
        log.info("获得token"+ LocalDateTime.now());
    }

    /**
     * 钉钉token数据结构
     */
    @Data
    @JsonIgnoreProperties(ignoreUnknown = true)
    private static class DingTalkToken{

        @JsonProperty(value = "errcode")
        private String errorCode;

        @JsonProperty(value = "access_token")
        private String accessToken;

        @JsonProperty(value = "errmsg")
        private String errorMessage;

        @JsonProperty(value = "expired_in")
        private Integer expiredIn;
    }
}
