package com.kiisoo.ic.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kiisoo.ic.constants.Constants;
import com.kiisoo.ic.system.bean.LoginPermissionBean;
import com.kiisoo.ic.system.bean.PermissionBean;
import com.kiisoo.ic.system.bean.PermissionBiggestBean;
import com.kiisoo.ic.system.bean.PermissionOutPut;
import com.kiisoo.ic.system.entity.PrivilagePermissionDO;
import com.kiisoo.ic.system.entity.PrivilageRolePermissionDO;
import com.kiisoo.ic.system.enums.PermissionEnum;
import com.kiisoo.ic.system.mapper.PrivilagePermissionDOMapper;
import com.kiisoo.ic.system.mapper.PrivilageRolePermissionDOMapper;
import com.kiisoo.ic.system.service.PrivilagePermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 权限菜单表  服务实现类
 * @author jinchaofan
 * @since 2020-02-19
 */
@Service
public class PrivilagePermissionServiceImpl extends ServiceImpl<PrivilagePermissionDOMapper, PrivilagePermissionDO> implements PrivilagePermissionService {

    private final PrivilagePermissionDOMapper privilagePermissionDOMapper;

    private final PrivilageRolePermissionDOMapper privilageRolePermissionDOMapper;

    @Autowired
    public PrivilagePermissionServiceImpl(PrivilagePermissionDOMapper privilagePermissionDOMapper, PrivilageRolePermissionDOMapper privilageRolePermissionDOMapper) {
        this.privilagePermissionDOMapper = privilagePermissionDOMapper;
        this.privilageRolePermissionDOMapper = privilageRolePermissionDOMapper;
    }

    @Override
    public List<PermissionBiggestBean> listRolePermission(Long roleId) {
        return listRoleHavePermission(roleId);
    }

    @Override
    public List<PermissionBiggestBean> listRoleHavePermission(Long roleId) {
        List<PermissionBiggestBean> allPermission = listAllPermission();
        allPermission.forEach(permission -> {
            //第一级
            Map<String, Object> firstMap = new HashMap<>();
            firstMap.put("role_id", roleId);
            firstMap.put("permission_id", permission.getId());
            List<PrivilageRolePermissionDO> privilageRole = privilageRolePermissionDOMapper.selectByMap(firstMap);
            boolean firstIndeterminate = false;
            //如果存在权限则选中
            if(privilageRole != null && privilageRole.size() > 0) firstIndeterminate = true;
            //全选是否选中
            boolean check = false;
            List<PermissionOutPut> secondList = permission.getSonPermissionList();
            //子权限的数量
            List<Long> firstSon = new ArrayList<>();
            secondList.forEach(permissionSecond -> {
                //第二级
                Map<String, Object> rolePermissionMap = new HashMap<>();
                rolePermissionMap.put("role_id", roleId);
                rolePermissionMap.put("permission_id", permissionSecond.getId());
                List<PrivilageRolePermissionDO> privilageRolePermissionDOS = privilageRolePermissionDOMapper.selectByMap(rolePermissionMap);
                if(privilageRolePermissionDOS != null && privilageRolePermissionDOS.size() > 0) {
                    firstSon.add(permissionSecond.getId());
                }

                boolean indeterminate = false;
                //如果存在权限则选中
                if(privilageRolePermissionDOS != null && privilageRolePermissionDOS.size() > 0) indeterminate = true;
                //全选是否选中
                boolean checkAll = false;
                List<PermissionBean> sonPermissionList = permissionSecond.getSonPermissionList();
                //子权限的数量
                List<Long> sonPermissionArr = new ArrayList<>();
                sonPermissionList.forEach(privilageRolePermissionDO -> {
                    //第三级
                    Map<String, Object> sonPermissionMap = new HashMap<>();
                    sonPermissionMap.put("role_id", roleId);
                    sonPermissionMap.put("permission_id", privilageRolePermissionDO.getId());
                    List<PrivilageRolePermissionDO> privilageRolePermissionDOS1 = privilageRolePermissionDOMapper.selectByMap(sonPermissionMap);
                    if(privilageRolePermissionDOS1 != null && privilageRolePermissionDOS1.size() > 0) {
                        sonPermissionArr.add(privilageRolePermissionDO.getId());
                    }
                });
                if(sonPermissionArr.size() == sonPermissionList.size()) {
                    checkAll = true;
                    indeterminate = false;
                }
                //选中的子权限
                permissionSecond.setCheckArr(sonPermissionArr);
                permissionSecond.setCheck(checkAll);
                permissionSecond.setIndeterminate(indeterminate);
            } );
            if(firstSon.size() == secondList.size()) {
                check = true;
                firstIndeterminate = false;
            }
            //选中的子权限
            permission.setCheckArr(firstSon);
            permission.setCheck(check);
            permission.setIndeterminate(firstIndeterminate);
        });
        return allPermission;
    }

    @Override
    public List<PermissionBiggestBean> listAllPermission() {
        List<PermissionBiggestBean> fatherPermissionList = new ArrayList<>();

        //第一级权限
        QueryWrapper<PrivilagePermissionDO> firstWrapper = new QueryWrapper<>();
        firstWrapper.eq("level", PermissionEnum.PERMISSION_LEVEL_ONE.getType());
        List<PrivilagePermissionDO> firstList = privilagePermissionDOMapper.selectList(firstWrapper);
        firstList.forEach(first -> {
            PermissionBiggestBean permissionBiggestBean = new PermissionBiggestBean();
            permissionBiggestBean.setName(first.getName());
            permissionBiggestBean.setId(first.getId());
            permissionBiggestBean.setParentId(first.getParentId());
            permissionBiggestBean.setResource(first.getName());
            permissionBiggestBean.setLevel(first.getLevel());
            //第二级权限
            List<PermissionOutPut> secondPermission = new ArrayList<>();
            QueryWrapper<PrivilagePermissionDO> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("level", PermissionEnum.PERMISSION_LEVEL_TWO.getType());
            queryWrapper.eq("parent_id", first.getId());
            List<PrivilagePermissionDO> privilagePermissionDOS = privilagePermissionDOMapper.selectList(queryWrapper);
            privilagePermissionDOS.forEach(fatherPermission ->{
                PermissionOutPut permissionOutPut = new PermissionOutPut();
                permissionOutPut.setName(fatherPermission.getName());
                permissionOutPut.setId(fatherPermission.getId());
                permissionOutPut.setParentId(fatherPermission.getParentId());
                permissionOutPut.setResource(fatherPermission.getName());
                permissionOutPut.setLevel(fatherPermission.getLevel());
                QueryWrapper<PrivilagePermissionDO> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("level", PermissionEnum.PERMISSION_LEVEL_THREE.getType());
                queryWrapper2.eq("parent_id", fatherPermission.getId());
                List<PrivilagePermissionDO> privilagePermissionDOS1 = privilagePermissionDOMapper.selectList(queryWrapper2);
                List<PermissionBean> sonPermissionList = new ArrayList<>();
                privilagePermissionDOS1.forEach(sonPermission -> {
                    PermissionBean permissionBean = new PermissionBean();
                    permissionBean.setLevel(sonPermission.getLevel());
                    permissionBean.setId(sonPermission.getId());
                    permissionBean.setName(sonPermission.getName());
                    permissionBean.setParentId(sonPermission.getParentId());
                    permissionBean.setResource(sonPermission.getName());
                    sonPermissionList.add(permissionBean);
                });

                permissionOutPut.setSonPermissionList(sonPermissionList);
                secondPermission.add(permissionOutPut);
            });
            permissionBiggestBean.setSonPermissionList(secondPermission);
            fatherPermissionList.add(permissionBiggestBean);
        });

        return fatherPermissionList;
    }


    @Transactional(rollbackFor=Exception.class)
    @Override
    public boolean saveRolePermission(List<PermissionBiggestBean> permissionOutPuts, Long roleId) {
        //删除所有角色权限
        Map<String, Object> rolePermissionDeleteMap = new HashMap<>();
        rolePermissionDeleteMap.put("role_id", roleId);
        privilageRolePermissionDOMapper.deleteByMap(rolePermissionDeleteMap);
        Set<Long> addPermissionIdList = new HashSet<>();
        permissionOutPuts.forEach(permissionOutPut -> {
            //没有权限
            if(permissionOutPut.getCheckArr() == null || permissionOutPut.getCheckArr().size() == 0) return;
            //添加需要添加的权限集合
            addPermissionIdList.add(permissionOutPut.getId());
            if(permissionOutPut.getParentId() != null) {
                addPermissionIdList.add(permissionOutPut.getParentId());
            }
            addPermissionIdList.addAll(permissionOutPut.getCheckArr());
            permissionOutPut.getSonPermissionList().forEach(permissionOutPut1 -> {
                //没有权限
                if(permissionOutPut1.getCheckArr() == null || permissionOutPut1.getCheckArr().size() == 0) return;
                //添加需要添加的权限集合
                addPermissionIdList.add(permissionOutPut1.getId());
                addPermissionIdList.add(permissionOutPut1.getParentId());
                addPermissionIdList.addAll(permissionOutPut1.getCheckArr());
            });
        });
        //最后添加权限
        addPermissionIdList.forEach(permissionId -> {
            PrivilageRolePermissionDO privilageRolePermissionDO = new PrivilageRolePermissionDO();
            privilageRolePermissionDO.setPermissionId(permissionId);
            privilageRolePermissionDO.setRoleId(roleId);
            privilageRolePermissionDO.setCreateTime(new Date());
            privilageRolePermissionDO.setCreateBy(Constants.SYS_OPERATION);
            privilageRolePermissionDO.setUpdateBy(Constants.SYS_OPERATION);
            privilageRolePermissionDOMapper.insert(privilageRolePermissionDO);
        });
        return false;
    }

    @Override
    public List<LoginPermissionBean> listUserLoginPermission(Long userId, int level) {
        return privilageRolePermissionDOMapper.selectLoginPermission(userId, level);
    }


}
