package com.boman.system.service.impl;

import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.boman.common.core.exception.CustomException;
import com.boman.common.core.utils.SecurityUtils;
import com.boman.common.core.utils.StringUtils;
import com.boman.common.core.utils.array.ArrayUtils;
import com.boman.common.core.utils.obj.ObjectUtils;
import com.boman.common.datascope.annotation.DataScope;
import com.boman.domain.*;
import com.boman.domain.constant.UserConstants;
import com.boman.domain.dto.AjaxResult;
import com.boman.system.domain.vo.TreeSelect;
import com.boman.system.mapper.*;
import com.boman.system.service.IBomanGroupService;
import com.google.common.collect.Lists;
import org.apache.poi.ss.formula.functions.T;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 自定义组 服务实现
 *
 * @author ruoyi
 */
@Service
public class BomanGroupServiceImpl implements IBomanGroupService {
    @Autowired
    private BomanGroupMapper groupMapper;

    @Autowired
    private BomanGroupUserMapper groupUserMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 查询自定义组数据
     *
     * @param bomanGroup 自定义组
     * @return 自定义组集合
     */
    @Override
    @DataScope(deptAlias = "g")
    public List<BomanGroup> selectGroupList(BomanGroup bomanGroup) {
        return groupMapper.selectGroupList(bomanGroup);
    }

    /**
     * 根据组织id查询信息
     *
     * @param id
     * @return
     */
    @Override
    public BomanGroup selectGroupById(Long id) {
        return groupMapper.selectGroupById(id);
    }

    /**
     * 查询组织是否存在用户
     *
     * @param ids 组织ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkGroupExistUser(Long[] ids) {
        int result = groupMapper.checkGroupExistUser(ids);
        return result > 0 ? true : false;
    }

    /**
     * 校验组织名称是否唯一
     *
     * @param bomanGroup 组织信息
     * @return 结果
     */
    @Override
    public String checkGroupNameUnique(BomanGroup bomanGroup) {
        Long id = StringUtils.isNull(bomanGroup.getId()) ? -1L : bomanGroup.getId();
        BomanGroup bomanGroupOld = groupMapper.checkGroupNameUnique(bomanGroup.getGroupName());
        if (StringUtils.isNotNull(bomanGroupOld) && bomanGroupOld.getId().longValue() != id.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 新增保存组织信息
     *
     * @param bomanGroup 部门信息
     * @return
     */
    @Override
    public int insertGroup(BomanGroup bomanGroup) {
        return groupMapper.insertGroup(bomanGroup);
    }

    /**
     * 修改保存组织信息
     *
     * @param bomanGroup 组织信息
     * @return
     */
    @Override
    public int updateGroup(BomanGroup bomanGroup) {
        return groupMapper.updateGroup(bomanGroup);
    }

    /**
     * 删除
     *
     * @param ids 组织ID
     * @return
     */
    @Override
    public int deleteGroupId(Long[] ids) {
        return groupMapper.deleteGroupById(ids);
    }


    /**
     * 给组添加用户
     *
     * @param groupId
     * @param userIds
     * @return
     */
    @Override
    public AjaxResult insertUserGroup(Long groupId, Long[] userIds) {
        //查询该组所有用户
        List<Long> list = groupUserMapper.selectGroupUserList(groupId);
        List<BomanGroupUser> bomanGroupUserList = new ArrayList<>();
        List<Long> longs = Arrays.asList(userIds);
        //如果删除所有组用户,则前台longs只有一个-1
        if(longs.size() == 1){
            Long aLong = longs.get(0);
            if (-1L == aLong){
                //删除该组所有用户
                groupUserMapper.deleteGroupUser(groupId,list.stream().mapToLong(Long::valueOf).toArray());
                return AjaxResult.success();
            }
        }
        if (list.size() > 0) {
            //需要删除的
            List<Object> objectDelete = Arrays.asList(CollectionUtils.subtract(list, longs).toArray());
            if (objectDelete.size() > 0){
                List<Long> objectDeleteIds = new ArrayList<>();
                for (Object o : objectDelete) {
                    objectDeleteIds.add(Long.valueOf(o.toString()));
                }
                groupUserMapper.deleteGroupUser(groupId,objectDeleteIds.stream().mapToLong(Long::valueOf).toArray());
            }
            //是否有新增的
            List<Object> objects = Arrays.asList(CollectionUtils.subtract(longs, list).toArray());
            if (objects.size() > 0) {
                for (Object userId : objects) {
                    BomanGroupUser bomanGroupUser = new BomanGroupUser();
                    bomanGroupUser.setUserId(Long.valueOf(userId.toString()));
                    bomanGroupUser.setGroupId(groupId);
                    bomanGroupUser.setCreateBy(SecurityUtils.getUsername());
                    SysUser user = sysUserMapper.selectUserById(Long.valueOf(userId.toString()));
                    if (user != null) {
                        bomanGroupUser.setUserName(user.getUserName());
                        bomanGroupUserList.add(bomanGroupUser);
                    } else {
                        return AjaxResult.error("该用户不存在");
                    }
                }
                groupUserMapper.insertUserGroup(bomanGroupUserList);
            }
        } else {
            for (Long userId : longs) {
                BomanGroupUser bomanGroupUser = new BomanGroupUser();
                bomanGroupUser.setUserId(userId);
                bomanGroupUser.setGroupId(groupId);
                bomanGroupUser.setCreateBy(SecurityUtils.getUsername());
                SysUser user = sysUserMapper.selectUserById(userId);
                if (user != null) {
                    bomanGroupUser.setUserName(user.getUserName());
                    bomanGroupUserList.add(bomanGroupUser);
                }
            }
            groupUserMapper.insertUserGroup(bomanGroupUserList);
        }
        return AjaxResult.success();
    }


    /**
     * 给组删除用户
     *
     * @param groupId
     * @param userIds
     * @return
     */
    @Override
    public AjaxResult deleteGroupUser(Long groupId, long[] userIds) {
        groupUserMapper.deleteGroupUser(groupId, userIds);
        return AjaxResult.success();
    }

    /**
     * 根据组织编号获取对应组织所有用户
     *
     * @param groupId
     * @return
     */
    @Override
    public List<SysUser> selectUserByGroupId(Long groupId) {
        //所有组对应的用户id
        List<Long> userIds = groupUserMapper.selectGroupUserList(groupId);
        List<SysUser> sysUsers = new ArrayList<>();
        if (userIds.size() > 0) {
            sysUsers = sysUserMapper.selectUserByUserIds(userIds);
        }
        return sysUsers;
    }

}
