package com.izouma.jiashanxia.web;
import com.izouma.jiashanxia.domain.Article;
import com.izouma.jiashanxia.service.ArticleService;
import com.izouma.jiashanxia.dto.PageQuery;
import com.izouma.jiashanxia.exception.BusinessException;
import com.izouma.jiashanxia.repo.ArticleRepo;
import com.izouma.jiashanxia.utils.ObjUtils;
import com.izouma.jiashanxia.utils.excel.ExcelUtils;
import lombok.AllArgsConstructor;
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("/article")
@AllArgsConstructor
public class ArticleController extends BaseController {
    private ArticleService articleService;
    private ArticleRepo articleRepo;

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


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

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

    @GetMapping("/getByName/{name}")
    public Article get(@PathVariable String name) {
        return articleRepo.findFirstByName(name).orElseThrow(new BusinessException("无记录"));
    }

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

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

