package com.izouma.wenlvju.web;
import com.izouma.wenlvju.domain.Announcement;
import com.izouma.wenlvju.service.AnnouncementService;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.AnnouncementRepo;
import com.izouma.wenlvju.utils.ObjUtils;
import com.izouma.wenlvju.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("/announcement")
@AllArgsConstructor
public class AnnouncementController extends BaseController {
    private AnnouncementService announcementService;
    private AnnouncementRepo announcementRepo;

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


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

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

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

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

