package com.izouma.nineth.web;

import cn.hutool.core.collection.CollUtil;
import com.izouma.nineth.domain.News;
import com.izouma.nineth.domain.NewsLike;
import com.izouma.nineth.domain.User;
import com.izouma.nineth.repo.NewsLikeRepo;
import com.izouma.nineth.service.NewsService;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.NewsRepo;
import com.izouma.nineth.utils.ObjUtils;
import com.izouma.nineth.utils.SecurityUtils;
import com.izouma.nineth.utils.excel.ExcelUtils;
import lombok.AllArgsConstructor;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/news")
@AllArgsConstructor
public class NewsController extends BaseController {
    private NewsService  newsService;
    private NewsRepo     newsRepo;
    private NewsLikeRepo newsLikeRepo;

    @PreAuthorize("hasAnyRole('ADMIN','NEWS')")
    @PostMapping("/save")
    public News save(@RequestBody News record) {
        if (record.getId() != null) {
            News orig = newsRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
            ObjUtils.merge(orig, record);
            return newsRepo.save(orig);
        }
        return newsRepo.save(record);
    }


    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/all")
    public Page<News> all(@RequestBody PageQuery pageQuery) {
        return newsService.all(pageQuery);
    }

    @GetMapping("/get/{id}")
    @Cacheable("news")
    public News get(@PathVariable Long id) {
        News news = newsRepo.findById(id).orElseThrow(new BusinessException("无记录"));
        User user = SecurityUtils.getAuthenticatedUser();

        if (user != null && !user.isAdmin()) {
            List<NewsLike> likes = newsLikeRepo.findByUserIdAndNewsId(user
                    .getId(), id);
            news.setLiked(CollUtil.isNotEmpty(likes));
        }
        return news;
    }

    @PreAuthorize("hasAnyRole('ADMIN','NEWS')")
    @PostMapping("/del/{id}")
    public void del(@PathVariable Long id) {
        newsRepo.softDelete(id);
    }

    @GetMapping("/excel")
    @ResponseBody
    public void excel(HttpServletResponse response, PageQuery pageQuery) throws IOException {
        List<News> data = all(pageQuery).getContent();
        ExcelUtils.export(response, data);
    }
}

