package com.cm.common.plugin.push;

import com.cm.common.component.OAuthRestTemplateComponent;
import com.cm.common.config.properties.ApiPathProperties;
import com.cm.common.config.properties.OauthClientProperties;
import com.cm.common.plugin.utils.RestTemplateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: PushMessage
 * @Description:
 * @Author: WangGeng
 * @Date: 2019/10/14 4:07 下午
 * @Version: 1.0
 **/
@Component
public class PushMessage {
    private static final Logger LOG = LoggerFactory.getLogger(PushMessage.class);
    /**
     * APP推送的地址
     */
    private static final String APP_PUSH_URL = "%s/app/push/pushmessage/%s";
    /**
     * 客户端推送地址
     */
    private static final String RESOURCE_PUSH_CONTENT_URL = "%s/resource/push/pushmessagetouserwithcontent";
    @Autowired
    private ApiPathProperties apiPathProperties;
    @Autowired
    private RestTemplateUtil restTemplateUtil;
    @Autowired
    private OAuthRestTemplateComponent oAuthRestTemplateComponent;

    private static Executor executor = new ThreadPoolExecutor(2, 10, 60000, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>());

    /**
     * app推送
     *
     * @param token
     * @param userId
     * @param title
     * @param content
     */
    public void appPush(String token, String userId, String title, String content) {
        Map<String, Object> params = new HashMap<>(2);
        params.put("title", title);
        params.put("content", content);
        executor.execute(() -> {
            String result = restTemplateUtil.doPostJsonForApp(token, String.format(APP_PUSH_URL, apiPathProperties.getUserCenter(), userId), params);
            if (result == null) {
                LOG.error("消息推送失败");
            } else {
                LOG.info(result);
            }
        });
    }

    /**
     * 客户端推送
     *
     * @param token
     * @param params
     */
    public void clientPush(String token, Map<String, Object> params) {
        executor.execute(() -> {
            String result = oAuthRestTemplateComponent.doPostJsonForOAuth2Client(token, String.format(RESOURCE_PUSH_CONTENT_URL, apiPathProperties.getUserCenter()), params);
            if (result == null) {
                LOG.error("消息推送失败");
            } else {
                LOG.info(result);
            }
        });
    }

}
