package com.izouma.jmrh.web.stat;

import com.izouma.jmrh.web.BaseController;
import com.izouma.jmrh.domain.stat.AnalyzeState;
import com.izouma.jmrh.service.stat.AnalyzeStateService;
import com.izouma.jmrh.dto.PageQuery;
import com.izouma.jmrh.exception.BusinessException;
import com.izouma.jmrh.repo.stat.AnalyzeStateRepo;
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("/analyzeState")
@AllArgsConstructor
public class AnalyzeStateController extends BaseController {
    private AnalyzeStateService analyzeStateService;
    private AnalyzeStateRepo analyzeStateRepo;

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


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

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

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

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

