package cn.exploring.engine.server.db.service;

import cn.exploring.engine.server.db.dao.AdminRoleMapper;
import cn.exploring.engine.server.db.domain.AdminRole;
import cn.exploring.engine.server.db.domain.AdminRoleExample;
import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.PageHelper;
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 AdminRoleService {
    @Resource
    private AdminRoleMapper roleMapper;


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

        AdminRoleExample example = new AdminRoleExample();
        example.or().andIdIn(Arrays.asList(roleIds)).andEnabledEqualTo(true).andDeletedEqualTo(false);
        List<AdminRole> roleList = roleMapper.selectByExample(example);

        for(AdminRole role : roleList){
            roles.add(role.getName());
        }

        return roles;

    }

    public List<AdminRole> querySelective(String roleName, Integer page, Integer size, String sort, String order) {
        AdminRoleExample example = new AdminRoleExample();
        AdminRoleExample.Criteria criteria = example.createCriteria();

        if (!StringUtils.isEmpty(roleName)) {
            criteria.andNameEqualTo("%" + roleName + "%");
        }
        criteria.andDeletedEqualTo(false);

        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            example.setOrderByClause(sort + " " + order);
        }

        PageHelper.startPage(page, size);
        return roleMapper.selectByExample(example);
    }

    public AdminRole findById(Integer id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    public void add(AdminRole role) {
        role.setAddTime(LocalDateTime.now());
        role.setUpdateTime(LocalDateTime.now());
        roleMapper.insertSelective(role);
    }

    public void deleteById(Integer id) {
        roleMapper.logicalDeleteByPrimaryKey(id);
    }

    public void updateById(AdminRole role) {
        role.setUpdateTime(LocalDateTime.now());
        roleMapper.updateByPrimaryKeySelective(role);
    }

    public boolean checkExist(String name) {
        AdminRoleExample example = new AdminRoleExample();
        example.or().andNameEqualTo(name).andDeletedEqualTo(false);
        return roleMapper.countByExample(example) != 0;
    }

    public List<AdminRole> queryAll() {
        AdminRoleExample example = new AdminRoleExample();
        example.or().andDeletedEqualTo(false);
        return roleMapper.selectByExample(example);
    }
}
