package yangtz.cs.liu.campus.service.impl.message;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.model.MpLoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.util.UserInfoUtil;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import yangtz.cs.liu.campus.domain.message.SchoolMessageParentsPushs;
import yangtz.cs.liu.campus.domain.message.SchoolMessageParentsPushsDetails;
import yangtz.cs.liu.campus.domain.message.SchoolMessagePush;
import yangtz.cs.liu.campus.domain.message.SchoolMessagePushDetails;
import yangtz.cs.liu.campus.mapper.message.SchoolMessageParentsPushsDetailsMapper;
import yangtz.cs.liu.campus.mapper.message.SchoolMessageParentsPushsMapper;
import yangtz.cs.liu.campus.mapper.message.SchoolMessagePushDetailsMapper;
import yangtz.cs.liu.campus.mapper.message.SchoolMessagePushMapper;
import yangtz.cs.liu.campus.mapper.teacher.SchoolTeacherMapper;
import yangtz.cs.liu.campus.service.message.ISchoolMessagePushService;
import yangtz.cs.liu.campus.vo.message.SchoolMessagePushExportVO;
import yangtz.cs.liu.wechat.vo.message.MessagePushVO;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotNull;
import static com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank;
import static com.ruoyi.common.utils.SecurityUtils.getLoginUser;
import static com.ruoyi.common.utils.SecurityUtils.getUserId;
import static yangtz.cs.liu.campus.constant.MessageConstant.NORMAL;

@Service
public class SchoolMessagePushServiceImpl extends ServiceImpl<SchoolMessagePushMapper, SchoolMessagePush> implements ISchoolMessagePushService {

    @Autowired
    private SchoolMessagePushMapper schoolMessagePushMapper;
    @Autowired
    private SchoolMessagePushDetailsMapper detailsMapper;
    @Autowired
    private SysUserRoleMapper roleMapper;

    @Autowired
    private SchoolTeacherMapper teacherMapper;
    @Autowired
    UserInfoUtil userInfoUtil;

    private Logger log = LoggerFactory.getLogger(SchoolMessagePushServiceImpl.class);

    /**
     * 查询消息列表
     *
     * @param schoolMessagePush
     * @return
     */
    @Override
    public List<SchoolMessagePush> queryList(SchoolMessagePush schoolMessagePush) {
        LambdaQueryWrapper<SchoolMessagePush> lqw = new LambdaQueryWrapper<>();
        lqw
                .like(isNotBlank(schoolMessagePush.getTitle()), SchoolMessagePush::getTitle, schoolMessagePush.getTitle())
                .eq(isNotNull(schoolMessagePush.getReceivePacket()),SchoolMessagePush::getReceivePacket,schoolMessagePush.getReceivePacket())
                .eq(isNotNull(schoolMessagePush.getState()),SchoolMessagePush::getState,schoolMessagePush.getState())
                .orderByDesc(SchoolMessagePush::getCreateTime)
        ;
        return schoolMessagePushMapper.selectList(lqw);

    }

    @Override
    public List<MessagePushVO> getList(MessagePushVO messagePushVO) {
       //获取当前登录用户
       Long userId = getUserId();
       List<MessagePushVO> list = schoolMessagePushMapper.getList(userId,messagePushVO);
       return list;
    }

    /***
     * 新增消息，及接收人
     */
    @Override
    public int savePush(SchoolMessagePush schoolMessagePush) {
        if (1 == schoolMessagePushMapper.insert(schoolMessagePush)) {
            return insertDetails(schoolMessagePush);
        } else {
            throw new ServiceException("新增失败");
        }
    }

    @Override
    public int editPush(SchoolMessagePush schoolMessagePush) {
        //修改前的信息推送
        SchoolMessagePush push = schoolMessagePushMapper.selectById(schoolMessagePush.getId());
        //接收人（角色）未修改
        if (schoolMessagePush.getReceivePacket().equals(push.getReceivePacket())) {
            return schoolMessagePushMapper.updateById(schoolMessagePush);
        } else {
            //修改信息推送
            schoolMessagePushMapper.updateById(schoolMessagePush);
            //接收人修改，之前所选的推送用户都删掉，再添加所选角色下的用户
            LambdaQueryWrapper<SchoolMessagePushDetails> lqw = new LambdaQueryWrapper();
            lqw.eq(SchoolMessagePushDetails::getPushId, schoolMessagePush.getId());
            detailsMapper.delete(lqw);
            return insertDetails(schoolMessagePush);
        }
    }

    @Override
    public SchoolMessagePushExportVO getInfo(Long id) {
        return schoolMessagePushMapper.getInfo(id);
    }

    @Override
    public int deletePush(List<Long> ids) {
        //先删除子表数据
        LambdaQueryWrapper<SchoolMessagePushDetails> lqw = new LambdaQueryWrapper();
        lqw.in(SchoolMessagePushDetails::getPushId, ids);
        detailsMapper.delete(lqw);
        return schoolMessagePushMapper.deleteBatchIds(ids);
    }

    //添加信息推送接收用户
    public int insertDetails(SchoolMessagePush schoolMessagePush) {
        //获取接收人角色
        Long roleId = schoolMessagePush.getReceivePacket();
        //该角色下所有用户
        List<Long> userIdList = roleMapper.getRoleAllUserIds(roleId);
        if (StringUtils.isNull(userIdList) || userIdList.size() == 0) {
            return 0;
        }
        List<SchoolMessagePushDetails> detailsList = new ArrayList<>();
        for (Long userId : userIdList) {
            SchoolMessagePushDetails details = new SchoolMessagePushDetails();
            details.setPushId(schoolMessagePush.getId());
            details.setUserId(userId);
            details.setStatus(NORMAL);
            details.insert();
            detailsList.add(details);
        }
        return detailsMapper.insertTeachers(detailsList) == detailsList.size() ? 1 : 0;
    }

    /**
     * 查询微信教师消息列表
     * @param messagePushVO
     * @return
     */
    @Override
    public List<MessagePushVO> teacherPushList(Long userId, MessagePushVO messagePushVO) {
        List<MessagePushVO> list = schoolMessagePushMapper.getList(userId,messagePushVO);
        return list;

        /** edit on 2022-11-17
         做法一 根据userId直接查出来返回
         List<SchoolMessagePush> list = details.selectList(userId);
         return list;

         做法二 先查出来pushIds
         LambdaQueryWrapper<SchoolMessagePushDetails> lqw = new LambdaQueryWrapper();
         lqw.eq(SchoolMessagePushDetails::getUserId, userId).select(SchoolMessagePushDetails::getPushId);
         List<Long> pushIdList = detailsMapper.selectList(lqw).stream().map(SchoolMessagePushDetails::getUserId).collect(Collectors.toList());
         接下来再按上面按else里面的代码来

         注:把未读的放前面,再按时间排
         */
    }
}
