package com.xhkjedu.sexam.service.notice;

import com.xhkjedu.sexam.mapper.exam.EClassMapper;
import com.xhkjedu.sexam.mapper.notice.*;
import com.xhkjedu.sexam.mapper.system.UserMapper;
import com.xhkjedu.sexam.model.notice.*;
import com.xhkjedu.sexam.utils.ExamUtil;
import com.xhkjedu.sexam.utils.SMSSender;
import com.xhkjedu.sexam.vo.exam.ExamVo;
import com.xhkjedu.sexam.vo.exam.ZtMsgVo;
import com.xhkjedu.utils.N_Utils;
import com.xhkjedu.vo.system.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ywx
 * @classname NoticeService
 * @description
 * @date 2020/6/12 17:55
 **/
@Service
@Slf4j
public class NoticeService {
    @Resource
    private NoticeMapper noticeMapper;
    @Resource
    private NoticeUserMapper noticeUserMapper;
    @Resource
    private MsgMapper msgMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private EClassMapper eClassMapper;

    //批量添加通知和短信
    @Async("asyncPoolTaskExecutor")
    public void batchSave(List<TNotice> noticeList, List<TMsg> msgList, Integer schoolid, Integer createid, Integer noticetype) {
        try {
            Integer createtime = N_Utils.getSecondTimestamp();
            if (N_Utils.isListNotEmpty(noticeList)) {//通知
                noticeList = noticeList.stream().distinct().collect(Collectors.toList());
                noticeList.forEach(n -> {
                    n.setNoticetxt(n.getNoticecontent().replaceAll("<[.[^>]]*>", ""));
                    n.setNoticetype(noticetype);
                    n.setCreatetime(createtime);
                    n.setCreateid(createid);
                    n.setSchoolid(schoolid);
                });
                noticeMapper.insertList(noticeList);

                List<TNoticeUser> teacherList = new ArrayList<>();
                noticeList.forEach(n -> {
                    Integer noticeid = n.getId();
                    List<TNoticeUser> teachers = n.getUsers().stream().distinct().collect(Collectors.toList());
                    teachers.forEach(t -> {
                        t.setNoticeid(noticeid);
                        t.setReaded(0);
                        t.setCreatetime(createtime);
                    });
                    teacherList.addAll(teachers);
                });

                if (N_Utils.isListNotEmpty(teacherList)) noticeUserMapper.insertList(teacherList);//通知教师关联信息
            }

            if (N_Utils.isListNotEmpty(msgList)) {//短信
                msgList = msgList.stream().distinct().collect(Collectors.toList());
                List<TMsg> msgs = new ArrayList<>();
                if (noticetype == 1) {//通知对象1班级
                    for (TMsg msg : msgList) {
                        msg.setCreatetime(createtime);
                        msgs.add(msg);
                    }
                } else {//通知对象2老师
                    List<Integer> userids = msgList.stream().map(TMsg::getUserid).distinct().collect(Collectors.toList());
                    List<UserVo> users = userMapper.listPhoneByUserIds(userids);//根据用户ids查找手机号
                    Map<Integer, TMsg> msgMap = msgList.stream().collect(Collectors.toMap(TMsg::getUserid, m -> m));
                    for (UserVo u : users) {
                        String userphone = u.getUserphone();
                        if (N_Utils.isEmpty(userphone)) continue;
                        TMsg m = msgMap.get(u.getUserid());
                        m.setUserphone(userphone);
                        m.setCreatetime(createtime);
                        msgs.add(m);
                    }
                }
                if (N_Utils.isListNotEmpty(msgs)) {
                    msgMapper.insertList(msgs);//短信保存到数据库

                    //发短信
                    int pageSize = 2000;//手机号，多个手机号为用半角 , 分开，如13899999999,13688888888(最多2000个，必填)
                    Map<String, List<TMsg>> mcollect = msgs.stream().collect(Collectors.groupingBy(TMsg::getMsgtxt
                            , LinkedHashMap::new, Collectors.toList()));
                    for (Map.Entry<String, List<TMsg>> entry : mcollect.entrySet()) {
                        List<TMsg> list = entry.getValue();
                        String msgtxt = list.get(0).getMsgtxt();
                        for (int i = 0; i < list.size(); i += pageSize) {
                            ZtMsgVo vo = new ZtMsgVo();
                            String userphone = list.stream().skip(i).limit(pageSize)
                                                   .map(TMsg::getUserphone).collect(Collectors.joining(","));
                            vo.setMobile(userphone);
                            vo.setContent(msgtxt);
                            SMSSender.sendSms(vo);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("批量添加通知和短信失败：{}", e.getMessage());
        }
    }

    //批量添加通知和短信（发布考试用）
    @Async("asyncPoolTaskExecutor")
    public void batchSave2(ExamVo examVo, List<UserVo> students) {
        Integer notice = examVo.getNotice();//是否发送通知1发送2不发送
        Integer msg = examVo.getMsg();//是否发送短信1发送2不发送
        String examcomm = examVo.getExamcomm();
        Integer createid = examVo.getHandleid();
        Integer examid = examVo.getExamid();
        String examname = examVo.getExamname();
        Integer schoolid = examVo.getSchoolid();
        Integer gradeid = examVo.getGradeid();
        try {
            List<TNotice> noticeList = new ArrayList<>();
            List<TNoticeUser> users = new ArrayList<>();
            List<TMsg> msgList = new ArrayList<>();
            String noticetitle = examname + "-考试公告";
            List<Map> classes = eClassMapper.listByExamId(examid);
            String classids = classes.stream().map(c -> c.get("classid").toString()).collect(Collectors.joining(","));
            List<UserVo> teachers = userMapper.listTeacherByClassIds(classids);//获取考试班级任教老师
            if (notice == 1) {
                for (UserVo t : teachers) {
                    TNoticeUser nt = new TNoticeUser();
                    nt.setUserid(t.getUserid());
                    nt.setGradeid(gradeid);
                    nt.setSubjectid(t.getSubjectid());
                    users.add(nt);
                }

                for (UserVo student : students) {
                    TNoticeUser nu = new TNoticeUser();
                    nu.setUserid(student.getUserid());
                    nu.setGradeid(gradeid);
                    nu.setClassid(student.getClassid());
                    users.add(nu);
                }

                TNotice n2 = new TNotice();
                n2.setNoticetitle(noticetitle);
                n2.setNoticecontent(examcomm);
                n2.setNoticetype(1);
                n2.setUsers(users);
                noticeList.add(n2);
            }
            if (msg == 1) {
                String msgtxt = noticetitle + "\n" + ExamUtil.htmlRemoveTag(examcomm);
                List<String> userphones = new ArrayList<>();
                for (UserVo student : students) {
                    if (N_Utils.isNotEmpty(student.getUserphone())) {
                        String sUserphone = student.getUserphone();
                        userphones.add(sUserphone);
                    }
                }
                for (String userphone : userphones) {
                    TMsg m = new TMsg();
                    m.setMsgtxt(msgtxt);
                    m.setUserphone(userphone);
                    msgList.add(m);
                }
                List<String> list = new ArrayList<>();
                for (UserVo s : teachers) {
                    String sUserphone = s.getUserphone();
                    if (N_Utils.isNotEmpty(sUserphone)) {
                        list.add(sUserphone);
                    }
                }
                userphones = list;
                for (String userphone : userphones) {
                    TMsg m = new TMsg();
                    m.setMsgtxt(msgtxt);
                    m.setUserphone(userphone);
                    msgList.add(m);
                }
            }
            Integer createtime = N_Utils.getSecondTimestamp();
            if (N_Utils.isListNotEmpty(noticeList)) {//通知
                noticeList.forEach(n -> {
                    n.setNoticetxt(n.getNoticecontent().replaceAll("<[.[^>]]*>", ""));
                    n.setCreatetime(createtime);
                    n.setCreateid(createid);
                    n.setSchoolid(schoolid);
                });
                noticeMapper.insertList(noticeList);

                List<TNoticeUser> nteacherList = new ArrayList<>();
                noticeList.forEach(n -> {
                    Integer noticeid = n.getId();
                    List<TNoticeUser> cteachers = n.getUsers().stream().distinct().collect(Collectors.toList());
                    cteachers.forEach(t -> {
                        t.setNoticeid(noticeid);
                        t.setReaded(0);
                        t.setCreatetime(createtime);
                    });
                    nteacherList.addAll(cteachers);
                });

                if (N_Utils.isListNotEmpty(nteacherList)) noticeUserMapper.insertList(users);//通知教师关联信息
            }

            if (N_Utils.isListNotEmpty(msgList)) {//短信
                List<TMsg> msgs = new ArrayList<>();
                for (TMsg m : msgList) {
                    m.setCreatetime(createtime);
                    msgs.add(m);
                }
                if (N_Utils.isListNotEmpty(msgs)) {
                    msgMapper.insertList(msgs);//短信保存到数据库

                    //发短信
                    int pageSize = 2000;//手机号，多个手机号为用半角 , 分开，如13899999999,13688888888(最多2000个，必填)
                    Map<String, List<TMsg>> mcollect = msgs.stream().collect(Collectors.groupingBy(TMsg::getMsgtxt
                            , LinkedHashMap::new, Collectors.toList()));
                    for (Map.Entry<String, List<TMsg>> entry : mcollect.entrySet()) {
                        List<TMsg> list = entry.getValue();
                        String msgtxt = list.get(0).getMsgtxt();
                        for (int i = 0; i < list.size(); i += pageSize) {
                            ZtMsgVo vo = new ZtMsgVo();
                            String userphone = list.stream().skip(i).limit(pageSize)
                                                   .map(TMsg::getUserphone).collect(Collectors.joining(","));
                            vo.setMobile(userphone);
                            vo.setContent(msgtxt);
                            SMSSender.sendSms(vo);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("批量添加通知和短信（发布考试用）失败：{}", e.getMessage());
        }
    }
}
