package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.FormalParentsStudent;
import com.ruoyi.common.core.domain.entity.FormalTeacherClass;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.domain.XiakeConfig;
import com.ruoyi.system.mapper.SysConfigMapper;
import com.ruoyi.system.mapper.XiakeConfigMapper;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.IAppletService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: tjf
 * @Date: 2023/5/25 11:48
 * @Describe:
 */
@Service
public class AppletServiceImpl implements IAppletService {
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private XiakeConfigMapper xiakeConfigMapper;

    @Autowired
    private SysConfigMapper configMapper;
    @Autowired
    private RegisterParentsStudentMapper registerParentsStudentMapper;

    @Autowired
    private CourseChangeMapper courseChangeMapper;

    @Autowired
    private FormalTeacherClassMapper formalTeacherClassMapper;

    @Autowired
    private RegisterTeacherMapper registerTeacherMapper;

    @Autowired
    private XiaoyuanNoticeMapper xiaoyuanNoticeMapper;

    /**
     * 老师准备下课按钮
     *
     * @param formalTeacherClass
     */
    @Override
    public AjaxResult xiake(FormalTeacherClass formalTeacherClass) {
        String key = formalTeacherClass.getSchoolId() + ":" + formalTeacherClass.getClassId();
        //key = 学校id:班级id
        //Redis根据key键，查询对应的值
        String value = redisCache.getCacheObject(key);
        if ("2".equals(formalTeacherClass.getType())) {
            if (value.contains("time")) {
                return AjaxResult.error("未准备放学,请勿点击延迟放学");
            } else {
                //延迟放学
                String[] split = value.split(":");
                //下课时间
                String xiakeTime = split[1];
                //获取参数中默认下课时间
                XiakeConfig config = new XiakeConfig();
                config.setConfigKey(formalTeacherClass.getClassId()+":2");
                XiakeConfig retConfig = xiakeConfigMapper.selectConfig(config);
                //延迟下课的默认值
                String configValue = retConfig.getConfigValue();
                SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = null;
                try {
                    date = sdf.parse(xiakeTime);
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(date);
                    calendar.add(Calendar.MINUTE, Integer.parseInt(configValue));
                    redisCache.setCacheObject(key, value);
                    return AjaxResult.success("延迟放学成功");
                } catch (ParseException e) {
                    return AjaxResult.error("延迟放学失败");
                }
            }
        }
        if ("1".equals(formalTeacherClass.getType())) {
            if (!value.contains("time")) {
                return AjaxResult.error("请勿重复点击");
            }
            //value = 班级名称:放学时间
            //获取当前时间
            Calendar nowTime = Calendar.getInstance();
            //获取参数中默认下课时间
            XiakeConfig config = new XiakeConfig();
            config.setConfigKey(formalTeacherClass.getClassId()+":1");
            XiakeConfig retConfig = xiakeConfigMapper.selectConfig(config);
            String configValue = retConfig.getConfigValue();
            nowTime.add(Calendar.MINUTE, Integer.parseInt(configValue));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            value = value.replace("time", sdf.format(nowTime.getTime()));
            redisCache.setCacheObject(key, value);
        }
        return AjaxResult.success();
    }

    /**
     * 家长获取下课时间
     * @param formalTeacherClass
     * @return
     */
    @Override
    public AjaxResult xiaKeTime(FormalTeacherClass formalTeacherClass) {
        String key = formalTeacherClass.getSchoolId() + ":" + formalTeacherClass.getClassId();
        //key = 学校id:班级id
        //Redis根据key键，查询对应的值
        String value = redisCache.getCacheObject(key);
        String[] split = value.split(":");
        //下课时间
        String xiakeTime = split[1];
        return AjaxResult.success(xiakeTime);
    }

    @Override
    public AjaxResult index(FormalTeacherClass formalTeacherClass) {
        Map<String, Object> map = new HashMap<>(3);
        map.put("all", 0);
        Collection<String> keys = redisCache.keys(formalTeacherClass.getSchoolId() + "*");
        if (keys != null && keys.size() > 0) {
            map.put("all", keys.size());
            map.put("n", 0);
            map.put("y", 0);
            int n = 0;
            for (String key : keys) {
                //Redis根据key键，查询对应的值
                String value = redisCache.getCacheObject(key);
                //value = 班级名称:放学时间
                //判断有多少放学时间是time,占位符
                String[] split = value.split(":");
                String time = split[1];
                if ("time".equals(time)) {
                    n = n + 1;
                }
            }
            if (n > 0) {
                map.put("n", n);
                int y = keys.size() - n;
                map.put("y", Math.max(y, 0));
            }
        }
        return AjaxResult.success(map);
    }

    @Override
    public AjaxResult indexList(FormalTeacherClass formalTeacherClass) {
        List<Map<String, Object>> list = new ArrayList<>();
        Collection<String> keys = redisCache.keys(formalTeacherClass.getSchoolId() + "*");
        if (keys != null && keys.size() > 0) {
            for (String key : keys) {
                String value = redisCache.getCacheObject(key);
                //value = 班级名称:放学时间
                String[] split = value.split(":");
                Map<String, Object> map = new HashMap<>();
                map.put("className", split[0]);
                map.put("time", split[1]);
                list.add(map);
            }
        }
        return AjaxResult.success(list);
    }

    @Override
    public AjaxResult pcStatistics() {
        Map<String, Object> map = new HashMap<>();
        //获取当前月第一天
        String monthFirst = DateUtils.timeMonthFirst();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        List<SysRole> roles = user.getRoles();
        boolean blt = false;
        boolean bls = false;
        for (SysRole role : roles) {
            if ("teacher".equals(role.getRoleKey())) {
                blt = true;
            }
            if ("school".equals(role.getRoleKey())) {
                bls = true;
            }
        }
        //账号
        int tzhysh = 0;
        int tzhwsh = 0;
        //调课
        int ttkysh = 0;
        int ttkwsh = 0;
        Map<String,Object> map1 = new HashMap<>();
        Map<String,Object> map2 = new HashMap<>();
        Map<String,Object> map3 = new HashMap<>();

        //计算本人
        XiaoyuanNotice xiaoyuanNotice = new XiaoyuanNotice();
        xiaoyuanNotice.setSenderId(String.valueOf(user.getUserId()));
        List<XiaoyuanNotice> xiaoyuanNoticeList = xiaoyuanNoticeMapper.selectXiaoyuanNoticeMyList(xiaoyuanNotice);
        int xwsl = 0;
        if(xiaoyuanNoticeList!=null && xiaoyuanNoticeList.size()>0){
            xwsl = xiaoyuanNoticeList.size();
        }
        map.put("xwsl",xwsl);

        map1.put("zhysh",tzhysh);
        map1.put("zhwsh",tzhwsh);
        map.put("byzhsh",map1);
        map2.put("tkysh",ttkysh);
        map2.put("tkwsh",ttkwsh);
        map.put("bytksh",map2);

        //老师
        if(blt){
            //获取老师所属班级
            FormalTeacherClass formalTeacherClass = new FormalTeacherClass();
            formalTeacherClass.setTeacherId(user.getUserId());
            List<FormalTeacherClass> formalTeacherClasses = formalTeacherClassMapper.selectFormalTeacherClassList(formalTeacherClass);
            List<Long> classIds = formalTeacherClasses.stream().map(FormalTeacherClass::getClassId).collect(Collectors.toList());
            //查询本月家长的审核数据
            List<RegisterParentsStudent> registerParentsStudentList = registerParentsStudentMapper.selectRegisterParentsStudentListByTime(monthFirst,classIds);
            if(registerParentsStudentList!=null && registerParentsStudentList.size()>0){
                for (RegisterParentsStudent registerParentsStudent : registerParentsStudentList) {
                    if("1".equals(registerParentsStudent.getIsPass())){
                        tzhwsh++;
                    }else{
                        tzhysh++;
                    }
                }
            }
            //查询本月调课审核
            List<CourseChange> courseChangeList = courseChangeMapper.selectCourseChangeListByTime(monthFirst,user.getUserId(),0L);
            if(courseChangeList!=null && courseChangeList.size()>0){
                for (CourseChange courseChange : courseChangeList) {
                    if("1".equals(courseChange.getIsPass())){
                        ttkwsh++;
                    }else{
                        ttkysh++;
                    }
                }
            }
            map1.put("zhysh",tzhysh);
            map1.put("zhwsh",tzhwsh);
            map.put("byzhsh",map1);
            map2.put("tkysh",ttkysh);
            map2.put("tkwsh",ttkwsh);
            map.put("bytksh",map2);

        }


        //学校
        //账号
        int szhysh = 0;
        int szhwsh = 0;
        //调课
        int stkysh = 0;
        int stkwsh = 0;
        if(bls){
            //查询本月老师的审核数据
            List<RegisterTeacher> registerTeacherList = registerTeacherMapper.selectRegisterTeacherListByTime(monthFirst,user.getDeptId());
            if(registerTeacherList!=null && registerTeacherList.size()>0){
                for (RegisterTeacher registerTeacher : registerTeacherList) {
                    if("1".equals(registerTeacher.getIsPass())){
                        szhysh++;
                    }else{
                        szhwsh++;
                    }
                }
            }
            //查询本月学校的调课审核
            List<CourseChange> courseChangeList = courseChangeMapper.selectCourseChangeListByTime(monthFirst,0L,user.getDeptId());
            if(courseChangeList!=null && courseChangeList.size()>0){
                for (CourseChange courseChange : courseChangeList) {
                    if("1".equals(courseChange.getIsPass())){
                        stkysh++;
                    }else{
                        stkwsh++;
                    }
                }
            }

            map1.put("zhysh",szhysh);
            map1.put("zhwsh",szhwsh);
            map.put("byzhsh",map1);
            map2.put("tkysh",stkysh);
            map2.put("tkwsh",stkwsh);
            map.put("bytksh",map2);
        }
        //两个都有

        if(blt && bls){

            //账号
            int zzhysh = tzhysh + szhysh;
            int zzhwsh = tzhwsh + szhwsh;
            //调课
            int ztkysh =  stkysh;
            int ztkwsh =  stkwsh;

            map1.put("zhysh",zzhysh);
            map1.put("zhwsh",zzhwsh);
            map.put("byzhsh",map1);
            map2.put("tkysh",ztkysh);
            map2.put("tkwsh",ztkwsh);
            map.put("bytksh",map2);

        }
        return AjaxResult.success(map);
    }
}
