package com.izouma.jmrh.web.stat;

import com.izouma.jmrh.web.BaseController;
import com.izouma.jmrh.domain.stat.Category;
import com.izouma.jmrh.service.stat.CategoryService;
import com.izouma.jmrh.dto.PageQuery;
import com.izouma.jmrh.exception.BusinessException;
import com.izouma.jmrh.repo.stat.CategoryRepo;
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("/category")
@AllArgsConstructor
public class CategoryController extends BaseController {
    private CategoryService categoryService;
    private CategoryRepo categoryRepo;

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


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

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

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

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

