package com.izouma.jmrh.web;

import com.izouma.jmrh.domain.AuthorityMenu;
import com.izouma.jmrh.repo.MenuRepo;
import com.izouma.jmrh.service.AuthorityMenuService;
import com.izouma.jmrh.dto.PageQuery;
import com.izouma.jmrh.exception.BusinessException;
import com.izouma.jmrh.repo.AuthorityMenuRepo;
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.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/authorityMenu")
@AllArgsConstructor
public class AuthorityMenuController extends BaseController {

    private AuthorityMenuService authorityMenuService;
    private AuthorityMenuRepo    authorityMenuRepo;
    private MenuRepo             menuRepo;

    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public Map save(@RequestBody AuthorityMenu record) {
        HashMap<String, Object> rest = new HashMap<>();
        rest.put("success", false);
        if (record != null) {
            AuthorityMenu byAuthorityName = authorityMenuRepo.findByAuthorityName(record.getAuthorityName());
            if (byAuthorityName == null) {
                if (authorityMenuRepo.save(record) != null)
                    rest.put("success", true);
            }
            if (authorityMenuRepo.updateByAuthorityName(record.getMenuId(), record.getAuthorityName()) > 0) {
                rest.put("success", true);
            }
        }
        return rest;
    }

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

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

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

    }

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

