package com.izouma.jmrh.web;

import com.izouma.jmrh.repo.AuthorityMenuRepo;
import com.izouma.jmrh.security.Authority;
import com.izouma.jmrh.service.AuthorityService;
import com.izouma.jmrh.dto.PageQuery;
import com.izouma.jmrh.exception.BusinessException;
import com.izouma.jmrh.repo.AuthorityRepo;
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("/authority")
@AllArgsConstructor
public class AuthorityController extends BaseController {
    private AuthorityService authorityService;
    private AuthorityRepo authorityRepo;

    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public Authority save(@RequestBody Authority record) {
        if (record!=null){
            if (!record.getName().substring(1,5).equals("ROLE_")){
                record.setName("ROLE_"+record.getName());
            }
        }
        return authorityRepo.save(record);
    }


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

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

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

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

