package com.izouma.jmrh.web;
import com.izouma.jmrh.domain.Metric;
import com.izouma.jmrh.service.MetricService;
import com.izouma.jmrh.dto.PageQuery;
import com.izouma.jmrh.exception.BusinessException;
import com.izouma.jmrh.repo.MetricRepo;
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("/metric")
@AllArgsConstructor
public class MetricController extends BaseController {
    private MetricService metricService;
    private MetricRepo metricRepo;

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


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

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

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

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

