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

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jkcredit.invoice.hub.controller.base.WebResource;
import com.jkcredit.invoice.hub.controller.web.permission.fb.PermissionFB;
import com.jkcredit.invoice.hub.controller.web.permission.fb.PermissionQueryFB;
import com.jkcredit.invoice.hub.model.dto.permission.PermissionDto;
import com.jkcredit.invoice.hub.model.vo.permission.PermissionVo;
import com.jkcredit.invoice.hub.service.permission.PermissionService;
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.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @description:
 * @author: xusonglin
 * @create: 2020/1/13 16:03
 * @version: V1.0
 **/
@Slf4j
@RestController
public class PermissionResource extends WebResource {
    @Autowired
    PermissionService permissionService;

    @PreAuthorize("hasPermission('permission','read')")
    @GetMapping("/page/permissions")
    public ResponseData getPermissions(Page page, PermissionQueryFB queryFB) {
        try {
            PermissionDto permissionDto = mapper.map(queryFB, PermissionDto.class);
            IPage<PermissionVo> permissions = permissionService.getPermissions(page, permissionDto);
            return ResponseData.success(permissions);
        } catch (ServiceException e) {
            return ResponseData.failed("获取权限列表失败");
        }
    }

    @PreAuthorize("hasPermission('permission','edit')")
    @PostMapping("/permission")
    public ResponseData savePermission(PermissionFB permissionFB) {
        try {
            validate(permissionFB);
            PermissionDto permissionDto = mapper.map(permissionFB, PermissionDto.class);
            permissionService.savePermission(permissionDto);
            return ResponseData.success("新增权限成功");
        } catch (ServiceException e) {
            log.error(e.getMessage());
            return ResponseData.failed("新增权限失败，失败原因" + e.getMessage());
        }
    }

    @PreAuthorize("hasPermission('permission','read')")
    @GetMapping("/permissions")
    public ResponseData getPermissions() {
        try {
            return ResponseData.success(permissionService.getPermissions());
        } catch (ServiceException e) {
            return ResponseData.failed("获取权限列表失败");
        }
    }

}
