package ink.wgink.service.position.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.position.PositionSimpleDTO;
import ink.wgink.pojo.dtos.position.PositionUserDTO;
import ink.wgink.pojo.dtos.user.UserDTO;
import ink.wgink.pojo.pos.PositionPO;
import ink.wgink.pojo.result.SuccessResultList;
import ink.wgink.service.position.dao.IPositionUserDao;
import ink.wgink.service.position.service.IPositionService;
import ink.wgink.service.position.service.IPositionUserService;
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: IPositionUserServiceImpl
 * @Description: 职位用户业务
 * @Author: WangGeng
 * @Date: 2021/2/16 17:49
 * @Version: 1.0
 **/
@Service
public class PositionUserServiceImpl extends DefaultBaseService implements IPositionUserService {

    @Autowired
    private IPositionUserDao positionUserDao;
    @Autowired
    private IUserBaseService userBaseService;
    @Autowired
    private IPositionService positionService;
    @Autowired(required = false)
    private IMongoLoginUserService mongoLoginUserService;

    @Override
    public void save(String positionId, List<String> saveUserIds) {
        // 判断是否已经添加
        List<String> existUserIds = listUserIdByPositionIdAndUserIds(positionId, 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("positionId", positionId);
                params.put("userId", saveUserId);
                positionUserDao.save(params);
            } else {
                saveUserIds.remove(i);
                i--;
            }
        }

        updateMongoLoginUser(saveUserIds);
    }

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

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

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

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

    @Override
    public List<UserDTO> listUser(Map<String, Object> requestParams) {
        requestParams = requestParams == null ? getHashMap(0) : requestParams;
        return positionUserDao.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 positionId) {
        Map<String, Object> params = getHashMap(2);
        params.put("positionId", positionId);
        return positionUserDao.listUserId(params);
    }

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

    @Override
    public List<String> listUserIdByPositionIdAndUserIds(String positionId, List<String> userIds) {
        Map<String, Object> params = getHashMap(4);
        params.put("positionId", positionId);
        params.put("userIds", userIds);
        return positionUserDao.listUserId(params);
    }

    @Override
    public List<String> listUserIdByPositionIdsAndUserIds(List<String> positionIds, List<String> userIds) {
        Map<String, Object> params = getHashMap(4);
        params.put("positionIds", positionIds);
        params.put("userIds", userIds);
        return positionUserDao.listUserId(params);
    }

    @Override
    public List<String> listPositionIdByUserId(String userId) {
        Map<String, Object> params = getHashMap(2);
        params.put("userId", userId);
        return positionUserDao.listPositionId(params);
    }

    @Override
    public List<String> listPositionIdByUserIds(List<String> userIds) {
        Map<String, Object> params = getHashMap(2);
        params.put("userIds", userIds);
        return positionUserDao.listPositionId(params);
    }

    @Override
    public SuccessResultList<List<PositionUserDTO>> listPage(String positionId, ListPage page) {
        SuccessResultList<List<UserDTO>> successResultList;
        if (StringUtils.equals(positionId, ISystemConstant.TREE_BASE_ROOT_ID_VALUE)) {
            successResultList = listPageUserDTOByExcludePosition(page);
        } else {
            successResultList = listPageUser(positionId, page);
        }
        List<UserDTO> userDTOs = successResultList.getRows();
        List<PositionUserDTO> positionUserDTOs = new ArrayList<>();
        for (UserDTO userDTO : userDTOs) {
            PositionUserDTO positionUserDTO = new PositionUserDTO(userDTO);
            positionUserDTOs.add(positionUserDTO);
        }
        return new SuccessResultList<>(positionUserDTOs, successResultList.getPage(), successResultList.getTotal());
    }

    @Override
    public List<PositionPO> listPositionPOByUserId(String userId) {
        Map<String, Object> params = getHashMap(2);
        params.put("userId", userId);
        List<String> positionIds = positionUserDao.listPositionId(params);
        if (positionIds.isEmpty()) {
            return new ArrayList<>();
        }
        return positionService.listPO(positionIds);
    }

    @Override
    public List<PositionPO> listPositionPOByUserIds(List<String> userIds) {
        Map<String, Object> params = getHashMap(2);
        params.put("userIds", userIds);
        List<String> positionIds = positionUserDao.listPositionId(params);
        if (positionIds.isEmpty()) {
            return new ArrayList<>();
        }
        return positionService.listPO(positionIds);
    }

    @Override
    public List<PositionSimpleDTO> listSimple(List<PositionPO> positionPOs) {
        if (positionPOs == null || positionPOs.isEmpty()) {
            return new ArrayList<>();
        }
        List<PositionSimpleDTO> positionSimpleDTOs = new ArrayList<>();
        positionPOs.forEach(positionPO -> {
            PositionSimpleDTO positionSimpleDTO = new PositionSimpleDTO();
            positionSimpleDTO.setPositionId(positionPO.getPositionId());
            positionSimpleDTO.setPositionParentId(positionPO.getPositionParentId());
            positionSimpleDTO.setPositionName(positionPO.getPositionName());
            positionSimpleDTO.setPositionCode(positionPO.getPositionCode());
            positionSimpleDTOs.add(positionSimpleDTO);
        });
        return positionSimpleDTOs;
    }

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

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

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

    /**
     * 更新 mongo 用户
     *
     * @param userIds
     */
    private void updateMongoLoginUser(List<String> userIds) {
        if (mongoLoginUserService != null) {
            CachedThreadPoolUtil.execute(() -> {
                mongoLoginUserService.updateByUserIds(userIds);
            });
        }
    }

}
