package cn.teammodel.service.impl;

import cn.teammodel.common.ErrorCode;
import cn.teammodel.common.IdRequest;
import cn.teammodel.common.PK;
import cn.teammodel.config.exception.ServiceException;
import cn.teammodel.model.dto.news.CreateNewsDto;
import cn.teammodel.model.dto.news.UpdateNewsDto;
import cn.teammodel.model.entity.User;
import cn.teammodel.model.entity.news.News;
import cn.teammodel.repository.NewsRepository;
import cn.teammodel.security.utils.SecurityUtil;
import cn.teammodel.service.NewsService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Instant;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author winter
 * @create 2024-02-26 17:10
 */
@Service
public class NewsServiceImpl implements NewsService {

    @Resource
    private NewsRepository newsRepository;
    @Override
    public List<News> listNews(String periodId) {
        User user = SecurityUtil.getLoginUser();
        String schoolId = user.getSchoolId();
        List<News> res = newsRepository.findAllByCodeAndPeriodId(String.format(PK.NEWS, schoolId), periodId);
        // 降序排序
        res = res.stream().sorted((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime())).collect(Collectors.toList());
        return res;
    }

    @Override
    public News createNews(CreateNewsDto createNewsDto) {
        User user = SecurityUtil.getLoginUser();
        News newApp = new News();
        BeanUtils.copyProperties(createNewsDto, newApp);
        newApp.setCreator(user.getName());
        newApp.setCreatorId(user.getId());
        newApp.setCreateTime(Instant.now().toEpochMilli());
        newApp.setCode(String.format(PK.NEWS, user.getSchoolId()));

        return newsRepository.save(newApp);
    }

    @Override
    public News updateNews(UpdateNewsDto updateNewsDto) {
        String id = updateNewsDto.getId();
        User user = SecurityUtil.getLoginUser();
        String userId = user.getId();
        String schoolId = user.getSchoolId();

        News news = newsRepository.findNewsByIdAndCode(id, String.format(PK.NEWS, schoolId));
        if (ObjectUtils.isEmpty(news)) {
            throw new ServiceException(ErrorCode.PARAMS_ERROR.getCode(), "该新闻不存在");
        }
        if (!userId.equals(news.getCreatorId()) && !user.getRoles().contains("admin")) {
            throw new ServiceException(ErrorCode.NO_AUTH_ERROR.getCode(), "您没有权限修改该新闻");
        }
        BeanUtils.copyProperties(updateNewsDto, news);
        return newsRepository.save(news);
    }

    @Override
    public void deleteNews(IdRequest idRequest) {
        String newsId = idRequest.getId();
        User user = SecurityUtil.getLoginUser();
        String userId = user.getId();
        String schoolId = user.getSchoolId();
        News news = newsRepository.findNewsByIdAndCode(newsId, String.format(PK.NEWS, schoolId));
        if (userId.equals(news.getCreatorId()) && user.getRoles().contains("admin")) {
            newsRepository.deleteById(newsId, PK.buildOf(PK.NEWS, schoolId));
        } else {
            throw new ServiceException(ErrorCode.NO_AUTH_ERROR.getCode(), "您没有权限删除该新闻");
        }
    }

    @Override
    public News getNewsById(String newsId) {
        String schoolId = SecurityUtil.getLoginUser().getSchoolId();
        News news = newsRepository.findById(newsId, PK.buildOf(PK.NEWS, schoolId)).orElse(null);
        return news;
    }
}
