package com.kiisoo.ic.system.controller;


import com.alibaba.fastjson.JSONObject;
import com.kiisoo.ic.common.BaseController;
import com.kiisoo.ic.system.bean.LoginPermissionBean;
import com.kiisoo.ic.system.bean.PermissionBiggestBean;
import com.kiisoo.ic.system.bean.PermissionOutPut;
import com.kiisoo.ic.system.service.PrivilagePermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 权限菜单  前端控制器
 * @author jinchaofan
 * @since 2020-02-19
 */
@Slf4j
@RestController
@RequestMapping("/permission")
public class PrivilagePermissionController extends BaseController {

    /**
     * 权限 service
     */
    private final PrivilagePermissionService privilagePermissionService;

    @Autowired
    public PrivilagePermissionController(PrivilagePermissionService privilagePermissionService) {
        this.privilagePermissionService = privilagePermissionService;
    }

    /**
     * 查询角色的权限
     * @param roleId 角色id
     * @return 角色的权限
     */
    @ResponseBody
    @PostMapping("/role/list")
    public Map<String, Object> listRolePermission(@RequestParam("roleId") Long roleId) {
        try {
            List<PermissionBiggestBean> permissionOutPuts = privilagePermissionService.listRolePermission(roleId);
            return data(permissionOutPuts);
        } catch (Exception e){
            log.error("查询角色的权限出错", e);
            return fail();
        }
    }

    /**
     * 保存权限
     * @param permissionJson 权限集合
     * @param roleId 角色id
     * @return 是否成功
     */
    @ResponseBody
    @PostMapping("/role/save")
    public Map<String, Object> saveRolePermission(@RequestParam("roleId") Long roleId,
                                                  @RequestParam("permissionJson") String permissionJson) {
        try {
            List<PermissionBiggestBean> permissionOutPuts = JSONObject.parseArray(permissionJson, PermissionBiggestBean.class);
            boolean flag = privilagePermissionService.saveRolePermission(permissionOutPuts, roleId);
            return data(flag);
        } catch (Exception e){
            log.error("查询角色的权限出错", e);
            return fail();
        }
    }

    /**
     * 查询用户登录权限
     * @param userId 用户id
     * @param level 等级
     * @return 用户登录权限
     */
    @ResponseBody
    @GetMapping("/user/login/list")
    public Map<String, Object> listUserLoginPermission(@RequestParam("userId") Long userId,
                                                       @RequestParam("level") int level) {
        try {
            List<LoginPermissionBean> loginPermissionBeans = privilagePermissionService.listUserLoginPermission(userId, level);
            return data(loginPermissionBeans);
        } catch (Exception e){
            log.error("查询用户登录权限出错", e);
            return fail();
        }
    }


}
