package com.izouma.jmrh.web;
import com.izouma.jmrh.domain.Editing;
import com.izouma.jmrh.service.EditingService;
import com.izouma.jmrh.dto.PageQuery;
import com.izouma.jmrh.exception.BusinessException;
import com.izouma.jmrh.repo.EditingRepo;
import com.izouma.jmrh.utils.ObjUtils;
import com.izouma.jmrh.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("/editing")
@AllArgsConstructor
public class EditingController extends BaseController {
    private EditingService editingService;
    private EditingRepo editingRepo;

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


    //@PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/all")
    public Page<Editing> all(PageQuery pageQuery) {
        return editingRepo.findAll(toSpecification(pageQuery,Editing.class), toPageRequest(pageQuery));
    }

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

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

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

