package com.enterprise.manage.modules.system.controller;

import com.enterprise.manage.core.annotation.Log;
import com.enterprise.manage.common.base.BaseController;
import com.enterprise.manage.common.constant.ControllerConstant;
import com.enterprise.manage.common.constant.emuns.OperationType;
import com.enterprise.manage.common.tools.secure.SecurityUtil;
import com.enterprise.manage.common.web.request.PageDomain;
import com.enterprise.manage.common.web.response.Result;
import com.enterprise.manage.common.web.response.module.ResultTable;
import com.enterprise.manage.modules.system.domain.po.Menu;
import com.enterprise.manage.modules.system.domain.po.Role;
import com.enterprise.manage.modules.system.service.IMenuService;
import com.enterprise.manage.modules.system.service.IRoleService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * System role controller
 *
 * @author PeiZhi Guo
 * 2021-2-8 14:59
 */
@RestController
@RequestMapping(ControllerConstant.SYSTEM + "role/v1")
public class RoleController extends BaseController {

    private IRoleService roleService;

    private IMenuService menuService;

    @Autowired
    public RoleController(IRoleService roleService, IMenuService menuService) {
        this.roleService = roleService;
        this.menuService = menuService;
    }

    @GetMapping
    @PreAuthorize("hasPermission('','sys:role:main')")
    public ResultTable main(PageDomain page, Role role) {
        PageInfo<Role> rolePage = roleService.page(page, role);
        return pageTable(rolePage.getList(), rolePage.getTotal());
    }

    @GetMapping("{id}")
    @PreAuthorize("hasPermission('','sys:role:main')")
    public Result get(@PathVariable Long id) {
        return success(roleService.queryById(id));
    }

    @GetMapping("getEnableRoles")
    public Result getEnabledRoles() {
        Role role = new Role();
        role.setEnable(1);
        List<Role> roles = roleService.list(role);
        return success(roles);
    }

    @GetMapping("grant/{id}")
    public Result grant(@PathVariable Long id) {
        Map<String, Object> map = new HashMap<>();
        Role role = roleService.queryById(id);
        List<Menu> menuList = menuService.queryRolePermission(id);
        map.put("role", role);
        map.put("menuList", menuList);
        return success(map);
    }

    @PostMapping
    @PreAuthorize("hasPermission('','sys:role:add')")
    @Log(operationType = OperationType.INSERT , title = "角色管理")
    public Result save(Role role) {
        if (roleService.getCountByName(role.getName()) > 0) {
            return failure("该角色名已存在");
        }
        role.insertConfigure();
        return decide(roleService.save(role));
    }

    @PutMapping
    @PreAuthorize("hasPermission('','sys:role:edit')")
    @Log(operationType = OperationType.UPDATE , title = "角色管理")
    public Result edit(Role role) {
        Role oldRole = roleService.queryById(role.getId());
        if (!oldRole.getName().equals(role.getName())) {
            Integer count = roleService.getCountByName(role.getName());
            if (count > 0) {
                return failure("该角色名已存在");
            }
        }
        role.setUpdateBy(SecurityUtil.getCurrentUser().getId());
        return decide(roleService.update(role));
    }

    @DeleteMapping("{ids}")
    @PreAuthorize("hasPermission('','sys:role:del')")
    @Log(operationType = OperationType.DELETE , title = "角色管理")
    public Result remove(@PathVariable String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        for (String id : idList) {
            if ("1".equals(id)) {
                return failure("不允许删除超级管理员");
            }
        }
        for (String id : idList) {
            roleService.deleteRole(Integer.valueOf(id));
        }
        return success();
    }

    @PutMapping("grant")
    @PreAuthorize("hasPermission('','sys:role:grant')")
    @Log(operationType = OperationType.GRANT, title = "角色管理")
    public Result grantAuth(@RequestBody Role role) {
        Boolean result = roleService.updateRoleMenu(role);
        return decide(result);
    }
}
