package com.izouma.jmrh.web;

import com.izouma.jmrh.domain.Comment;
import com.izouma.jmrh.dto.CommentDTO;
import com.izouma.jmrh.dto.PageQuery;
import com.izouma.jmrh.exception.BusinessException;
import com.izouma.jmrh.repo.CommentRepo;
import com.izouma.jmrh.service.CommentService;
import com.izouma.jmrh.utils.ObjUtils;
import com.izouma.jmrh.utils.excel.ExcelUtils;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/comment")
@AllArgsConstructor
public class CommentController extends BaseController {
    private CommentService commentService;
    private CommentRepo    commentRepo;

    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public Comment save(@RequestBody Comment record) {
        if (record.getId() == null) {
            throw new BusinessException("无记录");
        }
        Comment orig = commentRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
        ObjUtils.merge(orig, record);
        return commentRepo.save(orig);
    }

    @PostMapping("/create")
    public Comment create(@RequestBody Comment record) {
        return commentService.create(record);
    }


    //@PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/all")
    public Page<Comment> all(PageQuery pageQuery) {
        return commentRepo.findAll(toSpecification(pageQuery, Comment.class), toPageRequest(pageQuery));
    }

    @GetMapping("/get/{id}")
    public Comment get(@PathVariable Long id) {
        return commentRepo.findById(id).orElseThrow(new BusinessException("无记录"));
    }

    @PostMapping("/del/{id}")
    public void del(@PathVariable Long id) {
        commentService.del(id);
    }

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

    @GetMapping("/like")
    public void like(@RequestParam Long commentId, @RequestParam boolean dislike) {
        commentService.like(commentId, dislike);
    }

    @GetMapping("/allDTO")
    public Page<CommentDTO> allDTO(PageQuery pageQuery) {
        pageQuery.getQuery().put("del", false);
        return commentService.allDTO(pageQuery);
    }
}

