package com.izouma.jmrh.web;
import com.izouma.jmrh.domain.ApplicationField;
import com.izouma.jmrh.service.ApplicationFieldService;
import com.izouma.jmrh.dto.PageQuery;
import com.izouma.jmrh.exception.BusinessException;
import com.izouma.jmrh.repo.ApplicationFieldRepo;
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("/applicationField")
@AllArgsConstructor
public class ApplicationFieldController extends BaseController {
    private ApplicationFieldService applicationFieldService;
    private ApplicationFieldRepo applicationFieldRepo;

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


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

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

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

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

