package com.tuoheng.service.op.Impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tuoheng.constant.CommonConstant;
import com.tuoheng.enums.MarkTypeEnum;
import com.tuoheng.mapper.ClientUserMapper;
import com.tuoheng.mapper.op.*;
import com.tuoheng.model.dto.LoginUser;
import com.tuoheng.model.dto.RoleMenuDto;
import com.tuoheng.model.dto.RoleMenuPermissionDto;
import com.tuoheng.model.entity.*;
import com.tuoheng.model.po.UserPo;
import com.tuoheng.model.query.RoleClientQuery;
import com.tuoheng.model.query.RoleQuery;
import com.tuoheng.model.vo.MenuVo;
import com.tuoheng.model.vo.OpPermissionsVo;
import com.tuoheng.model.vo.RoleListVo;
import com.tuoheng.service.op.RoleMenuService;
import com.tuoheng.service.op.RolePermissionService;
import com.tuoheng.service.op.RolesService;
import com.tuoheng.until.JsonResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 小影
 * @description 针对表【op_roles】的数据库操作Service实现
 * @createDate 2023-03-20 14:55:52
 */
@Service
public class RolesServiceImpl extends ServiceImpl<RolesMapper, Roles>
        implements RolesService {

    @Autowired
    private RolesMapper rolesMapper;
    @Autowired
    private RoleMenuMapper roleMenuMapper;
    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    @Autowired
    private ClientUserMapper clientUserMapper;
    @Autowired
    private MenusMapper menusMapper;
    @Autowired
    private PermissionsMapper permissionsMapper;
    @Autowired
    private RoleMenuService roleMenuService;
    @Autowired
    private RolePermissionService rolePermissionService;


    /**
     * 获取角色列表
     *
     * @param query 查询条件
     * @return
     */
    @Override
    public JsonResult getList(RoleQuery query) {
        query.checkParam();
        IPage<Roles> page = new Page<>(query.getPage(), query.getLimit());
        // 查询条件
        IPage<Roles> pageData = rolesMapper.selectPage(page, Wrappers.<Roles>lambdaQuery()
                .like(ObjectUtil.isNotEmpty(query.getRoleName()), Roles::getRoleName, query.getRoleName())
                .eq(Roles::getMark, MarkTypeEnum.VALID.getCode())
                .orderByDesc(Roles::getCreateTime));
        pageData.convert(x -> {
            RoleListVo vo = Convert.convert(RoleListVo.class, x);
            // TODO...
            return vo;
        });
        return JsonResult.success(pageData);
    }

    /**
     * 添加或编辑
     *
     * @param entity 实体对象
     * @return
     */
    @Override
    public JsonResult edit(Roles entity, LoginUser loginUser) {
        //新增
        boolean flag = false;
        if (ObjectUtil.isNull(entity.getId())) {
            entity.setCreateUser(loginUser.getUserId().intValue());
            flag = this.save(entity);
        } else {
            entity.setUpdateUser(loginUser.getUserId().intValue());
            flag = this.updateById(entity);
        }
        if (!flag) {
            return JsonResult.error();
        }
        return JsonResult.success();
    }


    /**
     * 删除角色,限制
     *
     * @param roleIds
     * @return
     */
    @Override
    public JsonResult deleteByList(Integer[] roleIds) {

        for (Integer roleId : roleIds) {
            List<RoleMenu> roleMenus = roleMenuMapper.selectList(Wrappers.<RoleMenu>lambdaQuery()
                    .eq(RoleMenu::getRoleId, roleId)
                    .eq(RoleMenu::getMark, MarkTypeEnum.VALID.getCode()));
            if (CollectionUtil.isNotEmpty(roleMenus)) {
                return JsonResult.error("该角色已配置菜单不能删除!");
            }
            List<RolePermission> opRolePermissionList = rolePermissionMapper.selectList(Wrappers.<RolePermission>lambdaQuery()
                    .eq(RolePermission::getRoleId, roleId)
                    .eq(RolePermission::getMark, MarkTypeEnum.VALID.getCode()));
            if (CollectionUtil.isNotEmpty(opRolePermissionList)) {
                return JsonResult.error("该角色已配置权限不能删除!");
            }
            List<UserPo> list = clientUserMapper.getUserByRoleId(roleId);
            if (CollectionUtil.isNotEmpty(list)) {
                return JsonResult.error("该角色已经分配用户不能删除!");
            }
            Roles role = rolesMapper.selectById(roleId);
            role.setMark(MarkTypeEnum.NOTVALID.getCode());
            rolesMapper.updateById(role);
        }
        return JsonResult.success();
    }

    /**
     * 获取菜单列表
     *
     * @param query
     * @return
     */
    @Override
    public JsonResult getMenuList(RoleClientQuery query) {


        RoleMenuPermissionDto dto = new RoleMenuPermissionDto();
        Integer roleId = query.getRoleId();
        List<Menu> menuList = menusMapper.selectList(Wrappers.<Menu>lambdaQuery()
                .eq(Menu::getMark, MarkTypeEnum.VALID.getCode())
                .eq(Menu::getStatus, CommonConstant.ONE)
                .orderByAsc(Menu::getSort));
        if (!menuList.isEmpty()) {
            // 获取角色菜单列表
            List<RoleMenu> roleMenuList = roleMenuMapper.selectList(Wrappers.<RoleMenu>lambdaQuery()
                    .eq(RoleMenu::getRoleId, roleId)
                    .select(RoleMenu::getMenuId));
            List<Integer> menuIds = roleMenuList.stream().map(p -> p.getMenuId()).collect(Collectors.toList());
            menuList.forEach(item -> {
                if (menuIds.contains(item.getId())) {
                    item.setChecked(true);
                    item.setOpen(true);
                }
            });
        }
        List<MenuVo> collect = menuList.stream().map(t -> {
            MenuVo menusVo = new MenuVo();
            BeanUtils.copyProperties(t, menusVo);
            menusVo.setIdentificationId(t.getId().toString());
            return menusVo;
        }).collect(Collectors.toList());

        dto.setOpMenusList(collect);
        //根据小程序或者pc标识
        List<Permissions> permissions = permissionsMapper.selectList(Wrappers.<Permissions>lambdaQuery()
                .eq(Permissions::getMark, MarkTypeEnum.VALID.getCode()));

        if (!permissions.isEmpty()) {
            // 获取角色菜单列表
            List<RolePermission> rolePermissions = rolePermissionMapper.selectList(Wrappers.<RolePermission>lambdaQuery()
                    .eq(RolePermission::getRoleId, roleId)
                    .select(RolePermission::getPermissionId));
            List<Integer> permissionIds = rolePermissions.stream().map(p -> p.getPermissionId()).collect(Collectors.toList());
            permissions.forEach(item -> {
                if (permissionIds.contains(item.getId())) {
                    item.setChecked(true);
                    item.setOpen(true);
                }
            });
        }

        List<OpPermissionsVo> collect1 = permissions.stream().map(t -> {
            OpPermissionsVo vo = new OpPermissionsVo();
            BeanUtils.copyProperties(t, vo);
            //用"_"进行区分
            vo.setIdentificationId(t.getMenuId() + CommonConstant.UNDERLINE + t.getId());
            return vo;
        }).collect(Collectors.toList());

        dto.setPermissionsList(collect1);
        dto.setRoleId(roleId);

        return JsonResult.success(dto);
    }

    /**
     * 保存角色菜单权限数据
     *
     * @param roleMenuDto 角色菜单Dto
     * @return
     */
    @Override
    public JsonResult savePermission(RoleMenuDto roleMenuDto) {
        // 角色ID校验
        if (ObjectUtil.isNull(roleMenuDto.getRoleId())) {
            return JsonResult.error("角色ID不能位空");
        }
        // 同步删除角色菜单,权限关系数据
        roleMenuMapper.delete(Wrappers.<RoleMenu>lambdaQuery().eq(RoleMenu::getRoleId, roleMenuDto.getRoleId()));
        rolePermissionMapper.delete(Wrappers.<RolePermission>lambdaQuery().eq(RolePermission::getRoleId, roleMenuDto.getRoleId()));

        // 插入新的角色菜单关系数据and权限
        List<RoleMenu> roleMenuList = new ArrayList<>();
        List<RolePermission> permissions = new ArrayList<>();
        if (roleMenuDto.getIds().length > 0) {
            for (String id : roleMenuDto.getIds()) {
                if (id.contains(CommonConstant.UNDERLINE)) {
                    id = id.split(CommonConstant.UNDERLINE)[CommonConstant.ONE];
                    RolePermission opRolePermission = new RolePermission();
                    opRolePermission.setRoleId(roleMenuDto.getRoleId());
                    opRolePermission.setPermissionId(Integer.parseInt(id));
                    permissions.add(opRolePermission);
                } else {
                    RoleMenu roleMenu = new RoleMenu();
                    //roleMenu.setTenantId(ShiroUtils.getTenantId());
                    roleMenu.setRoleId(roleMenuDto.getRoleId());
                    roleMenu.setMenuId(Integer.parseInt(id));
                    roleMenuList.add(roleMenu);
                }
            }
        }
        // 批量插入角色菜单关系数据
        roleMenuService.saveBatch(roleMenuList);
        rolePermissionService.saveBatch(permissions);
        return JsonResult.success();
    }
}




