package cn.com.ctop.common.module.service.impl;

import cn.com.ctop.common.module.mapper.MailLogMapper;
import cn.com.ctop.common.module.service.ISendMessageService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.CorpIllegalWexinUtils;
import cn.com.ctop.common.module.utils.CorpWexinUtils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class SendMessageServiceImpl implements ISendMessageService {
    @Autowired
    private MailLogMapper mailLogMapper;
    @Autowired
    private CorpWexinUtils corpWexinUtils;
    @Autowired
    private CorpIllegalWexinUtils illegalWexinUtils;

    @Override
    public void sendMessage(String userId, String text) {
        JSONObject weChatId = mailLogMapper.getWChatIdByUserId(userId);
        if (!Check.isNull(weChatId)) {
            corpWexinUtils.sendMessageByWeChatId(weChatId, text);
            log.info("消息发送成功，userId:{}，消息内容：{}", userId, text);
        }
    }

    @Override
    public void sendMessageByAccountId(Long accountId, String text) {
        List<JSONObject> list = mailLogMapper.getWChatIdByAccountId(accountId);
        for (JSONObject jsonObject : list) {
            corpWexinUtils.sendMessageByWeChatId(jsonObject, text);
        }
    }

    @Override
    public void illegalSendMessage(JSONObject info) {
        Long accountId = info.getLong("accountId");
        String userId = info.getString("userId");
        String text = info.getString("sendContent");
        List<JSONObject> list = mailLogMapper.getIllegalWChatId(accountId, userId);
        ArrayList<Object> collect = CollectionUtils.collect(list, row -> row.getString("wexin_name"), new ArrayList<>());
        for (JSONObject jsonObject : list) {
            illegalWexinUtils.sendMessageByWeChatId(jsonObject, text);
        }
        info.put("userIds", StringUtils.join(collect.iterator(), ","));
    }
}
