package com.izouma.wenlvju.web;
import com.izouma.wenlvju.domain.GradingOrganization;
import com.izouma.wenlvju.service.GradingOrganizationService;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.GradingOrganizationRepo;
import com.izouma.wenlvju.utils.ObjUtils;
import com.izouma.wenlvju.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("/gradingOrganization")
@AllArgsConstructor
public class GradingOrganizationController extends BaseController {
    private GradingOrganizationService gradingOrganizationService;
    private GradingOrganizationRepo gradingOrganizationRepo;

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


    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/all")
    public Page<GradingOrganization> all(@RequestBody PageQuery pageQuery) {
        return gradingOrganizationService.all(pageQuery);
    }

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

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/del/{id}")
    public void del(@PathVariable Long id) {
        gradingOrganizationRepo.softDelete(id);
    }

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

