package com.ruoyi.system.service.impl;

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

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.Constants;
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.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.FormalParentsStudentMapper;
import com.ruoyi.system.mapper.FormalTeacherClassMapper;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.support.incrementer.PostgresSequenceMaxValueIncrementer;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.XiaoyuanNoticeMapper;
import com.ruoyi.system.domain.XiaoyuanNotice;
import com.ruoyi.system.service.IXiaoyuanNoticeService;

import javax.annotation.Resource;

import static com.ruoyi.common.utils.PageUtils.startPage;

/**
 * 校园新闻Service业务层处理
 *
 * @author boman
 * @date 2023-06-05
 */
@Service
public class XiaoyuanNoticeServiceImpl implements IXiaoyuanNoticeService {
    @Autowired
    private XiaoyuanNoticeMapper xiaoyuanNoticeMapper;
    @Autowired
    private FormalTeacherClassMapper formalTeacherClassMapper;
    @Autowired
    private FormalParentsStudentMapper formalParentsStudentMapper;

    /**
     * 查询校园新闻
     *
     * @param noticeId 校园新闻主键
     * @return 校园新闻
     */
    @Override
    public XiaoyuanNotice selectXiaoyuanNoticeByNoticeId(Integer noticeId) {
        return xiaoyuanNoticeMapper.selectXiaoyuanNoticeByNoticeId(noticeId);
    }

    /**
     * 查询校园新闻列表
     *
     * @param xiaoyuanNotice 校园新闻
     * @return 校园新闻
     */
    @Override
    public List<XiaoyuanNotice> selectXiaoyuanNoticeList(XiaoyuanNotice xiaoyuanNotice) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        xiaoyuanNotice.setSenderId(user.getUserId().toString());
        List<SysRole> roles = user.getRoles();
        String classId = "0";
        for (SysRole role : roles) {
            if ("teacher".equals(role.getRoleKey())) {
                FormalTeacherClass formalTeacherClass = new FormalTeacherClass();
                formalTeacherClass.setTeacherId(user.getUserId());
                List<FormalTeacherClass> formalTeacherClasses = formalTeacherClassMapper.selectFormalTeacherClassList(formalTeacherClass);
                if (formalTeacherClasses != null && formalTeacherClasses.size() > 0) {
                    for (FormalTeacherClass teacherClass : formalTeacherClasses) {
                        classId = teacherClass.getClassId() + ",";
                    }
                }
            }
            if ("parents".equals(role.getRoleKey())) {
                FormalParentsStudent formalParentsStudent = new FormalParentsStudent();
                formalParentsStudent.setParentsId(user.getUserId());
                List<FormalParentsStudent> formalParentsStudents = formalParentsStudentMapper.selectFormalParentsStudentList(formalParentsStudent);
                for (FormalParentsStudent parentsStudent : formalParentsStudents) {
                    classId = parentsStudent.getClassId() + ",";
                }
            }
        }
        if (StringUtils.isNotBlank(classId)) {
            classId = classId.substring(0, classId.length() - 1);
        }
        //查询出所有班级id
        xiaoyuanNotice.setSenderDept(classId);
        startPage();
        return xiaoyuanNoticeMapper.selectXiaoyuanNoticeList(xiaoyuanNotice);
    }

    @Override
    public List<XiaoyuanNotice> selectXiaoyuanNoticeMyList(XiaoyuanNotice xiaoyuanNotice) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        xiaoyuanNotice.setSenderId(String.valueOf(user.getUserId()));
        return xiaoyuanNoticeMapper.selectXiaoyuanNoticeMyList(xiaoyuanNotice);
    }

    /**
     * 我的收藏
     * @param xiaoyuanNotice
     * @return
     */
    @Override
    public List<XiaoyuanNotice> myCollect(XiaoyuanNotice xiaoyuanNotice) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long userId = user.getUserId();
        xiaoyuanNotice.setCollect("\"userId\":"+userId);
        return  xiaoyuanNoticeMapper.selectXiaoyuanNoticeByMyCollect(xiaoyuanNotice);
    }

    /**
     * 新增校园新闻
     *
     * @param xiaoyuanNotice 校园新闻
     * @return 结果
     */
    @Override
    public int insertXiaoyuanNotice(XiaoyuanNotice xiaoyuanNotice) {
        xiaoyuanNotice.setCreateTime(DateUtils.getNowDate());
        SysUser user = SecurityUtils.getLoginUser().getUser();
        xiaoyuanNotice.setSenderId(String.valueOf(user.getUserId()));
        xiaoyuanNotice.setSenderName(user.getNickName());
        xiaoyuanNotice.setAvatar(user.getAvatar());
        int result = xiaoyuanNoticeMapper.insertXiaoyuanNotice(xiaoyuanNotice);
        return result;
    }

    /**
     * 修改校园新闻
     *
     * @param xiaoyuanNotice 校园新闻
     * @return 结果
     */
    @Override
    public int updateXiaoyuanNotice(XiaoyuanNotice xiaoyuanNotice) {
        //修改之前去查询
        XiaoyuanNotice xiaoyuanNoticeUpdate = xiaoyuanNoticeMapper.selectXiaoyuanNoticeByNoticeId(xiaoyuanNotice.getNoticeId());
        List<JSONObject> map = new ArrayList<>();
        //判断是评论还是点赞还是收藏
        UUID uuid = UUID.randomUUID();
        String deleteId = xiaoyuanNotice.getDeleteId();
        if (Constants.ONE.equals(xiaoyuanNotice.getUpdateType())) {
            String comment = xiaoyuanNotice.getComment();
            if (StringUtils.isNotBlank(comment)) {
                String updateComment = xiaoyuanNoticeUpdate.getComment();
                JSONObject jsonObject = JSONObject.parseObject(comment);
                //没有id就是新增
                if (StringUtils.isEmpty(deleteId)) {
                    //给新增参数增加id
                    jsonObject.put("id", uuid);
                    map.add(jsonObject);
                    xiaoyuanNotice.setComment(map.toString());
                    //如果数据库中原始数据不为空
                    if (StringUtils.isNotBlank(updateComment)) {
                        updateComment = updateComment.replace("[", "").replace("]", "");
                        ArrayList<Object> arr = new ArrayList<>(updateComment.length());
                        Collections.addAll(arr, updateComment);
                        arr.add(jsonObject);
                        xiaoyuanNotice.setComment(arr.toString());
                    }
                } else {
                    //删除原始数据
                    JSONArray jsonArray = JSONArray.parseArray(updateComment);
                    jsonArray.removeIf(object -> xiaoyuanNotice.getDeleteId().equals(((JSONObject) object).get("id")));
                    xiaoyuanNotice.setComment("");
                    if (jsonArray.size() > 0) {
                        xiaoyuanNotice.setComment(jsonArray.toString());
                    }
                }
            }
        } else if (Constants.TWO.equals(xiaoyuanNotice.getUpdateType())) {
            String prised = xiaoyuanNotice.getPrised();
            String updatePrised = xiaoyuanNoticeUpdate.getPrised();
            if (StringUtils.isNotBlank(prised)) {
                JSONObject jsonObject = JSONObject.parseObject(prised);
                //给新增参数增加id
                //没有id就是新增
                if (StringUtils.isEmpty(deleteId)) {
                    jsonObject.put("id", uuid);
                    map.add(jsonObject);
                    xiaoyuanNotice.setPrised(map.toString());
                    //如果数据库中原始数据不为空
                    if (StringUtils.isNotBlank(updatePrised)) {
                        updatePrised = updatePrised.replace("[", "").replace("]", "");
                        ArrayList<Object> arr = new ArrayList<>(updatePrised.length());
                        Collections.addAll(arr, updatePrised);
                        arr.add(jsonObject);
                        xiaoyuanNotice.setPrised(arr.toString());
                    }
                } else {

                    //删除原始数据
                    JSONArray jsonArray = JSONArray.parseArray(updatePrised);
                    jsonArray.removeIf(object -> xiaoyuanNotice.getDeleteId().equals(((JSONObject) object).get("id")));
                    xiaoyuanNotice.setPrised("");
                    if (jsonArray.size() > 0) {
                        xiaoyuanNotice.setPrised(jsonArray.toString());
                    }
                }
            }
        } else if (Constants.THR.equals(xiaoyuanNotice.getUpdateType())) {
            String collect = xiaoyuanNotice.getCollect();
            String updateCollect = xiaoyuanNoticeUpdate.getCollect();
            if (StringUtils.isNotBlank(collect)) {
                JSONObject jsonObject = JSONObject.parseObject(collect);

                //给新增参数增加id
                //没有id就是新增
                if (StringUtils.isEmpty(deleteId)) {
                    jsonObject.put("id", uuid);
                    map.add(jsonObject);
                    xiaoyuanNotice.setCollect(map.toString());
                    //如果数据库中原始数据不为空
                    if (StringUtils.isNotBlank(updateCollect)) {
                        updateCollect = updateCollect.replace("[", "").replace("]", "");
                        ArrayList<Object> arr = new ArrayList<>(updateCollect.length());
                        Collections.addAll(arr, updateCollect);
                        arr.add(jsonObject);
                        xiaoyuanNotice.setCollect(arr.toString());
                    }
                } else {
                    //删除原始数据
                    JSONArray jsonArray = JSONArray.parseArray(updateCollect);
                    jsonArray.removeIf(object -> xiaoyuanNotice.getDeleteId().equals(((JSONObject) object).get("id")));
                    xiaoyuanNotice.setCollect("");
                    if (jsonArray.size() > 0) {
                        xiaoyuanNotice.setCollect(jsonArray.toString());
                    }
                }
            }
        }

        xiaoyuanNotice.setUpdateTime(DateUtils.getNowDate());
        return xiaoyuanNoticeMapper.updateXiaoyuanNotice(xiaoyuanNotice);

    }

    /**
     * 批量删除校园新闻
     *
     * @param noticeIds 需要删除的校园新闻主键
     * @return 结果
     */
    @Override
    public int deleteXiaoyuanNoticeByNoticeIds(Integer[] noticeIds) {
        return xiaoyuanNoticeMapper.deleteXiaoyuanNoticeByNoticeIds(noticeIds);
    }

    /**
     * 删除校园新闻信息
     *
     * @param noticeId 校园新闻主键
     * @return 结果
     */
    @Override
    public int deleteXiaoyuanNoticeByNoticeId(Integer noticeId) {
        return xiaoyuanNoticeMapper.deleteXiaoyuanNoticeByNoticeId(noticeId);
    }
}
