package com.izouma.jmrh.web.stat;

import com.izouma.jmrh.web.BaseController;
import com.izouma.jmrh.domain.stat.OrgNumStat;
import com.izouma.jmrh.service.stat.OrgNumStatService;
import com.izouma.jmrh.dto.PageQuery;
import com.izouma.jmrh.exception.BusinessException;
import com.izouma.jmrh.repo.stat.OrgNumStatRepo;
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("/orgNumStat")
@AllArgsConstructor
public class OrgNumStatController extends BaseController {
    private OrgNumStatService orgNumStatService;
    private OrgNumStatRepo orgNumStatRepo;

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


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

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

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

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

