package com.izouma.nineth.web;

import com.izouma.nineth.domain.Recommend;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.RecommendRepo;
import com.izouma.nineth.service.RecommendService;
import com.izouma.nineth.utils.ObjUtils;
import com.izouma.nineth.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("/recommend")
@AllArgsConstructor
public class RecommendController extends BaseController {
    private RecommendService recommendService;
    private RecommendRepo recommendRepo;

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


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

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

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

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

