package com.srs.dormitory.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.srs.common.core.domain.AjaxResult;
import com.srs.common.core.domain.entity.SysUser;
import com.srs.common.utils.DateUtils;
import com.srs.comprehensive.domain.CphMsg;
import com.srs.comprehensive.mapper.CphMsgMapper;
import com.srs.comprehensive.service.impl.CphMsgServiceImpl;
import com.srs.dormitory.domain.DmsCheckLog;
import com.srs.dormitory.domain.Dto.DmsSearch;
import com.srs.dormitory.domain.SrsDormitoryStudent;
import com.srs.dormitory.mapper.DmsCheckLogMapper;
import com.srs.dormitory.mapper.DmsStuDailyMapper;
import com.srs.dormitory.mapper.SrsDormitoryStudentMapper;
import com.srs.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.srs.dormitory.mapper.DmsDormitoryCheckMapper;
import com.srs.dormitory.domain.DmsDormitoryCheck;
import com.srs.dormitory.service.IDmsDormitoryCheckService;

import static com.srs.common.utils.DateUtils.getNowDate;
import static com.srs.common.utils.SecurityUtils.getUserId;
import static com.srs.common.utils.SecurityUtils.getUsername;

/**
 * 查寝管理Service业务层处理
 *
 * @author LSD
 * @date 2024-12-06
 */
@Service
public class DmsDormitoryCheckServiceImpl extends ServiceImpl<DmsDormitoryCheckMapper,DmsDormitoryCheck> implements IDmsDormitoryCheckService {
    @Autowired
    private DmsDormitoryCheckMapper dmsDormitoryCheckMapper;

    @Autowired
    public CphMsgMapper _msgMapper;

    @Autowired
    public SrsDormitoryStudentMapper _stuDormMapper;
    @Autowired
    public SysUserMapper _sysUserMapper;
    @Autowired
    private DmsStuDailyMapper dmsStuDailyMapper;
    @Autowired
    public CphMsgServiceImpl _cphMsgService;
    @Autowired
    public DmsCheckLogServiceImpl _dmsCheckLogService;


    @Override
    public AjaxResult sendMail(Long checkId){
        try{
            DmsDormitoryCheck record = dmsDormitoryCheckMapper.selectById(checkId);
            if(record == null){
                return AjaxResult.error("查寝记录不存在");
            }

            Long dormitoryId = record.getDormitoryId();

            QueryWrapper<SrsDormitoryStudent> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("dormitory_id",dormitoryId);
            List<SrsDormitoryStudent> dormStuList = _stuDormMapper.selectList(queryWrapper);

            if(dormStuList.size() == 0){
                return AjaxResult.error("该寝室没有学生");
            }

            Set<String> stuSet = new HashSet<>();
            for(SrsDormitoryStudent stu : dormStuList){
                stuSet.add(stu.getStuNo());
            }

            QueryWrapper<SysUser> userQuery = new QueryWrapper<>();
            userQuery.in("user_name",stuSet);
            List<SysUser> stuUsers = _sysUserMapper.selectList(userQuery);

            List<CphMsg> addList = new ArrayList<>();
            for(SysUser stu : stuUsers){
                CphMsg msg = new CphMsg();
                msg.setSender(getUserId());
                SysUser user = stuUsers.stream().filter(u -> u.getUserName().equals(stu.getUserName())).findFirst().orElse(null);
                if(user == null){
                    continue;
                }
                msg.setReceiver(user.getUserId());
                msg.setCreateTime(getNowDate());
                msg.setCreateBy(getUsername());
                msg.setContent("您好，您有一条新的查寝记录待处理，请及时查看。");
                addList.add(msg);
            }


            List<Map<String,Object>> unCardStudent = dmsStuDailyMapper.listStudent(stuSet);

            Set<String> teacherSet = new HashSet<String>();
            unCardStudent.forEach(map -> teacherSet.add(map.get("t_no").toString()));
            QueryWrapper<SysUser> teacherQuery = new QueryWrapper<>();
            teacherQuery.in("user_name",teacherSet);
            List<SysUser> unCardTeachers = _sysUserMapper.selectList(teacherQuery);

            for(String map : teacherSet){
                CphMsg cphMsg = new CphMsg();
                cphMsg.setCreateTime(getNowDate());
                cphMsg.setCreateBy(getUsername());
                cphMsg.setSender(getUserId());
                SysUser user = unCardTeachers.stream().filter(u -> u.getUserName().equals(map)).findFirst().orElse(null);
                if(user == null){
                    continue;
                }
                cphMsg.setReceiver(user.getUserId());
                List<Map<String,Object>> stuList = unCardStudent.stream().filter(s -> s.get("t_no").equals(map)).collect(Collectors.toList());
                String stuNames = stuList.stream().map(s -> s.get("stu_name").toString()).collect(Collectors.joining(","));
                cphMsg.setContent("您的学生"+stuNames+"有查寝记录，请及时查看。");
                addList.add(cphMsg);
            }

            List<Map<String,Object>> xwList = dmsStuDailyMapper.listAllXw();

            for(Map<String,Object> map : xwList){
                CphMsg cphMsg = new CphMsg();
                cphMsg.setCreateTime(getNowDate());
                cphMsg.setCreateBy(getUsername());
                cphMsg.setSender(getUserId());
                cphMsg.setReceiver(Long.parseLong(map.get("user_id").toString()));

                List<Map<String,Object>> stuList = unCardStudent.stream().filter(
                        x-> (x.get("dept_name").toString() ).equals(map.get("dept_name").toString())
                ).collect(Collectors.toList());

                if(stuList.size() == 0){
                    continue;
                }
                String stuNames = stuList.stream().map(s -> s.get("stu_name").toString()).collect(Collectors.joining(","));
                cphMsg.setContent("您的学生"+stuNames+"有查寝记录，请及时查看。");
                addList.add(cphMsg);
            }
            boolean res = _cphMsgService.saveBatch(addList);
            if(!res){
                throw new Exception("发送失败");
            }

            List<DmsCheckLog> logList = new ArrayList<>();
            for(String stuNo : stuSet) {
                DmsCheckLog log = new DmsCheckLog();
                log.setCheckId(checkId);
                log.setStuNo(stuNo);
                log.setCreateTime(getNowDate());
                logList.add(log);
            }
            boolean res1 = _dmsCheckLogService.saveBatch(logList);
            if(!res1){
                throw new Exception("添加查寝推送记录失败");
            }

            return AjaxResult.success();
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }


    @Override
    public List<Map<String,Object>> listDorm(DmsSearch param){
        return dmsDormitoryCheckMapper.listDorm(param);
    }

    /**
     * 查询查寝管理
     *
     * @param checkId 查寝管理主键
     * @return 查寝管理
     */
    @Override
    public DmsDormitoryCheck selectDmsDormitoryCheckByCheckId(Long checkId) {
        return dmsDormitoryCheckMapper.selectDmsDormitoryCheckByCheckId(checkId);
    }

    /**
     * 查询查寝管理列表
     *
     * @param dmsDormitoryCheck 查寝管理
     * @return 查寝管理
     */
    @Override
    public List<DmsDormitoryCheck> selectDmsDormitoryCheckList(DmsDormitoryCheck dmsDormitoryCheck) {
        return dmsDormitoryCheckMapper.selectDmsDormitoryCheckList(dmsDormitoryCheck);
    }

    /**
     * 新增查寝管理
     *
     * @param dmsDormitoryCheck 查寝管理
     * @return 结果
     */
    @Override
    public int insertDmsDormitoryCheck(DmsDormitoryCheck dmsDormitoryCheck) {
        DmsSearch dmsSearch = new DmsSearch();
        dmsSearch.dormitoryId = dmsDormitoryCheck.getDormitoryId();
        List<Map<String,Object>> dormList = dmsDormitoryCheckMapper.listDorm(dmsSearch);
        if(dormList.size() == 0){
            return 0;
        }
        String dormitoryNumber = dormList.get(0).get("park_name").toString()
                +dormList.get(0).get("building_name").toString()
                +dormList.get(0).get("room_no").toString();
        dmsDormitoryCheck.setDormitoryNumber(dormitoryNumber);
        dmsDormitoryCheck.setCreateTime(DateUtils.getNowDate());
        return dmsDormitoryCheckMapper.insertDmsDormitoryCheck(dmsDormitoryCheck);
    }

    /**
     * 修改查寝管理
     *
     * @param dmsDormitoryCheck 查寝管理
     * @return 结果
     */
    @Override
    public int updateDmsDormitoryCheck(DmsDormitoryCheck dmsDormitoryCheck) {
        dmsDormitoryCheck.setUpdateTime(DateUtils.getNowDate());
        return dmsDormitoryCheckMapper.updateDmsDormitoryCheck(dmsDormitoryCheck);
    }

    /**
     * 批量删除查寝管理
     *
     * @param checkIds 需要删除的查寝管理主键
     * @return 结果
     */
    @Override
    public int deleteDmsDormitoryCheckByCheckIds(Long[] checkIds) {
        return dmsDormitoryCheckMapper.deleteDmsDormitoryCheckByCheckIds(checkIds);
    }

    /**
     * 删除查寝管理信息
     *
     * @param checkId 查寝管理主键
     * @return 结果
     */
    @Override
    public int deleteDmsDormitoryCheckByCheckId(Long checkId) {
        return dmsDormitoryCheckMapper.deleteDmsDormitoryCheckByCheckId(checkId);
    }
}
