package com.cf.imes.module.system.service.notify;

import cn.hutool.core.collection.CollUtil;
import com.cf.imes.framework.common.pojo.PageResult;
import com.cf.imes.framework.common.util.object.BeanUtils;
import com.cf.imes.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.cf.imes.module.system.controller.admin.notify.vo.message.NotifyMessageMyPageReqVO;
import com.cf.imes.module.system.controller.admin.notify.vo.message.NotifyMessagePageReqVO;
import com.cf.imes.module.system.controller.admin.notify.vo.message.NotifyMessageRespVO;
import com.cf.imes.module.system.dal.dataobject.notify.NotifyMessageDO;
import com.cf.imes.module.system.dal.dataobject.notify.NotifyTemplateDO;
import com.cf.imes.module.system.dal.mysql.notify.NotifyMessageMapper;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import static com.cf.imes.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

/**
 * 站内信 Service 实现类
 *
 * @author xrcoder
 */
@Service
@Validated
public class NotifyMessageServiceImpl implements NotifyMessageService {

    @Resource
    private NotifyMessageMapper notifyMessageMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Long createNotifyMessage(Long userId, Integer userType,
                                    NotifyTemplateDO template, String templateContent, Map<String, Object> templateParams) {
        NotifyMessageDO message = new NotifyMessageDO().setUserId(userId).setUserType(userType)
                .setTemplateId(template.getId()).setTemplateCode(template.getCode())
                .setTemplateType(template.getType()).setTemplateNickname(template.getNickname())
                .setTemplateContent(templateContent).setTemplateParams(templateParams);
        notifyMessageMapper.insert(message);
        return message.getId();
    }

    @Override
    public PageResult<NotifyMessageDO> getNotifyMessagePage(NotifyMessagePageReqVO pageReqVO) {
        return notifyMessageMapper.selectPage(pageReqVO);
    }

    @Override
    public PageResult<NotifyMessageDO> getMyMyNotifyMessagePage(NotifyMessageMyPageReqVO pageReqVO, Long userId, Integer userType) {
        return notifyMessageMapper.selectPage(pageReqVO, userId, userType);
    }

    @Override
    public NotifyMessageDO getNotifyMessage(Long id) {
        return notifyMessageMapper.selectById(id);
    }

    @Override
    public List<NotifyMessageDO> getUnreadNotifyMessageList(Long userId, Integer userType, Integer size) {
        return notifyMessageMapper.selectUnreadListByUserIdAndUserType(userId, userType, size);
    }

    @Override
    public Long getUnreadNotifyMessageCount(Long userId, Integer userType) {
        List<NotifyMessageDO> notifyMessageDOS = notifyMessageMapper.selectList(new LambdaQueryWrapperX<NotifyMessageDO>()
                .eq(NotifyMessageDO::getUserType, userType)
                .in(NotifyMessageDO::getUserId, Arrays.asList(userId, 0L))
                .select(NotifyMessageDO::getId)
        );
        if(CollUtil.isEmpty(notifyMessageDOS)) {
            return 0L;
        }
        Set<String> messageIds = notifyMessageDOS.stream().map(e->e.getId().toString()).collect(Collectors.toSet());
        Set<String> set = bitGet(messageIds, userId);
        messageIds.removeAll(set);
        return (long) messageIds.size();
        //return notifyMessageMapper.selectUnreadCountByUserIdAndUserType(userId, userType);
    }

    @Override
    public int updateNotifyMessageRead(Collection<Long> ids, Long userId, Integer userType) {
        bitset(ids.stream().map(Object::toString).collect(Collectors.toSet()), userId);
        return 1;
        //return notifyMessageMapper.updateListRead(ids, userId, userType);
    }

    @Override
    public int updateAllNotifyMessageRead(Long userId, Integer userType) {
        List<NotifyMessageDO> notifyMessageDOS = notifyMessageMapper.selectList(new LambdaQueryWrapperX<NotifyMessageDO>()
                .in(NotifyMessageDO::getUserId, Arrays.asList(userId, 0))
                .eq(NotifyMessageDO::getUserType, 2)
                .select(NotifyMessageDO::getId)
        );
        if (CollUtil.isNotEmpty(notifyMessageDOS)) {
            Set<String> messageIds = notifyMessageDOS.stream().map(e -> String.valueOf(e.getId())).collect(Collectors.toSet());
            bitset(messageIds, userId);
        }
        return 1;
        //return notifyMessageMapper.updateListRead(userId, userType);
    }

    @Override
    public Set<String> getMessageRead(Collection<String> messageIds, Long userId) {
        return bitGet(messageIds,userId);
    }

    @Override
    public PageResult<NotifyMessageRespVO> getPageResultByRead(NotifyMessageMyPageReqVO pageVO) {
        Boolean readStatus = pageVO.getReadStatus();
        Long userId = getLoginUserId();
        List<NotifyMessageDO> notifyMessageDOS = notifyMessageMapper.selectList(new LambdaQueryWrapperX<NotifyMessageDO>()
                .eq(NotifyMessageDO::getUserType, 2)
                .in(NotifyMessageDO::getUserId, Arrays.asList(userId, 0L))
                .betweenIfPresent(NotifyMessageDO::getCreateTime, pageVO.getCreateTime())
        );
        Set<String> messageIds = notifyMessageDOS.stream().map(e -> e.getId().toString()).collect(Collectors.toSet());
        Set<String> set = bitGet(messageIds, userId);
        List<NotifyMessageRespVO> respVOS = notifyMessageDOS.stream()
                .filter(f -> readStatus ? set.contains(f.getId().toString()): !set.contains(f.getId().toString()))
                .skip((long) (pageVO.getPageNo() - 1) * pageVO.getPageSize())
                .limit(pageVO.getPageSize())
                .map(e -> {
                    NotifyMessageRespVO respVO = BeanUtils.toBean(e, NotifyMessageRespVO.class);
                    respVO.setReadStatus(readStatus);
                    return respVO;
                })
                .toList();

        return new PageResult<>(respVOS, (long)respVOS.size());
    }

    private Boolean bitset(Collection<String> keys, Long userId) {
        return stringRedisTemplate.execute((RedisCallback<Boolean>) connection -> {
                    AtomicReference<Boolean> flag = new AtomicReference<>(false);
                    keys.forEach(key -> flag.set(connection.setBit(joinKey(key).getBytes(StandardCharsets.UTF_8), userId, true)));
                    return flag.get();
                }
        );
    }

    private Set<String> bitGet(Collection<String> keys, Long userId) {
        return stringRedisTemplate.execute((RedisCallback<Set<String>>)connection -> {
            Set<String> set = new HashSet<>();
            keys.forEach(key->{
                Boolean bit = connection.getBit(joinKey(key).getBytes(StandardCharsets.UTF_8), userId);
                if(bit) {
                    set.add(key);
                }
            });
            return set;
        });
    }

    private String joinKey(String key) {
        return NOTIFY_MESSAGE_KEY + key;
    }


}
