package com.izouma.nineth.web;
import com.izouma.nineth.domain.TestClass;
import com.izouma.nineth.service.TestClassService;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.TestClassRepo;
import com.izouma.nineth.utils.ObjUtils;
import com.izouma.nineth.utils.excel.ExcelUtils;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/testClass")
@AllArgsConstructor
public class TestClassController extends BaseController {
    private TestClassService testClassService;
    private TestClassRepo testClassRepo;

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


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

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

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

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

