package jnpf.authority.controller;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fantaibao.permission.handling.PermissionHandling;
import jnpf.authority.service.FtbPermissionRoleService;
import jnpf.base.ActionResult;
import jnpf.base.SystemApi;
import jnpf.base.UserInfo;
import jnpf.base.entity.SystemEntity;
import jnpf.base.model.module.ModuleModel;
import jnpf.base.vo.PageListVO;
import jnpf.model.UserMenuModel;
import jnpf.model.authority.dto.menu.FtbPermissionRoleAddDTO;
import jnpf.model.authority.dto.role.FtbPermissionDataDTO;
import jnpf.model.authority.dto.role.FtbPermissionRoleCopyDTO;
import jnpf.model.authority.dto.role.FtbPermissionRoleInfoDTO;
import jnpf.model.authority.dto.role.FtbPermissionRoleUpdateDTO;
import jnpf.model.authority.vo.role.FtbPermissionRoleDetailsVO;
import jnpf.model.authority.vo.role.FtbPermissionRoleIdentificationVO;
import jnpf.model.authority.vo.role.FtbPermissionRoleInfoVO;
import jnpf.model.cultivate.CultivatePage;
import jnpf.model.cultivate.vo.common.InnerPowerUserVO;
import jnpf.model.login.MenuTreeVO;
import jnpf.permission.AuthorizeApi;
import jnpf.permission.model.authorize.AuthorizeVO;
import jnpf.util.JsonUtil;
import jnpf.util.UserProvider;
import jnpf.util.treeutil.SumTree;
import jnpf.util.treeutil.newtreeutil.TreeDotUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * web权限管理角色模块
*
* @author xxxxx
*/
@Slf4j
@RestController
@RequestMapping("/web/permission-role")
public class FtbPermissionRoleController {

    @Resource
    private FtbPermissionRoleService ftbPermissionRoleService;

    @Autowired
    private AuthorizeApi authorizeApi;

    @Autowired
    private SystemApi systemApi;

    @Autowired
    private PermissionHandling permissionHandling;

    /**
     * 新增角色
     */
    @PostMapping("/add-role")
    public ActionResult<Void> addRole(@RequestBody @Validated FtbPermissionRoleAddDTO ftbPermissionRole) {
        ftbPermissionRoleService.addRole(ftbPermissionRole);
        return ActionResult.success();
    }

    /**
     * 编辑角色
     */
    @PutMapping("/edit-role")
    public ActionResult<Void> editRole(@RequestBody @Validated FtbPermissionRoleUpdateDTO roleUpdateDTO) {
        ftbPermissionRoleService.editRole(roleUpdateDTO);
        return ActionResult.success();
    }

    /**
     * 删除角色
     *
     * @param id 角色主键Id必传
     */
    @DeleteMapping("/delete-role/{id}")
    public ActionResult<Void> deleteRole(@PathVariable(value = "id") String id) {
        ftbPermissionRoleService.deleteRole(id);
        return ActionResult.success();
    }

    /**
     * 角色列表
     *
     * @return {@link ActionResult }<{@link PageListVO }<{@link FtbPermissionRoleInfoVO }>>
     */
    @GetMapping("/role-list")
    public ActionResult<PageListVO<FtbPermissionRoleInfoVO>> permissionList(CultivatePage cultivatePage,
                                                                            FtbPermissionRoleInfoDTO roleInfoDTO) {
        Page<FtbPermissionRoleInfoVO> page = cultivatePage.coverCultivatePage();
        page = ftbPermissionRoleService.permissionList(page, roleInfoDTO);
        PageListVO<FtbPermissionRoleInfoVO> result = CultivatePage.coverPageList(page);
        return ActionResult.success(result);
    }

    /**
     * 员工已有的功能权限标识集合
     */
    @GetMapping("/permission-identification-collection")
    public ActionResult<FtbPermissionRoleIdentificationVO> permissionIdentificationCollection() {
        FtbPermissionRoleIdentificationVO result = ftbPermissionRoleService.permissionIdentificationCollection();
        return ActionResult.success(result);
    }

    /**
     * 角色详情
     *
     * @param roleId    角色ID
     * @param menuWebId 菜单Web ID
     * @param menuAppId 菜单APP ID
     * @param menuPcId 菜单PC ID
     * @return {@link ActionResult }<{@link FtbPermissionRoleInfoVO }>
     */
    @GetMapping("/role-details")
    public ActionResult<FtbPermissionRoleDetailsVO> roleDetails(String roleId, String menuWebId, String menuAppId, String menuPcId) {
        FtbPermissionRoleDetailsVO ftbPermissionRole = ftbPermissionRoleService.roleDetails(roleId, menuWebId, menuAppId,menuPcId);
        return ActionResult.success(ftbPermissionRole);
    }

    /**
     * 获取当前人员的数据权限范围
     *
     * @return
     */
    @GetMapping("/query-user-scope-permission")
    public Map<String, String> queryUserScopeOfPermission(@RequestParam("userId") String userId) {
        return ftbPermissionRoleService.queryUserScopeOfPermissionNoTenant(userId);
    }

    /**
     * 复制角色
     */
    @PostMapping("/copy-role")
    public ActionResult<Void> copyRole(@RequestBody @Validated FtbPermissionRoleCopyDTO ftbPermissionRole) {
        ftbPermissionRoleService.copyRole(ftbPermissionRole);
        return ActionResult.success();
    }

    /**
    * 数据权限应用至其他模块
    */
    @PostMapping("/data-permission-application-to-other-modules")
    public ActionResult<Void> dataPermissionApplicationToOtherModules(@RequestBody @Validated FtbPermissionDataDTO ftbPermissionDataDTO) {
        ftbPermissionRoleService.dataPermissionApplicationToOtherModules(ftbPermissionDataDTO);
        return ActionResult.success();
    }

    /**
     *  根据token获取用户菜单列表
     * @return
     */
    @GetMapping("/obtain-menus-on-token")
    public ActionResult<List<MenuTreeVO>> obtainTheListOfUserMenusBasedOnTheToken(String type) {
        type = StringUtils.isEmpty(type) ? "Web" : type;
        AuthorizeVO authorizeModel = authorizeApi.getAuthorize(false);
        // 获取菜单权限
        List<ModuleModel> moduleList = authorizeModel.getModuleList();
        String systemId = "App".equals(type) ? UserProvider.getUser().getAppSystemId() : UserProvider.getUser().getSystemId();
        boolean isNormalPlatform = true;
        if (!"App".equals(type)) {
            moduleList = moduleList.stream().filter(t -> t.getSystemId() != null && t.getSystemId().equals(systemId)).collect(Collectors.toList());
            // 判断是否为Web
            // 判断是否需要切换系统
            if (moduleList.size() > 0) {
                String systemId1 = moduleList.get(0).getSystemId();
                SystemEntity  systemEntity = systemApi.getInfoById(systemId1);
                if (systemEntity.getIsMain() == 1) {
                    isNormalPlatform = false;
                }
                if (systemEntity.getEnabledMark() == 0) {
                    moduleList = new ArrayList<>();
                }
            }
        }
        String finalType = type;
        List<ModuleModel> menuList = moduleList.stream().filter(t -> finalType.equals(t.getCategory())).sorted(Comparator.comparing(ModuleModel::getSortCode)).collect(Collectors.toList());
        UserInfo user = UserProvider.getUser();
        if (!user.getIsAdministrator()) {
            // 登录时 实时查询用户当前的数据权限范围
            Set<String> menuPermissions = ftbPermissionRoleService.queryTheLatestListOfMenuPermissions(user.getUserId());
            // 获取登陆时的缓存菜单
            if (CollUtil.isNotEmpty(menuPermissions) && isNormalPlatform) {
                // 过滤权限菜单
                menuList = menuList.stream().filter(t -> menuPermissions.contains(t.getId())).collect(Collectors.toList());
            }
        }
        List<UserMenuModel> menu = JsonUtil.getJsonToList(menuList, UserMenuModel.class);
        List<SumTree<UserMenuModel>> menus = TreeDotUtils.convertListToTreeDot(menu, "-1");
        //返回前台tree的list
        List<MenuTreeVO> list = JsonUtil.getJsonToList(menus, MenuTreeVO.class);
        log.debug("用户菜单：{}", list);
        return ActionResult.success(list);
    }

    /**
     * 根据模块编码获取当前人员的数据权限范围
     *
     * @return
     */
    @GetMapping("/query-user-scope-permission-for-module-code")
    public InnerPowerUserVO queryUserScopeOfPermissionForModuleCode() {
        InnerPowerUserVO vo = new InnerPowerUserVO();
        UserInfo userInfo = UserProvider.getUser();
        if (userInfo.getIsAdministrator()) {
            vo.setCode(0);
            return vo;
        }
        try {
            //往header中添加一个字段
            List<String> userIds = permissionHandling.getUserIdsByUserId(userInfo.getUserId());
            // 权限适用范围为全部
            if (userIds == null) {
                vo.setCode(0);
                return vo;
            }
            if (userIds.isEmpty()) {
                vo.setCode(2);
                return vo;
            }
            vo.setCode(1);
            vo.setUserIds(userIds);
        } catch (Exception e) {
            vo.setCode(2);
            return vo;
        }
        return vo;
    }
}
