package org.springblade.common.notify.dingding;

import org.springblade.common.cache.CachesService;
import com.wn.common.exception.BusinessException;
import org.springblade.common.notify.constant.NotifyErrorConstants;
import org.springblade.common.notify.dingding.handler.DingDingAccessTokenHandler;
import org.springblade.common.notify.dingding.handler.DingDingMsgSendHandler;
import org.springblade.common.notify.dingding.handler.DingDingUserSyncHandler;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class DingDingMsgNotify {

    public static final String DING_CACHE_TYPE = "dingding";

    public static final String DING_CACHE_KEY = "userinfo";

    public static final String DING_EMPTY_USERID = "empty";

    //12 hours
    public static final int DING_CACHE_TIMEOUT_SECONDS = 3600 * 12;

    @Autowired
    private CachesService cacheService;

    @Autowired
    private DingDingUserSyncHandler userSyncHandler;

    @Autowired
    private DingDingAccessTokenHandler accessTokenHandler;

    @Autowired
    private DingDingMsgSendHandler msgSendHandler;

    //根据用户手机号码查询钉钉ID
    private String getUserIdByUsername(String accessToken, String name) throws Exception {
        Map<String, String> mapping = cacheService.getFromCache(DING_CACHE_TYPE, DING_CACHE_KEY);
        if (mapping != null && mapping.get(name) != null) {
            return mapping.get(name);
        }
        mapping = userSyncHandler.doSyncData(accessToken);
        if (mapping == null) {
            log.error("DingDingMsgNotify sync user info from DingDing return empty data.");
            return null;
        }
        if (mapping.get(name) == null) {
            mapping.put(name, DING_EMPTY_USERID);
        }
        cacheService.putInCache(DING_CACHE_TYPE, DING_CACHE_KEY, mapping, DING_CACHE_TIMEOUT_SECONDS);
        return mapping.get(name);
    }

    /**
     * 发送钉钉消息
     *
     * @param name    用户姓名
     * @param message 消息内容
     * @return 发送结果，以JSON格式返回
     * @throws Exception
     */
    public String send(String name, String message) throws BusinessException {
        try {
            String accessToken = accessTokenHandler.getAccessToken();
            if (StringUtils.isEmpty(accessToken)) {
                throw new BusinessException(NotifyErrorConstants.DING_ACCESS_TOKEN_ERROR);
            }
            String userId = getUserIdByUsername(accessToken, name);
            if (userId == null) {
                throw new BusinessException(NotifyErrorConstants.DING_USER_SYNC_ERROR);
            }
            if (DING_EMPTY_USERID.equalsIgnoreCase(userId)) {
                throw new BusinessException(NotifyErrorConstants.DING_SEND_USERID_EMPTY);
            }
            String result = msgSendHandler.send(accessToken, userId, message);
            if (StringUtils.isEmpty(result)) {
                throw new BusinessException(NotifyErrorConstants.DING_SEND_MSG_ERROR);
            }
            return result;
        } catch (Exception e) {
            log.error("DingDingMsgNotify send dingding msg error. ", e);
            throw new BusinessException(NotifyErrorConstants.DING_SEND_MSG_ERROR);
        }

    }

    public String sendDDMessage(String userId, String message) {
        try {
            String accessToken = accessTokenHandler.getAccessToken();
            if (StringUtils.isEmpty(accessToken)) {
                throw new BusinessException(NotifyErrorConstants.DING_ACCESS_TOKEN_ERROR);
            }
            String result = msgSendHandler.send(accessToken, userId, message);
            if (StringUtils.isEmpty(result)) {
                throw new BusinessException(NotifyErrorConstants.DING_SEND_MSG_ERROR);
            }
            return result;
        } catch (Exception e) {
            log.error("DingDingMsgNotify send dingding msg error. ", e);
            throw new BusinessException(NotifyErrorConstants.DING_SEND_MSG_ERROR);
        }
    }
}