package com.izouma.nineth.web;
import com.izouma.nineth.domain.CollectionPrivilege;
import com.izouma.nineth.service.CollectionPrivilegeService;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.CollectionPrivilegeRepo;
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.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("/collectionPrivilege")
@AllArgsConstructor
public class CollectionPrivilegeController extends BaseController {
    private CollectionPrivilegeService collectionPrivilegeService;
    private CollectionPrivilegeRepo collectionPrivilegeRepo;

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


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

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

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

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

