package com.izouma.jiashanxia.web;
import com.izouma.jiashanxia.domain.Feedback;
import com.izouma.jiashanxia.service.FeedbackService;
import com.izouma.jiashanxia.dto.PageQuery;
import com.izouma.jiashanxia.exception.BusinessException;
import com.izouma.jiashanxia.repo.FeedbackRepo;
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("/feedback")
@AllArgsConstructor
public class FeedbackController extends BaseController {
    private FeedbackService feedbackService;
    private FeedbackRepo feedbackRepo;

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


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

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

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

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

