package com.izouma.jmrh.web.stat;

import com.izouma.jmrh.web.BaseController;
import com.izouma.jmrh.domain.stat.Threshold;
import com.izouma.jmrh.service.stat.ThresholdService;
import com.izouma.jmrh.dto.PageQuery;
import com.izouma.jmrh.exception.BusinessException;
import com.izouma.jmrh.repo.stat.ThresholdRepo;
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("/threshold")
@AllArgsConstructor
public class ThresholdController extends BaseController {
    private ThresholdService thresholdService;
    private ThresholdRepo thresholdRepo;

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


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

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

    @GetMapping("/initData")
    public void initData() {
        thresholdService.init();
    }

    @GetMapping("/getOneThreshold")
    public Threshold getOneThreshold() {
       return thresholdService.getOneThreshold();
    }

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

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

