package ink.wgink.service.group.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import ink.wgink.common.base.DefaultBaseService;
import ink.wgink.interfaces.consts.ISystemConstant;
import ink.wgink.interfaces.user.IUserBaseService;
import ink.wgink.interfaces.user.mongo.IMongoLoginUserService;
import ink.wgink.pojo.ListPage;
import ink.wgink.pojo.dtos.group.GroupSimpleDTO;
import ink.wgink.pojo.dtos.group.GroupUserDTO;
import ink.wgink.pojo.dtos.user.UserDTO;
import ink.wgink.pojo.pos.GroupPO;
import ink.wgink.pojo.result.SuccessResultList;
import ink.wgink.service.group.dao.IGroupUserDao;
import ink.wgink.service.group.service.IGroupService;
import ink.wgink.service.group.service.IGroupUserService;
import ink.wgink.util.thread.CachedThreadPoolUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: GroupUserServiceImpl
 * @Description: 用户组用户
 * @Author: wanggeng
 * @Date: 2021/2/16 11:32 上午
 * @Version: 1.0
 */
@Service
public class GroupUserServiceImpl extends DefaultBaseService implements IGroupUserService {

    @Autowired
    private IGroupUserDao groupUserDao;
    @Autowired
    private IUserBaseService userBaseService;
    @Autowired
    private IGroupService groupService;
    @Autowired(required = false)
    private IMongoLoginUserService mongoLoginUserService;

    @Override
    public void save(String groupId, List<String> saveUserIds) {
        // 判断是否已经添加
        List<String> existUserIds = listUserIdByGroupIdAndUserIds(groupId, saveUserIds);
        Map<String, Object> params = getHashMap(4);
        for (int i = 0; i < saveUserIds.size(); i++) {
            String saveUserId = saveUserIds.get(i);
            boolean isExist = false;
            for (String existUserId : existUserIds) {
                if (StringUtils.equals(saveUserId, existUserId)) {
                    isExist = true;
                    existUserIds.remove(existUserId);
                    break;
                }
            }
            if (!isExist) {
                params.put("groupId", groupId);
                params.put("userId", saveUserId);
                groupUserDao.save(params);
            } else {
                saveUserIds.remove(i);
                i--;
            }
        }
        updateMongoLoginUser(saveUserIds);
    }

    @Override
    public void update(String groupId, List<String> saveUserIds, List<String> deleteUserIds) {
        if (deleteUserIds != null && !deleteUserIds.isEmpty()) {
            delete(groupId, deleteUserIds);
        }
        if (saveUserIds != null && !saveUserIds.isEmpty()) {
            Map<String, Object> params = getHashMap(4);
            params.put("groupId", groupId);
            for (String userId : saveUserIds) {
                params.put("userId", userId);
                groupUserDao.save(params);
            }
            updateMongoLoginUser(saveUserIds);
        }
    }

    @Override
    public void delete(String groupId) {
        List<String> userIds = listUserId(groupId);
        delete(groupId, userIds);
    }

    @Override
    public void delete(List<String> groupIds) {
        groupIds.forEach(groupId -> {
            delete(groupId);
        });
    }

    @Override
    public void delete(String groupId, List<String> userIds) {
        Map<String, Object> params = getHashMap(4);
        params.put("groupId", groupId);
        params.put("userIds", userIds);
        groupUserDao.delete(params);

        updateMongoLoginUser(userIds);
    }

    @Override
    public List<UserDTO> listUser(Map<String, Object> requestParams) {
        requestParams = requestParams == null ? getHashMap(0) : requestParams;
        return groupUserDao.listUser(requestParams);
    }

    @Override
    public SuccessResultList<List<UserDTO>> listPageUser(ListPage page) {
        PageHelper.startPage(page.getPage(), page.getRows());
        List<UserDTO> userDTOs = listUser(page.getParams());
        PageInfo<UserDTO> pageInfo = new PageInfo<>(userDTOs);
        return new SuccessResultList<>(userDTOs, pageInfo.getPageNum(), pageInfo.getTotal());
    }

    @Override
    public List<String> listUserId(String groupId) {
        Map<String, Object> params = getHashMap(2);
        params.put("groupId", groupId);
        return groupUserDao.listUserId(params);
    }

    @Override
    public List<String> listUserId(List<String> groupIds) {
        Map<String, Object> params = getHashMap(2);
        params.put("groupIds", groupIds);
        return groupUserDao.listUserId(params);
    }

    @Override
    public SuccessResultList<List<GroupUserDTO>> listPage(String groupId, ListPage page) {
        SuccessResultList<List<UserDTO>> successResultList;
        if (StringUtils.equals(groupId, ISystemConstant.TREE_BASE_ROOT_ID_VALUE)) {
            successResultList = listPageUserDTOByExcludeGroup(page);
        } else {
            successResultList = listPageUser(groupId, page);
        }
        List<UserDTO> userDTOs = successResultList.getRows();
        List<GroupUserDTO> groupUserDTOs = new ArrayList<>();
        for (UserDTO userDTO : userDTOs) {
            GroupUserDTO groupUserDTO = new GroupUserDTO(userDTO);
            groupUserDTOs.add(groupUserDTO);
        }
        return new SuccessResultList<>(groupUserDTOs, successResultList.getPage(), successResultList.getTotal());
    }

    @Override
    public List<GroupPO> listGroupPOByUserId(String userId) {
        Map<String, Object> params = getHashMap(2);
        params.put("userId", userId);
        List<String> groupIds = groupUserDao.listGroupId(params);
        if (groupIds.isEmpty()) {
            return new ArrayList<>();
        }
        return groupService.listPO(groupIds);
    }

    @Override
    public List<GroupSimpleDTO> listSimple(List<GroupPO> groupPOs) {
        if (groupPOs == null || groupPOs.isEmpty()) {
            return new ArrayList<>();
        }
        List<GroupSimpleDTO> groupSimpleDTOs = new ArrayList<>();
        groupPOs.forEach(groupPO -> {
            GroupSimpleDTO groupSimpleDTO = new GroupSimpleDTO();
            groupSimpleDTO.setGroupId(groupPO.getGroupId());
            groupSimpleDTO.setGroupParentId(groupPO.getGroupParentId());
            groupSimpleDTO.setGroupName(groupPO.getGroupName());
            groupSimpleDTO.setGroupCode(groupPO.getGroupCode());
            groupSimpleDTOs.add(groupSimpleDTO);
        });
        return groupSimpleDTOs;
    }


    private List<String> listGroupUserId(Map<String, Object> params) {
        return groupUserDao.listGroupUserId(params);
    }

    /**
     * 没有用户组的用户分页列表
     *
     * @param page
     * @return
     */
    private SuccessResultList<List<UserDTO>> listPageUserDTOByExcludeGroup(ListPage page) {
        List<String> hasGroupUserIds = listGroupUserId(new HashMap<>(0));
        return userBaseService.listPageByExcludeIds(hasGroupUserIds, page);
    }

    /**
     * 用户组的用户分页列表
     *
     * @param groupId 用户组ID
     * @param page
     * @return
     */
    private SuccessResultList<List<UserDTO>> listPageUser(String groupId, ListPage page) {
        List<String> userIds = listUserId(groupId);
        if (userIds.isEmpty()) {
            return new SuccessResultList<>(new ArrayList<>(), 1, 0L);
        }
        return userBaseService.listPageByIds(userIds, page);
    }

    private List<String> listUserIdByGroupIdAndUserIds(String groupId, List<String> userIds) {
        Map<String, Object> params = getHashMap(4);
        params.put("groupId", groupId);
        params.put("userIds", userIds);
        return groupUserDao.listUserId(params);
    }

    private List<String> listUserIdByPositionIdsAndUserIds(List<String> groupIds, List<String> userIds) {
        Map<String, Object> params = getHashMap(4);
        params.put("groupIds", groupIds);
        params.put("userIds", userIds);
        return groupUserDao.listUserId(params);
    }

    private void updateMongoLoginUser(List<String> userIds) {
        if (mongoLoginUserService != null) {
            CachedThreadPoolUtil.execute(() -> {
                mongoLoginUserService.updateByUserIds(userIds);
            });
        }
    }

}
