package org.linlinjava.jz.db.service;

import org.linlinjava.jz.db.dao.JzPermissionMapper;
import org.linlinjava.jz.db.dao.JzRoleMapper;
import org.linlinjava.jz.db.domain.JzPermission;
import org.linlinjava.jz.db.domain.JzPermissionExample;
import org.linlinjava.jz.db.domain.JzRole;
import org.linlinjava.jz.db.domain.JzRoleExample;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 商城 系统权限
 */
@Service
public class JzPermissionService {
    @Resource
    private JzPermissionMapper permissionMapper;

    public Set<String> queryByRoleIds(Integer[] roleIds) {
        Set<String> permissions = new HashSet<String>();
        if(roleIds.length == 0){
            return permissions;
        }

        JzPermissionExample example = new JzPermissionExample();
        example.or().andRoleIdIn(Arrays.asList(roleIds)).andDeletedEqualTo(false);
        List<JzPermission> permissionList = permissionMapper.selectByExample(example);

        for(JzPermission permission : permissionList){
            permissions.add(permission.getPermission());
        }

        return permissions;
    }


    public Set<String> queryByRoleId(Integer roleId) {
        Set<String> permissions = new HashSet<String>();
        if(roleId == null){
            return permissions;
        }

        JzPermissionExample example = new JzPermissionExample();
        example.or().andRoleIdEqualTo(roleId).andDeletedEqualTo(false);
        List<JzPermission> permissionList = permissionMapper.selectByExample(example);

        for(JzPermission permission : permissionList){
            permissions.add(permission.getPermission());
        }

        return permissions;
    }

    public boolean checkSuperPermission(Integer roleId) {
        if(roleId == null){
            return false;
        }

        JzPermissionExample example = new JzPermissionExample();
        example.or().andRoleIdEqualTo(roleId).andPermissionEqualTo("*").andDeletedEqualTo(false);
        return permissionMapper.countByExample(example) != 0;
    }

    public void deleteByRoleId(Integer roleId) {
        JzPermissionExample example = new JzPermissionExample();
        example.or().andRoleIdEqualTo(roleId).andDeletedEqualTo(false);
        permissionMapper.logicalDeleteByExample(example);
    }

    public void add(JzPermission JzPermission) {
        JzPermission.setAddTime(LocalDateTime.now());
        JzPermission.setUpdateTime(LocalDateTime.now());
        permissionMapper.insertSelective(JzPermission);
    }
}
