package com.xhkjedu.sexam.service.notice;

import com.xhkjedu.sexam.mapper.notice.MsgMapper;
import com.xhkjedu.sexam.mapper.notice.NoticeClassMapper;
import com.xhkjedu.sexam.mapper.notice.NoticeMapper;
import com.xhkjedu.sexam.mapper.notice.NoticeSchoolMapper;
import com.xhkjedu.sexam.mapper.notice.NoticeTeacherMapper;
import com.xhkjedu.sexam.mapper.system.UserMapper;
import com.xhkjedu.sexam.model.notice.TMsg;
import com.xhkjedu.sexam.model.notice.TNotice;
import com.xhkjedu.sexam.model.notice.TNoticeClass;
import com.xhkjedu.sexam.model.notice.TNoticeSchool;
import com.xhkjedu.sexam.model.notice.TNoticeTeacher;
import com.xhkjedu.sexam.utils.SMSSender;
import com.xhkjedu.sexam.vo.exam.ZtMsgVo;
import com.xhkjedu.sexam.vo.system.UserVo;
import com.xhkjedu.utils.N_Utils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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
public class NoticeService {
    @Resource
    private NoticeMapper noticeMapper;
    @Resource
    private NoticeTeacherMapper noticeTeacherMapper;
    @Resource
    private NoticeClassMapper noticeClassMapper;
    @Resource
    private NoticeSchoolMapper noticeSchoolMapper;
    @Resource
    private MsgMapper msgMapper;
    @Resource
    private UserMapper userMapper;

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

            List<TNoticeTeacher> teacherList = new ArrayList<>();
            List<TNoticeClass> classList = new ArrayList<>();
            List<TNoticeSchool> schoolList = new ArrayList<>();
            noticeList.forEach(n -> {
                Integer noticeid = n.getId();
                List<TNoticeTeacher> teachers = n.getTeachers().stream().distinct().collect(Collectors.toList());
                teachers.forEach(t -> {
                    t.setNoticeid(noticeid);
                    t.setReaded(0);
                    t.setCreatetime(createtime);
                    t.setSchoolid(schoolid);
                });
                teacherList.addAll(teachers);

                List<TNoticeClass> classes = n.getClasses();
                classes.forEach(c -> {
                    c.setNoticeid(noticeid);
                    c.setCreateid(createid);
                    c.setCreatetime(createtime);
                });
                classList.addAll(classes);

                TNoticeSchool ns = new TNoticeSchool();
                ns.setNoticeid(noticeid);
                ns.setSchoolid(schoolid);
                ns.setCreateid(createid);
                ns.setCreatetime(createtime);
                schoolList.add(ns);
            });

            if (N_Utils.isListNotEmpty(teacherList)) noticeTeacherMapper.insertList(teacherList);//通知教师关联信息
            if (N_Utils.isListNotEmpty(classList)) noticeClassMapper.insertList(classList);//通知班级关联信息
            if (N_Utils.isListNotEmpty(schoolList)) noticeSchoolMapper.insertList(schoolList);//通知学校关联信息
        }

        if (N_Utils.isListNotEmpty(msgList)) {//短信
            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(m -> m.getUserid()).distinct().collect(Collectors.toList());
                List<UserVo> users = userMapper.listPhoneByUserIds(userids);//根据用户ids查找手机号
                Map<Integer, TMsg> msgMap = msgList.stream().collect(Collectors.toMap(m -> m.getUserid(), m -> m));
                for (int i = 0; i < users.size(); i++) {
                    UserVo u = users.get(i);
                    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);//短信保存到数据库

                //发短信
                Integer pageSize = 2000;//手机号，多个手机号为用半角 , 分开，如13899999999,13688888888(最多2000个，必填)
                Map<String, List<TMsg>> mcollect = msgs.stream().collect(Collectors.groupingBy(s -> s.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(s -> s.getUserphone()).collect(Collectors.joining(","));
                        vo.setMobile(userphone);
                        vo.setContent(msgtxt);
                        SMSSender.sendSms(vo);
                    }
                }
            }
        }
    }

    //批量添加通知和短信（发布考试用）
    public void batchSave2(List<TNotice> noticeList, List<TMsg> msgList, Integer schoolid, Integer createid) {
        noticeList = null;
        msgList = null;
        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<TNoticeTeacher> teacherList = new ArrayList<>();
            List<TNoticeClass> classList = new ArrayList<>();
            List<TNoticeSchool> schoolList = new ArrayList<>();
            noticeList.forEach(n -> {
                Integer noticeid = n.getId();
                List<TNoticeTeacher> teachers = n.getTeachers().stream().distinct().collect(Collectors.toList());
                teachers.forEach(t -> {
                    t.setNoticeid(noticeid);
                    t.setReaded(0);
                    t.setCreatetime(createtime);
                    t.setSchoolid(schoolid);
                });
                teacherList.addAll(teachers);

                List<TNoticeClass> classes = n.getClasses();
                classes.forEach(c -> {
                    c.setNoticeid(noticeid);
                    c.setCreateid(createid);
                    c.setCreatetime(createtime);
                });
                classList.addAll(classes);

                TNoticeSchool ns = new TNoticeSchool();
                ns.setNoticeid(noticeid);
                ns.setSchoolid(schoolid);
                ns.setCreateid(createid);
                ns.setCreatetime(createtime);
                schoolList.add(ns);
            });

            if (N_Utils.isListNotEmpty(teacherList)) noticeTeacherMapper.insertList(teacherList);//通知教师关联信息
            if (N_Utils.isListNotEmpty(classList)) noticeClassMapper.insertList(classList);//通知班级关联信息
            if (N_Utils.isListNotEmpty(schoolList)) noticeSchoolMapper.insertList(schoolList);//通知学校关联信息
        }

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

                //发短信
                Integer pageSize = 2000;//手机号，多个手机号为用半角 , 分开，如13899999999,13688888888(最多2000个，必填)
                Map<String, List<TMsg>> mcollect = msgs.stream().collect(Collectors.groupingBy(s -> s.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(s -> s.getUserphone()).collect(Collectors.joining(","));
                        vo.setMobile(userphone);
                        vo.setContent(msgtxt);
                        SMSSender.sendSms(vo);
                    }
                }
            }
        }
    }
}
