package com.izouma.jmrh.web;

import com.izouma.jmrh.domain.ResSnDProperty;
import com.izouma.jmrh.service.ResSnDPropertyService;
import com.izouma.jmrh.dto.PageQuery;
import com.izouma.jmrh.exception.BusinessException;
import com.izouma.jmrh.repo.ResSnDPropertyRepo;
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("/resSnDProperty")
@AllArgsConstructor
public class ResSnDPropertyController extends BaseController {
    private ResSnDPropertyService resSnDPropertyService;
    private ResSnDPropertyRepo resSnDPropertyRepo;

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


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

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

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

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

