package com.foreverwin.mesnac.meapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.foreverwin.mesnac.meapi.mapper.NwaUserMapper;
import com.foreverwin.mesnac.meapi.mapper.UserGroupMapper;
import com.foreverwin.mesnac.meapi.model.NwaUser;
import com.foreverwin.mesnac.meapi.service.NwaUserService;
import com.foreverwin.mesnac.meapi.util.StringUtils;
import com.foreverwin.modular.core.exception.BusinessException;
import com.foreverwin.modular.core.util.CommonMethods;
import com.foreverwin.modular.core.util.FrontPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author robert
 * @since 2021-06-16
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class NwaUserServiceImpl extends ServiceImpl<NwaUserMapper, NwaUser> implements NwaUserService {


    @Autowired
    private NwaUserMapper nwaUserMapper;

    @Autowired
    private UserGroupMapper userGroupMapper;

    @Override
    public IPage<NwaUser> selectPage(FrontPage<NwaUser> frontPage, NwaUser nwaUser) {
        QueryWrapper<NwaUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(nwaUser);
        return super.page(frontPage.getPagePlus(), queryWrapper);
    }

    @Override
    public List<NwaUser> selectList(NwaUser nwaUser) {
        QueryWrapper<NwaUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(nwaUser);
        return super.list(queryWrapper);
    }

    @Override
    public NwaUser findUserByUserName(String user) {
        String site = CommonMethods.getSite();
        return nwaUserMapper.findUserByUserName(site, user);
    }

    @Override
    public List<NwaUser> findAllUser(String site) {
        return nwaUserMapper.findAllUser(site);
    }

    @Override
    public List<NwaUser> checkUserGroup(String site,String userGroups) {
        if(StringUtils.isBlank(site)){
            site = CommonMethods.getSite();
        }
        List<String> item = new ArrayList<String>();
        if(StringUtils.isBlank(userGroups)){
            return null;
        }
        if (!userGroups.contains(",")) {
            item.add(userGroups);
        } else {
            String[] userGroupss = userGroups.split(",");
            item.addAll(Arrays.asList(userGroupss));
        }
        //判断用户组是否输入正确
        int length = userGroupMapper.checkUserGroup(site, item);
        if(item.size() != length){
            throw BusinessException.build("用户组输入不正确");
        }
        //根据用户组找到所有的用户
        List<NwaUser> nwaUsers = nwaUserMapper.selectAllByUserGroups(site, item);
        return nwaUsers;
    }


}