package com.kxs.system.biz.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kxs.common.security.util.SecurityUtils;
import com.kxs.system.api.model.KxsSysMsgRead;
import com.kxs.system.api.vo.kxsapp.sysMsg.SysMsgPageVO;
import com.kxs.system.api.vo.kxsapp.sysMsg.SysMsgVO;
import com.kxs.system.biz.constant.SysConstants;
import com.kxs.system.biz.mapper.KxsSysMsgMapper;
import com.kxs.system.api.model.KxsSysMsg;
import com.kxs.system.biz.mapper.KxsSysMsgReadMapper;
import com.kxs.system.biz.service.KxsSysMsgService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 系统消息推送表(KxsSysMsg)表服务实现类
 *
 * @author 系统
 * @since 2023-12-15 12:16:32
 */
@Service("kxsSysMsgService")
@RequiredArgsConstructor
public class KxsSysMsgServiceImpl extends ServiceImpl<KxsSysMsgMapper, KxsSysMsg> implements KxsSysMsgService {

    private final RedisTemplate<String, Object> redisTemplate;

    private final KxsSysMsgReadMapper kxsSysMsgReadMapper;

    @Override
    public IPage<SysMsgPageVO> getByPage(Page<SysMsgPageVO> page) {
        Long userId = SecurityUtils.getUser().getId();

        return baseMapper.getByPage(page, userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void readAll() {

        Long userId = SecurityUtils.getUser().getId();

        List<SysMsgPageVO> list = baseMapper.getList(userId);

        for (SysMsgPageVO sysMsgPageVO : list) {
            KxsSysMsgRead kxsSysMsgRead = new KxsSysMsgRead();
            kxsSysMsgRead.setMsgId(sysMsgPageVO.getId());
            kxsSysMsgRead.setUserId(Math.toIntExact(userId));
            kxsSysMsgReadMapper.insert(kxsSysMsgRead);
        }

    }

    @Override
    public SysMsgVO getByData(Integer id) {

        KxsSysMsg kxsSysMsg = baseMapper.selectById(id);
        if(kxsSysMsg == null){
            return null;
        }

        Long userId = SecurityUtils.getUser().getId();
        //已读消息
        KxsSysMsgRead kxsSysMsgRead = new KxsSysMsgRead();
        kxsSysMsgRead.setMsgId(kxsSysMsg.getId());
        kxsSysMsgRead.setUserId(Math.toIntExact(userId));
        kxsSysMsgReadMapper.insert(kxsSysMsgRead);

        SysMsgVO sysMsgVO = new SysMsgVO();
        BeanUtils.copyProperties(kxsSysMsg, sysMsgVO);


        return sysMsgVO;
    }


}

