package com.jkcredit.invoice.hub.controller.web.rolePermission;

import com.jkcredit.invoice.hub.controller.base.WebResource;
import com.jkcredit.invoice.hub.controller.web.rolePermission.fb.RolePermissionFB;
import com.jkcredit.invoice.hub.model.dto.rolePermission.RolePermissionDto;
import com.jkcredit.invoice.hub.service.rolePermission.RolePermissionService;
import com.jkcredit.invoice.hub.spi.lang.exception.ServiceException;
import com.jkcredit.invoice.hub.spi.web.data.ResponseData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.xml.ws.Service;

/**
 * @description:
 * @author: xusonglin
 * @create: 2020/1/14 22:54
 * @version: V1.0
 **/
@Slf4j
@RestController
public class RolePermissionResource extends WebResource {
    @Autowired
    RolePermissionService rolePermissionService;

    @PreAuthorize("hasPermission('permission','edit')")
    @PostMapping("/rolePermission")
    public ResponseData addRolePermission(@RequestBody RolePermissionFB rolePermissionFB) {
        try {
            validate(rolePermissionFB);
            RolePermissionDto dto = mapper.map(rolePermissionFB, RolePermissionDto.class);
            rolePermissionService.updateRolePermission(dto);
            return ResponseData.success("操作成功");
        } catch (ServiceException e) {
            return ResponseData.failed("操作失败，失败原因" + e.getMessage());
        }
    }

    @PreAuthorize("hasPermission('permission','read')")
    @GetMapping("/rolePermissions/{roleId}")
    public ResponseData getRolePermissionsByRoleId(@PathVariable Long roleId) {
        try {
            return ResponseData.success(rolePermissionService.getPermissionsByRoleId(roleId));
        } catch (ServiceException se) {
            return ResponseData.failed("获取权限失败，失败原因" + se.getMessage());
        }
    }
}
