package cn.com.ctop.common.module.utils;

import lombok.extern.slf4j.Slf4j;
import lombok.val;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.bean.WxCpMessage;
import me.chanjar.weixin.cp.config.impl.WxCpDefaultConfigImpl;

import java.util.List;

@Slf4j
public class CorpWexinUtils {
    private static WxCpService wxCpService;

    {
        initService();
    }

    public static void initService() {
        val configStorage = new WxCpDefaultConfigImpl();
        configStorage.setCorpId("ww24b8a47826f5875f");
        configStorage.setAgentId(1000002);
        configStorage.setCorpSecret("MJIlySADGPlgvADnkFQPUpfZD4yV-4WN6066OgNnb0s");
        configStorage.setToken("hcst2019");
        configStorage.setAesKey("hcst2019");
        wxCpService = new WxCpServiceImpl();
        wxCpService.setWxCpConfigStorage(configStorage);
    }

    public static void sendMessage(List<String> wxUserList, String content) {
        if (wxCpService == null) {
            initService();
        }
        if (wxUserList != null && wxUserList.size() > 0) {
            for (String userId : wxUserList) {
                WxCpMessage message = new WxCpMessage();
                message.setMsgType("text");
                message.setContent(content);
                message.setAgentId(1000002);
                message.setToUser(userId);
                try {
                    wxCpService.messageSend(message);
                } catch (WxErrorException e) {
                    log.error("发送信息失败，userId:{}", userId);
                    e.printStackTrace();
                }
            }
        }
    }

    public synchronized static void sendMessageByWeChatId(String weChatId, String content) {
        if (wxCpService == null) {
            initService();
        }
        if (!Check.isNull(weChatId)) {
            WxCpMessage message = new WxCpMessage();
            message.setMsgType("text");
            message.setContent(content);
            message.setAgentId(1000002);
            message.setToUser(weChatId);
            try {
                wxCpService.messageSend(message);
            } catch (WxErrorException e) {
                log.error("发送信息失败，userId:{}", weChatId);
                e.printStackTrace();
            }

        }


    }

}
