package com.mortals.xhx.module.dingding;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.xhx.common.pdu.ApiRespPdu;
import com.mortals.xhx.module.dingding.personal.service.IDingPersonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;

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

/**
 * 钉钉访问抽象服务类
 *
 * @author:
 * @date: 2023/7/14 13:49
 */
@Slf4j
public abstract class AbstractDingTalkService implements IDingPersonService {

    /**
     * AgentId
     */
    @Value("${dingtalk.agentId:0}")
    protected Long agentId;

    /**
     * AgentId
     */
    @Value("${dingtalk.domain:https://oapi.dingtalk.com}")
    protected String domain;

    /**
     * appKey
     */
    @Value("${dingtalk.AppKey:''}")
    protected String appKey;

    /**
     * AppSecret
     */
    @Value("${dingtalk.AppSecret:''}")
    protected String appSecret;

    /**
     * getToken
     */
    @Value("${dingtalk.gettoken:https://oapi.dingtalk.com/gettoken}")
    protected String getTokneUrl;

    protected String dingToken;

    protected DingTalkClient getDingTalkClient(String path) {
        DingTalkClient client = new DefaultDingTalkClient(domain + path);
        return client;
    }

    protected void checkToken() {
        if (ObjectUtils.isEmpty(dingToken)) {
            dingToken = getToken().getData();
        }
    }

    @Override
    public Rest<String> getToken() {
        try {
            DingTalkClient client = getDingTalkClient("/gettoken");
            OapiGettokenRequest req = new OapiGettokenRequest();
            req.setAppkey(appKey);
            req.setAppsecret(appSecret);
            OapiGettokenResponse rsp = client.execute(req);
            log.info("OapiGettokenResponse:{}",rsp.getBody());
            if (rsp.getErrcode() == 0) {
                return Rest.ok(rsp.getAccessToken());
            } else {
                throw new AppException(rsp.getMessage());
            }

        } catch (Exception e) {
            log.error("获取TOKEN异常", e);
            return Rest.fail(e.getMessage());
        }
    }

}
