package com.izouma.nineth.service;

import com.izouma.nineth.config.RedisKeys;
import com.izouma.nineth.domain.Activity;
import com.izouma.nineth.domain.User;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.ActivityRepo;
import com.izouma.nineth.utils.JpaUtils;
import com.izouma.nineth.utils.ObjUtils;
import com.izouma.nineth.utils.SecurityUtils;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@AllArgsConstructor
public class ActivityService {

    private ActivityRepo activityRepo;

    private final RedisTemplate<String, Object> redisTemplate;

    public Page<Activity> all(PageQuery pageQuery) {
        return activityRepo.findAll(JpaUtils.toSpecification(pageQuery, Activity.class), JpaUtils.toPageRequest(pageQuery));
    }

    /**
     * 查看用户是否读过公告
     * @return 是否阅读
     */
    public Map<String, Boolean> hasRead() {
        User authenticatedUser = SecurityUtils.getAuthenticatedUser();
        Map<String, Boolean> map = new HashMap<>(1);
        if (activityRepo.countByDelFalse()>0) {
            //已阅读公告返回false redis set 存在key为已阅读
            if (authenticatedUser != null) {
                map.put("read", Boolean.FALSE.equals(redisTemplate.opsForSet().isMember(RedisKeys.NOTICE_READ_USER, authenticatedUser.getId())));
            } else {
                map.put("read", true);
            }
        }else {
            map.put("read", false);
        }
        return map;
    }

    public Activity save(Activity record) {
        if (record.getId() != null) {
            Activity orig = activityRepo.findById(record.getId()).orElseThrow(new BusinessException("活动无记录"));
            ObjUtils.merge(orig, record);
            return activityRepo.save(orig);
        }
        redisTemplate.delete(RedisKeys.NOTICE_READ_USER);
        return activityRepo.save(record);
    }

    public Activity findById(Long id) {
        Activity activity = activityRepo.findById(id).orElseThrow(new BusinessException("活动无记录"));
        User authenticatedUser = SecurityUtils.getAuthenticatedUser();
        if (authenticatedUser != null) {
            redisTemplate.opsForSet().add(RedisKeys.NOTICE_READ_USER, authenticatedUser.getId());
        }
        return activity;
    }

    public List<Activity> contraction(Integer projectId) {
        return activityRepo.findAllByProjectId(projectId);
    }
}
