package com.izouma.jmrh.web;

import com.izouma.jmrh.annotations.OperLog;
import com.izouma.jmrh.domain.ArticleType;
import com.izouma.jmrh.service.ArticleTypeService;
import com.izouma.jmrh.dto.PageQuery;
import com.izouma.jmrh.exception.BusinessException;
import com.izouma.jmrh.repo.ArticleTypeRepo;
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("/articleType")
@AllArgsConstructor
public class ArticleTypeController extends BaseController {
    private ArticleTypeService articleTypeService;
    private ArticleTypeRepo    articleTypeRepo;

    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    @OperLog(value = "类型管理-编辑", type = "编辑")
    public ArticleType save(@RequestBody ArticleType record) {
        if (record.getName() != null) {
            ArticleType orig = articleTypeRepo.findById(record.getName()).orElse(null);
            if (orig != null) {
                ObjUtils.merge(orig, record);
                return articleTypeRepo.save(orig);
            }
        }
        return articleTypeRepo.save(record);
    }


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

    @GetMapping("/get/{id}")
    public ArticleType get(@PathVariable String id) {
        return articleTypeRepo.findById(id).orElseThrow(new BusinessException("无记录"));
    }

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

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

