package com.zcxk.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zcxk.dao.GroupUserMapper;
import com.zcxk.dao.UserGroupMapper;
import com.zcxk.dao.UserMapper;
import com.zcxk.dto.UserGroupDto;
import com.zcxk.entity.*;
import com.zcxk.model.LoginUser;
import com.zcxk.service.UserGroupService;
import com.zcxk.service.UserService;
import com.zcxk.util.ByteArrayUtils;
import com.zcxk.util.RedisUtil;
import com.zcxk.util.UserUtil;
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.Date;
import java.util.List;

/**
 * 用户组(UserGroup表)服务实现类
 *
 * @author makejava
 * @since 2020-10-27 09:13:57
 */
@Service("userGroupService")
public class UserGroupServiceImpl implements UserGroupService {
    @Autowired
    private UserGroupMapper userGroupMapper;
    @Autowired
    private GroupUserMapper groupUserMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtil redisUtil;




    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public UserGroup selectById(Integer id) {
        return this.userGroupMapper.selectById(id);
    }


    /**
     * 查询所有
     *
     * @return 实例对象的集合
     */
    @Override
    public List<UserGroup> selectAll() {
        return this.userGroupMapper.selectAll();
    }

    /**
     * 根据条件查询
     *
     * @return 实例对象的集合
     */
    @Override
    public List<UserGroup> selectList(UserGroup userGroup) {
        return this.userGroupMapper.selectList(userGroup);
    }

    /**
     * 新增数据
     *
     * @param userGroup 实例对象
     * @return 实例对象
     */
    @Override
    public int insert(UserGroup userGroup) {
        LoginUser currentUser = UserUtil.getCurrentUser();
        userGroup.setTenantId(currentUser.getTenantId());
        userGroup.setCreateBy(currentUser.getUsername());
        userGroup.setDateCreate(new Date());
        userGroup.setStatus(1);
        return this.userGroupMapper.insert(userGroup);
    }

    /**
     * 批量新增
     *
     * @param userGroups 实例对象的集合
     * @return 生效的条数
     */
    @Override
    public int batchInsert(List<UserGroup> userGroups) {
        return this.userGroupMapper.batchInsert(userGroups);
    }

    /**
     * 修改数据
     *
     * @param userGroup 实例对象
     * @return 实例对象
     */
    @Override
    @Transactional
    public int update(UserGroup userGroup) {

        LoginUser currentUser = UserUtil.getCurrentUser();
        userGroup.setUpdateBy(currentUser.getUsername());
        List<UserEntity> usersByUserGroup = userGroupMapper.findUsersByUserGroup(userGroup);
        List<Long>userIds=new ArrayList<>();
        List<UserRoleEntity>userRoleEntities=new ArrayList<>();

        usersByUserGroup.forEach(userEntity -> {
            UserEntity updateUserEntity=new UserEntity();
            updateUserEntity.setId(userEntity.getId());
            updateUserEntity.setEnableState(userGroup.getGroupState()+"");
            userService.updateUserById(updateUserEntity);
            if (userGroup.getGroupState()==0) {
                String roleKey = "disableUser:" + userEntity.getId();
                redisUtil.setExpire(roleKey.getBytes(), ByteArrayUtils.objectToBytes("1").get(), 60 * 60 * 24);//15分钟过期

            }
            if (userGroup.getGroupState()==1) {
                String roleKey = "disableUser:" + userEntity.getId();
                redisUtil.del(roleKey.getBytes());
            }
            userIds.add(userEntity.getId());
            UserRoleEntity userRoleEntity=new UserRoleEntity();
            Long id=Long.valueOf(userGroup.getRoleId()+"");
            userRoleEntity.setRoleId(id);
            userRoleEntity.setUserId(userEntity.getId());
            userRoleEntity.setStatus(1);
            userRoleEntity.setCreateBy(currentUser.getUsername());
            userRoleEntities.add(userRoleEntity);
        });
        if(userIds.size()>0){
            UserGroupDto userGroupDto=new UserGroupDto();
            userGroupDto.setGroupId(userGroup.getId());
            userGroupDto.setOrginUserIds(userIds);
            userGroupDto.setUserIds(userIds);
            userGroupMapper.deleteUserRoles(userGroupDto);
            userGroupMapper.batchInsertRoles(userRoleEntities);
        }
        return this.userGroupMapper.update(userGroup);
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public int deleteById(Integer id) {
        return this.userGroupMapper.deleteById(id);
    }

    @Override
    public List<String> deleteAll(List<Integer> ids) {
        List<String>fail=new ArrayList<>();
        ids.forEach(id->{
            UserGroup userGroup=new UserGroup();
            userGroup.setId(id);
            userGroup.setStatus(0);
            userGroupMapper.update(userGroup);
            userGroupMapper.deleteUserGroupRelations(userGroup);

        });

        return fail;
    }

    /**
     * 查询总数据数
     *
     * @return 数据总数
     */
    @Override
    public int count() {
        return this.userGroupMapper.count();
    }

    /**
     * 分页查询
     *
     * @return 对象列表
     */
    @Override
    public IPage<UserGroup> selectPage(UserGroup userGroup, IPage<UserGroup> page) {
        LoginUser currentUser = UserUtil.getCurrentUser();
        userGroup.setTenantId(currentUser.getTenantId());

        return this.userGroupMapper.selectPage(page, userGroup);
    }

    @Override
    public List<UserEntity> findUsersByUserGroup(UserGroup userGroup) {
        LoginUser currentUser = UserUtil.getCurrentUser();
        userGroup.setTenantId(currentUser.getTenantId());
        UserEntity userEntity=new UserEntity();
        userEntity.setTenantId(currentUser.getTenantId());
        List<UserEntity>list;
        if(userGroup.getId()==-1){
            list=userMapper.findList(userEntity);
        }else{
            list=userGroupMapper.findUsersByUserGroup( userGroup);
        }

        return list;
    }

    @Override
    @Transactional
    public int updateRolesByUserGroup(UserGroupDto userGroupDto) {
        UserGroup userGroup=new UserGroup();
        LoginUser currentUser = UserUtil.getCurrentUser();
        Integer groupId=userGroupDto.getGroupId();
        userGroup.setId(groupId);
        userGroupMapper.deleteUserGroupRelations(userGroup);
        List<Long> userIds = userGroupDto.getUserIds();
        List<GroupUser>groupUsers=new ArrayList<>();
        List<UserRoleEntity>userRoleEntities=new ArrayList<>();
        List<Long> orginUserIds = userGroupDto.getOrginUserIds();

        userIds.forEach(id->{
            GroupUser user=new GroupUser();
            user.setUserId(id);
            user.setGroupId(groupId);
            UserRoleEntity userRoleEntity=new UserRoleEntity();
            userRoleEntity.setRoleId(userGroupDto.getRoleId());
            userRoleEntity.setUserId(id);
            userRoleEntity.setStatus(1);
            userRoleEntity.setCreateBy(currentUser.getUsername());
            groupUsers.add(user);
            user.setStatus(1);
            userRoleEntities.add(userRoleEntity);
        });
        if(userIds.size()>0){
            orginUserIds.addAll(userIds);
        }
      ;
        if(orginUserIds.size()>0){

            userGroupMapper.deleteUserRoles(userGroupDto);
        }

        if(userGroupDto.getDeleteFlag()==1){
            userGroupMapper.batchInsertRoles(userRoleEntities);
            groupUserMapper.batchInsert(groupUsers);
        }



        return 0;
    }
}