package com.liang.service.impl;


//import com.liang.common.utils.RedisUtil;

import com.liang.entity.LayuiTree;
import com.liang.entity.SysRolePermission;
import com.liang.dao.SysRolePermissionDao;
import com.liang.service.SysRolePermissionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * (SysRolePermission)表服务实现类
 *
 * @author makejava
 * @since 2023-02-19 21:37:39
 */
@Service("sysRolePermissionService")
public class SysRolePermissionServiceImpl implements SysRolePermissionService {
    @Resource
    private SysRolePermissionDao sysRolePermissionDao;

//    @Resource
//    private RedisUtil redisUtil;

    /**
     * 通过ID查询单条数据
     *
     * @param roleId 主键
     * @return 实例对象
     */
    @Override
    public SysRolePermission queryById(Integer roleId) {
        return this.sysRolePermissionDao.queryById(roleId);
    }

    /**
     * 分页查询
     *
     * @param sysRolePermission 筛选条件
     * @param pageRequest       分页对象
     * @return 查询结果
     */
    @Override
    public Page<SysRolePermission> queryByPage(SysRolePermission sysRolePermission, PageRequest pageRequest) {
        long total = this.sysRolePermissionDao.count(sysRolePermission);
        return new PageImpl<>(this.sysRolePermissionDao.queryAllByLimit(sysRolePermission, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param sysRolePermission 实例对象
     * @return 实例对象
     */
    @Override
    public SysRolePermission insert(SysRolePermission sysRolePermission) {
        this.sysRolePermissionDao.insert(sysRolePermission);
        return sysRolePermission;
    }

    /**
     * 修改数据
     *
     * @param sysRolePermission 实例对象
     * @return 实例对象
     */
    @Override
    public SysRolePermission update(SysRolePermission sysRolePermission) {
        this.sysRolePermissionDao.update(sysRolePermission);
        return this.queryById(sysRolePermission.getRoleId());
    }

    /**
     * 通过主键删除数据
     *
     * @param roleId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer roleId) {
        return this.sysRolePermissionDao.deleteById(roleId) > 0;
    }


    @Override
    public Set<String> listRolePermissionByUserId(Integer userId) {
//        String token = SecurityUtil.getUserKey();
//
//        Object object = redisUtil.get(SystemConst.SYSTEM_USER_PERMISSION + ":" + token);
//        if (null != object) {
//            return (Set<String>) object;
//        }
        Set<String> set = sysRolePermissionDao.listRolePermissionByUserId(userId);
//        redisUtil.set(SystemConst.SYSTEM_USER_PERMISSION + ":" + token, set, 1800);

        return set;
    }

    /**
     * 角色权限更新，先删后插
     *
     * @return
     */
    @Override
    @Transactional
    public int doAuthorize(Integer roleId, String permIds) {
        // 先删除sys_role_permission表里之前存的
        int num = sysRolePermissionDao.deleteById(roleId);

        // 再进行重新插入角色权限
        if (StringUtils.isNotBlank(permIds)) {
            String[] permArr = permIds.split(",");
            List<SysRolePermission> list = new ArrayList<>();
            SysRolePermission rolePermission = null;
            for (String item : permArr) {
                rolePermission = new SysRolePermission();
                rolePermission.setRoleId(roleId);
                rolePermission.setPermissionId(item);
                list.add(rolePermission);
            }
            return sysRolePermissionDao.insertBatch(list);
        } else {
            return 0;
        }
    }


    /**
     * 角色赋权，根据角色id获取权限树tree组件
     *
     * @param roleId
     * @return
     */
    @Override
    public Map<String, Object> listPermissionByRoleId(Integer roleId) {
        Map<String, Object> resultMap = new HashMap<>();
        List<LayuiTree> list = sysRolePermissionDao.listPermissionByRoleId(roleId);
        if (null == list || list.isEmpty()) {
            resultMap.put("data", null);
            resultMap.put("code", 0);
            resultMap.put("msg", "");
            return resultMap;
        }

        List<LayuiTree> resultList = toTree(list, "0");
        resultMap.put("data", resultList);
        resultMap.put("code", 0);
        resultMap.put("msg", "");
        return resultMap;
    }


    /**
     * 获取菜单树(list转tree)
     *
     * @param treeList
     * @param pid
     * @return
     */
    public static List<LayuiTree> toTree(List<LayuiTree> treeList, String pid) {
        List<LayuiTree> retList = new ArrayList<>();
        for (LayuiTree parent : treeList) {
            if (pid.equals(parent.getParentId())) {
                retList.add(findChildren(parent, treeList));
            }
        }
        return retList;
    }

    /**
     * 递归获取子节点
     *
     * @param parent
     * @param treeList
     * @return
     */
    private static LayuiTree findChildren(LayuiTree parent, List<LayuiTree> treeList) {
        for (LayuiTree child : treeList) {
            if (parent.getPermissionId().equals(child.getParentId())) {
                // 这里是为了将父节点的选中状态置为false，为了适配前端eleTree
                // parent.setChecked(false); // eleTree设置了isDefaultChangePstatus属性，好像就不需要这么干了
                if (parent.getChildren() == null) {
                    parent.setChildren(new ArrayList<>());
                }
                parent.getChildren().add(findChildren(child, treeList));
            }
        }
        return parent;
    }
}
