package cn.com.ctop.notice.handler;

import cn.com.ctop.common.module.mapper.MailLogMapper;
import cn.com.ctop.common.module.utils.CorpWexinUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Slf4j
@Service
public class SendWeChatHandle {

    @Autowired
    MailLogMapper mailLogMapper;

    public void sendWeChatByMail(String mail,String message){
        String weChatId=mailLogMapper.getWeChatByMail(mail);
        if(weChatId.isEmpty()){
        log.error(String.format("mail's WeChat not found. mail =%s", mail));
        //TODO 通知管理员添加邮箱
    }else{
        List<String> messageList= splitMessage(message);
        messageList.forEach(it->CorpWexinUtils.sendMessageByWeChatId(weChatId,it));
    }
}

    /**
     * 发送多人，邮箱逗号隔开
     * @param mails
     * @param message
     */
    public void sendWeChatByMails(String mails,String message){
        List<String> mail= Arrays.asList(mails.split(","));
        mail.forEach(m-> this.sendWeChatByMail(m,message));
    }

    /**
     *  消息切割
     */
    private List<String> splitMessage(String message){
        List<String> messageList=new ArrayList<>();
        if(message.length()>1006){
            int number=message.length()/1006;
            for(int i=0;i<number;i++){
                if(i!=number-1){
                    messageList.add(message.substring(i*1006,(i+1)*1006-1));
                }else {
                    messageList.add(message.substring((i+1)*1006));
                }
            }
        }else {
            messageList.add(message);
        }
        return messageList;
    }
}
