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.comprehensive.domain.CphMsg;
import com.srs.comprehensive.mapper.CphMsgMapper;
import com.srs.comprehensive.service.impl.CphMsgServiceImpl;
import com.srs.dormitory.domain.SrsDormitoryStudent;
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.DmsStuDailyMapper;
import com.srs.dormitory.domain.DmsStuDaily;
import com.srs.dormitory.service.IDmsStuDailyService;

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 srs
 * @date 2024-12-21
 */
@Service
public class DmsStuDailyServiceImpl extends ServiceImpl<DmsStuDailyMapper,DmsStuDaily> implements IDmsStuDailyService {
    @Autowired
    private DmsStuDailyMapper dmsStuDailyMapper;
    @Autowired
    public SrsDormitoryStudentMapper _srsDormitoryStudentMapper;

    @Autowired
    public SysUserMapper _sysUserMapper;
    @Autowired
    public CphMsgMapper _cphMsgMapper;
    @Autowired
    public CphMsgServiceImpl _cphMsgService;

    @Override
    public List<Map<String, Object>> countDeptCard(){
        return dmsStuDailyMapper.countDeptCard();
    }

    @Override
    public List<String> listLeaveLog(){
        return dmsStuDailyMapper.listLeaveLog();
    }

    @Override
    public List<Map<String, Object>> countDeptShixi(){
        return dmsStuDailyMapper.countDeptShixi();
    }

    @Override
    public List<Map<String, Object>> countDeptLeave(){
        return dmsStuDailyMapper.countDeptLeave();
    }

    @Override
    public void sendTask(){
        DmsStuDaily dmsStuDaily = new DmsStuDaily();
        dmsStuDaily.setSubmitTime(getNowDate());
        List<Map<String,Object>> unCardList = dmsStuDailyMapper.listUnCard(dmsStuDaily);

        Set<String> stuSet = new HashSet<String>();
        unCardList.forEach(map -> stuSet.add(map.get("stu_no").toString()));

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

        List<CphMsg> cphMsgs = new ArrayList<CphMsg>();
        for(Map<String,Object> map : unCardList){
            CphMsg cphMsg = new CphMsg();
            cphMsg.setId(null);
            cphMsg.setCreateTime(getNowDate());
            cphMsg.setCreateBy(getUsername());
            cphMsg.setSender(getUserId());
            SysUser user = unCardUsers.stream().filter(u -> u.getUserName().equals(map.get("stu_no").toString())).findFirst().orElse(null);
            if(user == null){
                continue;
            }
            cphMsg.setReceiver(user.getUserId());
            cphMsg.setContent("您今日还没有打卡，请按时打卡，谢谢！");
            cphMsgs.add(cphMsg);
        }

        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+"还没有打卡，记得提醒他们打卡，谢谢！");
            cphMsgs.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+"还没有打卡，记得提醒他们打卡，谢谢！");
            cphMsgs.add(cphMsg);

        }
        _cphMsgService.saveBatch(cphMsgs);
    }

    @Override
    public AjaxResult sendMail(){
        try{
            DmsStuDaily dmsStuDaily = new DmsStuDaily();
            dmsStuDaily.setSubmitTime(getNowDate());
            List<Map<String,Object>> unCardList = dmsStuDailyMapper.listUnCard(dmsStuDaily);

            Set<String> stuSet = new HashSet<String>();
            unCardList.forEach(map -> stuSet.add(map.get("stu_no").toString()));

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

            List<CphMsg> cphMsgs = new ArrayList<CphMsg>();
            for(Map<String,Object> map : unCardList){
                CphMsg cphMsg = new CphMsg();
                cphMsg.setId(null);
                cphMsg.setCreateTime(getNowDate());
                cphMsg.setCreateBy(getUsername());
                cphMsg.setSender(getUserId());
                SysUser user = unCardUsers.stream().filter(u -> u.getUserName().equals(map.get("stu_no").toString())).findFirst().orElse(null);
                if(user == null){
                    continue;
                }
                cphMsg.setReceiver(user.getUserId());
                cphMsg.setContent("您今日还没有打卡，请按时打卡，谢谢！");
                cphMsgs.add(cphMsg);
            }

            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+"还没有打卡，记得提醒他们打卡，谢谢！");
                cphMsgs.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+"还没有打卡，记得提醒他们打卡，谢谢！");
                cphMsgs.add(cphMsg);

            }

            boolean res = _cphMsgService.saveBatch(cphMsgs);
            if(!res){
                throw new Exception("发送失败");
            }
            return AjaxResult.success();
        }catch(Exception ex){
            return AjaxResult.error(ex.getMessage());
        }
    }

    @Override
    public List<DmsStuDaily> listView(DmsStuDaily param){
        return dmsStuDailyMapper.listToday(param);
    }

    @Override
    public AjaxResult doCard(DmsStuDaily param){
        try{
            QueryWrapper<SrsDormitoryStudent> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("stu_no",param.getStuNo());
            SrsDormitoryStudent srsDormitoryStudent = _srsDormitoryStudentMapper.selectOne(queryWrapper);
            if(srsDormitoryStudent == null){
                return AjaxResult.error("学生宿舍不存在");
            }

            //判断是否已经打卡
            DmsStuDaily searchTodayParams = new DmsStuDaily();
            searchTodayParams.submitTime = getNowDate();
            searchTodayParams.stuNo = param.getStuNo();
            List<DmsStuDaily> todayList = dmsStuDailyMapper.listToday(searchTodayParams);
            if(todayList.size() > 0){
                return AjaxResult.error("今天已经打过卡了");
            }

            param.dormitoryId = srsDormitoryStudent.getDormitoryId();
            param.submitTime = getNowDate();

            int res = dmsStuDailyMapper.insert(param);
            if(res == 0){
                throw new Exception("新增学生宿舍打卡失败");
            }

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

    @Override
    public Map<String, Object> getStuDorm(String stuNo){
        return dmsStuDailyMapper.getStuDorm(stuNo);
    }

    /**
     * 查询学生宿舍打卡
     *
     * @param id 学生宿舍打卡主键
     * @return 学生宿舍打卡
     */
    @Override
    public DmsStuDaily selectDmsStuDailyById(Long id) {
        return dmsStuDailyMapper.selectDmsStuDailyById(id);
    }

    /**
     * 查询学生宿舍打卡列表
     *
     * @param dmsStuDaily 学生宿舍打卡
     * @return 学生宿舍打卡
     */
    @Override
    public List<DmsStuDaily> selectDmsStuDailyList(DmsStuDaily dmsStuDaily) {
        return dmsStuDailyMapper.selectDmsStuDailyList(dmsStuDaily);
    }

    /**
     * 新增学生宿舍打卡
     *
     * @param dmsStuDaily 学生宿舍打卡
     * @return 结果
     */
    @Override
    public int insertDmsStuDaily(DmsStuDaily dmsStuDaily) {
        return dmsStuDailyMapper.insertDmsStuDaily(dmsStuDaily);
    }

    /**
     * 修改学生宿舍打卡
     *
     * @param dmsStuDaily 学生宿舍打卡
     * @return 结果
     */
    @Override
    public int updateDmsStuDaily(DmsStuDaily dmsStuDaily) {
        return dmsStuDailyMapper.updateDmsStuDaily(dmsStuDaily);
    }

    /**
     * 批量删除学生宿舍打卡
     *
     * @param ids 需要删除的学生宿舍打卡主键
     * @return 结果
     */
    @Override
    public int deleteDmsStuDailyByIds(Long[] ids) {
        return dmsStuDailyMapper.deleteDmsStuDailyByIds(ids);
    }

    /**
     * 删除学生宿舍打卡信息
     *
     * @param id 学生宿舍打卡主键
     * @return 结果
     */
    @Override
    public int deleteDmsStuDailyById(Long id) {
        return dmsStuDailyMapper.deleteDmsStuDailyById(id);
    }
    // 统计已打卡的数据
    @Override
    public int  checkedIn(){
        return  dmsStuDailyMapper.checkedIn();
    }
    // 统计未打卡的数据
    @Override
    public int   notCheckedIn(){
        return  dmsStuDailyMapper.notCheckedIn();
    }
    //统计请假的离校人数
    @Override
    public int  leavScholl(){
        return  dmsStuDailyMapper.leavScholl();
    }
    //统计去实习人数
    @Override
    public  int goLesson(){
        return  dmsStuDailyMapper.goLesson();
    }
    @Override
    public  List<Map<String,Object>>getDeptNames(){
        return  dmsStuDailyMapper.getDeptNames();
    }
}
