package com.jkcredit.invoice.hub.service.rolePermission;

import com.jkcredit.invoice.hub.constant.CommonConstant;
import com.jkcredit.invoice.hub.mapper.RolePermissionMapper;
import com.jkcredit.invoice.hub.model.dto.rolePermission.RolePermissionDto;
import com.jkcredit.invoice.hub.model.po.rolePermission.RolePermissionPo;
import com.jkcredit.invoice.hub.service.base.BaseService;
import com.jkcredit.invoice.hub.service.userRolePermission.UserRolePermissionService;
import com.jkcredit.invoice.hub.spi.lang.exception.ServiceException;
import com.jkcredit.invoice.hub.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

/**
 * @description:
 * @author: xusonglin
 * @create: 2020/1/14 22:37
 * @version: V1.0
 **/
@Slf4j
@Service
@Transactional(readOnly = true)
public class RolePermissionServiceImpl extends BaseService implements RolePermissionService {
    @Resource
    RolePermissionMapper rolePermissionMapper;
    @Autowired
    UserRolePermissionService userRolePermissionService;

//    @Override
//    @Transactional(rollbackFor = ServiceException.class)
//    public void saveRolePermission(RolePermissionDto rolePermissionDto) {
//        validate(rolePermissionDto);
//        for (Long permissionId : rolePermissionDto.getPermissionIds()) {
//            RolePermissionPo rolePermissionPo = new RolePermissionPo();
//            rolePermissionPo.setRoleId(rolePermissionDto.getRoleId());
//            rolePermissionPo.setPermissionId(permissionId);
//            rolePermissionPo.setCreateTime(new Date());
//            try {
//                rolePermissionMapper.insert(rolePermissionPo);
//            } catch (Exception e) {
//                log.error("新增角色权限失败，失败原因：{}", e.getMessage());
//                throw new ServiceException("新增角色权限失败");
//            }
//
//        }
//    }

    @Override
    public List<Long> getPermissionsByRoleId(Long roleId) {
        List<Long> permissions;
        try {
            permissions = rolePermissionMapper.getPermissionIdByRoleId(roleId);
        } catch (Exception e) {
            log.error("根据角色ID获取权限失败，失败原因：{}", e.getMessage());
            throw new ServiceException("根据角色ID获取权限失败");
        }
        return permissions;
    }

    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void updateRolePermission(RolePermissionDto rolePermissionDto) {
        validate(rolePermissionDto);
        // 获取角色下所有permissionId
        List<Long> permissions = rolePermissionMapper.getPermissionIdByRoleId(rolePermissionDto.getRoleId());
        if (permissions.size() == 0) {
            // 没有为角色添加过权限，所以直接新增即可
            addRolePermissions(permissions, rolePermissionDto);
        } else {
            // 角色已经添加过权限，判断传入权限，哪些是新增，哪些需要删除

            // 需要新增的权限
            List<Long> addList = CommonUtil.getSubtraction(new HashSet<>(rolePermissionDto.getPermissionIds()), new HashSet<>(permissions));
            // 对角色授权
            addRolePermissions(addList, rolePermissionDto);
            // 对用户角色授权
            userRolePermissionService.saveUserRolePermissionByRoleId(rolePermissionDto.getRoleId(), addList);

            // 需要删除的角色权限
            List<Long> updateList = CommonUtil.getIntersection(new HashSet<>(rolePermissionDto.getPermissionIds()), new HashSet<>(permissions));
            // 删除角色授权
            deleteRolePermissionByRoleId(rolePermissionDto.getRoleId(), updateList);
            // 删除用户角色授权
            userRolePermissionService.updateUserRolePermissionByRoleId(rolePermissionDto.getRoleId(), updateList);
        }
    }

    private void addRolePermissions(List<Long> databasePermissions, RolePermissionDto rolePermissionDto) {
        for (Long permissionId : databasePermissions) {
            RolePermissionPo rolePermissionPo = new RolePermissionPo();
            rolePermissionPo.setRoleId(rolePermissionDto.getRoleId());
            rolePermissionPo.setPermissionId(permissionId);
            rolePermissionPo.setCreateTime(new Date());
            try {
                rolePermissionMapper.insert(rolePermissionPo);
            } catch (Exception e) {
                log.error("新增角色权限失败，失败原因：{}", e.getMessage());
                throw new ServiceException("新增角色权限失败");
            }
        }
    }

    @Override
    public void deleteRolePermissionByRoleId(Long roleId, List<Long> permissionList) {
        try {
            List<RolePermissionPo> rolePermissionPoList = rolePermissionMapper.getPermissionByRoleId(roleId);
            for (RolePermissionPo rolePermissionPo : rolePermissionPoList) {
                for (Long permissionId : permissionList) {
                    if (rolePermissionPo.getPermissionId().equals(permissionId)) {
                        rolePermissionPo.setActivated(CommonConstant.ACTIVATED_DELETED);
                        rolePermissionPo.setUpdateTime(new Date());
                        rolePermissionMapper.updateById(rolePermissionPo);
                    }
                }
            }
        } catch (Exception e) {
            log.error("删除角色权限失败，失败原因：{}", e.getMessage());
            throw new ServiceException("删除角色权限失败");
        }

    }
}
