package com.izouma.jiashanxia.web;
import com.izouma.jiashanxia.domain.Banner;
import com.izouma.jiashanxia.service.BannerService;
import com.izouma.jiashanxia.dto.PageQuery;
import com.izouma.jiashanxia.exception.BusinessException;
import com.izouma.jiashanxia.repo.BannerRepo;
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("/banner")
@AllArgsConstructor
public class BannerController extends BaseController {
    private BannerService bannerService;
    private BannerRepo bannerRepo;

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


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

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

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

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

