package com.ruoyi.system.service.impl.notice;

import java.util.Comparator;
import java.util.List;

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.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.notice.InfoPinglun;
import com.ruoyi.system.domain.notice.XiaoyuanInfo;
import com.ruoyi.system.mapper.FormalParentsStudentMapper;
import com.ruoyi.system.mapper.FormalTeacherClassMapper;
import com.ruoyi.system.mapper.XiaoyuanNoticeMapper;
import com.ruoyi.system.mapper.notice.XiaoyuanInfoMapper;
import com.ruoyi.system.service.notice.IXiaoyuanInfoService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;

import static com.ruoyi.common.constant.CacheConstants.*;
import static com.ruoyi.common.utils.PageUtils.startPage;

/**
 * 校园安全信息Service业务层处理
 * 
 * @author boman
 * @date 2023-08-01
 */
@Service
public class XiaoyuanInfoServiceImpl implements IXiaoyuanInfoService
{
    @Autowired
    private XiaoyuanInfoMapper xiaoyuanInfoMapper;

    @Autowired
    private FormalTeacherClassMapper formalTeacherClassMapper;
    @Autowired
    private FormalParentsStudentMapper formalParentsStudentMapper;

    @Autowired
    private RedisCache redisCache;

    /**
     * 查询校园安全信息
     * 
     * @param infoId 校园安全信息主键
     * @return 校园安全信息
     */
    @Override
    public XiaoyuanInfo selectXiaoyuanInfoByInfoId(Long infoId)
    {
        //已读数量+1
        XiaoyuanInfo xiaoyuanInfo = xiaoyuanInfoMapper.selectXiaoyuanInfoByInfoId(infoId);
        String infoYiDu = xiaoyuanInfo.getInfoYiDu();
        int result = Integer.parseInt(infoYiDu) + 1;
        xiaoyuanInfo.setInfoYiDu(String.valueOf(result));

        //组装评论
        List<InfoPinglun> infoPingLunList = xiaoyuanInfo.getInfoPingLunList();
        if (infoPingLunList != null && infoPingLunList.size() > 0){
            //根据评论类型进行分组评论类型 1:评论 2:回复
            Map<String, List<InfoPinglun>> collect = infoPingLunList.stream().sorted(Comparator.comparing(InfoPinglun::getPingLunTime, Comparator.reverseOrder())).collect(Collectors.groupingBy(InfoPinglun::getInfoPingLunType));
            if (collect != null && collect.size() > 0){
                //所有评论类型的数据
                List<InfoPinglun> infoPingLunListFather = collect.get("1");
                //给他们找自己的回复类型的数据
                if (infoPingLunListFather != null && infoPingLunListFather.size() > 0){
                    for (InfoPinglun infoPinglun : infoPingLunListFather) {
                        List<InfoPinglun> infoPinglunList = collect.get("2");
                        //回复不是空
                        if(infoPinglunList != null && infoPinglunList.size() > 0){
                            Map<Long, List<InfoPinglun>> infoPingLunListParen = infoPinglunList.stream().collect(Collectors.groupingBy(InfoPinglun::getInfoPingLunParent));
                            List<InfoPinglun> infoPinglunListCh = infoPingLunListParen.get(infoPinglun.getInfoPingLunId());
                            if (infoPinglunListCh != null && infoPinglunListCh.size() > 0){
                                infoPinglun.setInfoPingLunList(infoPinglunListCh.stream().sorted(Comparator.comparing(InfoPinglun::getPingLunTime, Comparator.reverseOrder())).collect(Collectors.toList()));
                            }
                        }
                    }
                }
                xiaoyuanInfo.setInfoPingLunList(infoPingLunListFather);
            }
        }
        //获取点赞/分享/这个人是否点赞信息
        Object dianZan = redisCache.getCacheObject(XIAOYUAN_INFO_DIANZAN + xiaoyuanInfo.getInfoId());
        if (ObjectUtils.isNotEmpty(dianZan)){
            xiaoyuanInfo.setInfoDianZan(String.valueOf(dianZan));
        }
        Object zhuanFa = redisCache.getCacheObject(XIAOYUAN_INFO_ZHUANFA+ xiaoyuanInfo.getInfoId());
        if (ObjectUtils.isNotEmpty(zhuanFa)){
            xiaoyuanInfo.setInfoZhuanFa(String.valueOf(zhuanFa));
        }
        Object dianZanUser = redisCache.getCacheObject(XIAOYUAN_INFO_DIANZAN_USER + xiaoyuanInfo.getInfoId());
        xiaoyuanInfo.setIsDianZan("N");
        if (ObjectUtils.isNotEmpty(dianZanUser)){
            xiaoyuanInfo.setIsDianZan("Y");
        }
        xiaoyuanInfoMapper.updateXiaoyuanInfoYiDu(xiaoyuanInfo);
        return xiaoyuanInfo;
    }

    /**
     * 查询校园安全信息列表
     * 
     * @param xiaoyuanInfo 校园安全信息
     * @return 校园安全信息
     */
    @Override
    public List<XiaoyuanInfo> selectXiaoyuanInfoList(XiaoyuanInfo xiaoyuanInfo)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        StringBuilder schoolId = new StringBuilder("0,");
        Map<String, Object> params = xiaoyuanInfo.getParams();
        String role = "admin";
        if (params != null && params.size() > 0) {
            role = (String) params.get("role");
        }
        List<XiaoyuanInfo> xiaoyuanInfoList = new ArrayList<>();
        if ("teacher".equals(role)) {
            FormalTeacherClass formalTeacherClass = new FormalTeacherClass();
            formalTeacherClass.setTeacherId(user.getUserId());
            List<FormalTeacherClass> formalTeacherClasses = formalTeacherClassMapper.selectFormalTeacherClassList(formalTeacherClass);
            if (formalTeacherClasses != null && formalTeacherClasses.size() > 0) {
                for (FormalTeacherClass teacherClass : formalTeacherClasses) {
                    schoolId.append(teacherClass.getClassId()).append(",");
                }
            }
            if (StringUtils.isNotBlank(schoolId.toString())) {
                schoolId = new StringBuilder(schoolId.substring(0, schoolId.length() - 1));
            }
            startPage();
            xiaoyuanInfo.setSchoolId(schoolId.toString());
            xiaoyuanInfoList = xiaoyuanInfoMapper.selectXiaoyuanInfoList(xiaoyuanInfo);
        } else if ("parents".equals(role)) {
            FormalParentsStudent formalParentsStudent = new FormalParentsStudent();
            formalParentsStudent.setParentsId(user.getUserId());
            List<FormalParentsStudent> formalParentsStudents = formalParentsStudentMapper.selectFormalParentsStudentList(formalParentsStudent);
            for (FormalParentsStudent parentsStudent : formalParentsStudents) {
                schoolId.append(parentsStudent.getClassId()).append(",");
            }
            if (StringUtils.isNotBlank(schoolId.toString())) {
                schoolId = new StringBuilder(schoolId.substring(0, schoolId.length() - 1));
            }
            startPage();
            xiaoyuanInfo.setSchoolId(schoolId.toString());
            xiaoyuanInfoList = xiaoyuanInfoMapper.selectXiaoyuanInfoList(xiaoyuanInfo);
        } else if ("admin".equals(role)) {
            startPage();
            xiaoyuanInfoList = xiaoyuanInfoMapper.selectXiaoyuanInfoList(xiaoyuanInfo);
        }
        return xiaoyuanInfoList;
    }

    /**
     * 新增校园安全信息
     * 
     * @param xiaoyuanInfo 校园安全信息
     * @return 结果
     */
    @Transactional
    @Override
    public int insertXiaoyuanInfo(XiaoyuanInfo xiaoyuanInfo)
    {
        Long schoolId = SecurityUtils.getLoginUser().getDeptId();
        xiaoyuanInfo.setSchoolId(String.valueOf(schoolId));
        xiaoyuanInfo.setCreateBy(String.valueOf(SecurityUtils.getLoginUser().getUser().getUserId()));
        xiaoyuanInfo.setCreateTime(DateUtils.getNowDate());
        int rows = xiaoyuanInfoMapper.insertXiaoyuanInfo(xiaoyuanInfo);
        insertInfoPinglun(xiaoyuanInfo);
        return rows;
    }

    /**
     * 新增校园安全信息评论
     * @param infoPinglun
     * @return
     */
    @Override
    public int insertInfoPingLun(InfoPinglun infoPinglun) {
        List<InfoPinglun> infoPingLunList = new ArrayList<>();
        infoPingLunList.add(infoPinglun);
        return xiaoyuanInfoMapper.batchInfoPingLun(infoPingLunList);
    }

    /**
     * 删除评论
     * @param infoPinglun
     * @return
     */
    @Override
    public int deletePingLun(InfoPinglun infoPinglun) {
        return xiaoyuanInfoMapper.deletePingLun(infoPinglun);
    }

    /**
     * 修改校园安全信息
     * 
     * @param xiaoyuanInfo 校园安全信息
     * @return 结果
     */
    @Transactional
    @Override
    public int updateXiaoyuanInfo(XiaoyuanInfo xiaoyuanInfo)
    {
        xiaoyuanInfo.setUpdateTime(DateUtils.getNowDate());
        xiaoyuanInfoMapper.deleteInfoPingLunByInfoId(xiaoyuanInfo.getInfoId());
        insertInfoPinglun(xiaoyuanInfo);
        return xiaoyuanInfoMapper.updateXiaoyuanInfo(xiaoyuanInfo);
    }

    /**
     * 点赞接口/取消点赞
     * @param xiaoyuanInfo
     * @return
     */
    @Override
    public AjaxResult dianZan(XiaoyuanInfo xiaoyuanInfo) {
        //从redis中获取点赞数量
        // key =xiaoyuan_info_dianzan:时间:xiaoyuan_info表中的info_id
        //value = 点赞数量
        //谁点赞了,key = xiaoyuan_info_dianzan_user:xiaoyuan_info表中的info_id
        //value = user_id

        Object cacheObject = redisCache.getCacheObject(XIAOYUAN_INFO_DIANZAN_USER + xiaoyuanInfo.getInfoId());
        //获取点赞数量
        Object dianZanNum = redisCache.getCacheObject(XIAOYUAN_INFO_DIANZAN + xiaoyuanInfo.getInfoId());
        if (ObjectUtils.isEmpty(cacheObject)){
            //如果是空,则给这个人点赞
            redisCache.setCacheObject(XIAOYUAN_INFO_DIANZAN_USER + xiaoyuanInfo.getInfoId(),SecurityUtils.getUserId());
            if (ObjectUtils.isEmpty(dianZanNum)){
                redisCache.setCacheObject(XIAOYUAN_INFO_DIANZAN + xiaoyuanInfo.getInfoId(),1);
            }else {
                redisCache.setCacheObject(XIAOYUAN_INFO_DIANZAN + xiaoyuanInfo.getInfoId(),(int)dianZanNum + 1);
            }
        }else {
            //删除这个key
            redisCache.deleteObject(XIAOYUAN_INFO_DIANZAN_USER + xiaoyuanInfo.getInfoId());
            int i = (int) dianZanNum - 1;
            if (i < 0){
                i= 0;
            }
            redisCache.setCacheObject(XIAOYUAN_INFO_DIANZAN + xiaoyuanInfo.getInfoId(),i);
        }
        return AjaxResult.success();
    }


    /**
     * 转发接口
     * @param xiaoyuanInfo
     * @return
     */
    @Override
    public AjaxResult zhuanFa(XiaoyuanInfo xiaoyuanInfo) {
        //从redis中获取转发数量
        // key =xiaoyuan_info_zhuanfa:xiaoyuan_info表中的info_id
        //value = 转发数量
        Object number = redisCache.getCacheObject(XIAOYUAN_INFO_ZHUANFA + xiaoyuanInfo.getInfoId());
        if (ObjectUtils.isEmpty(number)){
            //如果是空,则给这个信息创建一个转发数量
            redisCache.setCacheObject(XIAOYUAN_INFO_ZHUANFA + xiaoyuanInfo.getInfoId(),1);
        }else {
            //转发数量+1
            redisCache.setCacheObject(XIAOYUAN_INFO_ZHUANFA + xiaoyuanInfo.getInfoId(),(int)number + 1);
        }
        return AjaxResult.success();
    }

    /**
     * 批量删除校园安全信息
     * 
     * @param infoIds 需要删除的校园安全信息主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteXiaoyuanInfoByInfoIds(Long[] infoIds)
    {
        xiaoyuanInfoMapper.deleteInfoPingLunByInfoIds(infoIds);
        return xiaoyuanInfoMapper.deleteXiaoyuanInfoByInfoIds(infoIds);
    }

    /**
     * 删除校园安全信息信息
     * 
     * @param infoId 校园安全信息主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteXiaoyuanInfoByInfoId(Long infoId)
    {
        xiaoyuanInfoMapper.deleteInfoPingLunByInfoId(infoId);
        return xiaoyuanInfoMapper.deleteXiaoyuanInfoByInfoId(infoId);
    }

    /**
     * 新增校园安全信息评论信息
     * 
     * @param xiaoyuanInfo 校园安全信息对象
     */
    public void insertInfoPinglun(XiaoyuanInfo xiaoyuanInfo)
    {
        List<InfoPinglun> infoPinglunList = xiaoyuanInfo.getInfoPingLunList();
        Long infoId = xiaoyuanInfo.getInfoId();
        if (StringUtils.isNotNull(infoPinglunList))
        {
            List<InfoPinglun> list = new ArrayList<InfoPinglun>();
            for (InfoPinglun infoPinglun : infoPinglunList)
            {
                infoPinglun.setInfoId(infoId);
                list.add(infoPinglun);
            }
            if (list.size() > 0)
            {
                xiaoyuanInfoMapper.batchInfoPingLun(list);
            }
        }
    }
}
