package com.izouma.wenlvju.web;
import com.izouma.wenlvju.domain.Award;
import com.izouma.wenlvju.service.AwardService;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.AwardRepo;
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("/award")
@AllArgsConstructor
public class AwardController extends BaseController {
    private AwardService awardService;
    private AwardRepo awardRepo;

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


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

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

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

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

