package com.izouma.nineth.web;
import com.izouma.nineth.domain.PrivilegeOption;
import com.izouma.nineth.service.PrivilegeOptionService;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.PrivilegeOptionRepo;
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("/privilegeOption")
@AllArgsConstructor
public class PrivilegeOptionController extends BaseController {
    private PrivilegeOptionService privilegeOptionService;
    private PrivilegeOptionRepo privilegeOptionRepo;

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


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

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

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

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

