package ink.wgink.service.department.service.impl;

import ink.wgink.common.base.DefaultBaseService;
import ink.wgink.exceptions.SearchException;
import ink.wgink.interfaces.consts.ISystemConstant;
import ink.wgink.interfaces.user.IUserBaseService;
import ink.wgink.pojo.ListPage;
import ink.wgink.pojo.dtos.department.DepartmentSimpleDTO;
import ink.wgink.pojo.dtos.department.DepartmentUserDTO;
import ink.wgink.pojo.dtos.user.UserDTO;
import ink.wgink.pojo.pos.DepartmentPO;
import ink.wgink.pojo.result.SuccessResultList;
import ink.wgink.service.department.dao.IDepartmentUserDao;
import ink.wgink.service.department.pojo.vos.DepartmentUserSortVO;
import ink.wgink.service.department.service.IDepartmentAdjustmentService;
import ink.wgink.service.department.service.IDepartmentService;
import ink.wgink.service.department.service.IDepartmentUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: DepartmentUserServiceImpl
 * @Description: 组织部门用户
 * @Author: wanggeng
 * @Date: 2021/1/28 4:21 下午
 * @Version: 1.0
 */
@Service
public class DepartmentUserServiceImpl extends DefaultBaseService implements IDepartmentUserService {

    @Autowired
    private IDepartmentUserDao departmentUserDao;
    @Autowired
    private IDepartmentService departmentService;
    @Autowired
    private IDepartmentAdjustmentService departmentAdjustmentService;
    @Autowired
    private IUserBaseService userBaseService;

    @Override
    public void save(String departmentId, String departmentName, List<String> departmentUserIds) {
        Map<String, Object> params = getHashMap(2);
        for (String departmentUserId : departmentUserIds) {
            params.put("userId", departmentUserId);
            params.put("departmentId", departmentId);
            departmentUserDao.save(params);
        }
        departmentAdjustmentService.save(departmentUserIds, departmentId, departmentName, USER_DEPARTMENT_TYPE_JOIN);
    }

    @Override
    public void delete(String departmentId, String departmentName, List<String> userIds) {
        String adjustmentDepartmentName = departmentName;
        if (StringUtils.isBlank(departmentName)) {
            DepartmentPO departmentPO = departmentService.getPO(departmentId);
            if (departmentPO == null) {
                throw new SearchException("部门不存在");
            }
            adjustmentDepartmentName = departmentPO.getDepartmentName();
        }
        if (userIds == null || userIds.isEmpty()) {
            return;
        }
        Map<String, Object> params = getHashMap(1);
        params.put("departmentId", departmentId);
        params.put("userIds", userIds);
        departmentUserDao.delete(params);
        departmentAdjustmentService.save(userIds, departmentId, adjustmentDepartmentName, USER_DEPARTMENT_TYPE_LEAVE);
    }

    @Override
    public void delete(String departmentId) {
        Map<String, Object> params = getHashMap(2);
        params.put("departmentId", departmentId);
        List<String> userIds = departmentUserDao.listUserId(params);
        delete(departmentId, null, userIds);
    }

    @Override
    public void update(String departmentId, List<String> userIds) {
        if (userIds.isEmpty()) {
            return;
        }
        DepartmentPO departmentPO = departmentService.getPO(departmentId);
        if (departmentPO == null) {
            throw new SearchException("部门不存在");
        }
        Map<String, Object> params = getHashMap(2);
        params.put("departmentId", departmentId);
        List<String> existUserIds = departmentUserDao.listUserId(params);
        List<String> newUserIds = new ArrayList<>();
        for (String userId : userIds) {
            boolean isNewUser = true;
            for (String existUserId : existUserIds) {
                if (StringUtils.equals(userId, existUserId)) {
                    isNewUser = false;
                    break;
                }
            }
            if (isNewUser) {
                params.put("userId", userId);
                departmentUserDao.save(params);
                newUserIds.add(userId);
            }
        }
        departmentAdjustmentService.save(newUserIds, departmentId, departmentPO.getDepartmentName(), USER_DEPARTMENT_TYPE_JOIN);
    }

    @Override
    public void updateSort(String departmentId, DepartmentUserSortVO departmentUserSortVO) {
        Map<String, Object> params = getHashMap(6);
        params.put("departmentId", departmentId);
        params.put("userId", departmentUserSortVO.getUserId());
        params.put("userSort", departmentUserSortVO.getUserSort());
        departmentUserDao.updateSort(params);
    }

    @Override
    public List<DepartmentPO> listDepartmentPOByUserId(String userId) {
        Map<String, Object> params = getHashMap(2);
        params.put("userId", userId);
        List<String> departmentIds = departmentUserDao.listDepartmentId(params);
        if (departmentIds.isEmpty()) {
            return new ArrayList<>();
        }
        return departmentService.listPO(departmentIds);
    }

    @Override
    public List<DepartmentSimpleDTO> listSimple(List<DepartmentPO> departmentPOs) {
        if (departmentPOs == null || departmentPOs.isEmpty()) {
            return new ArrayList<>();
        }
        List<DepartmentSimpleDTO> departmentSimpleDTOs = new ArrayList<>();
        departmentPOs.forEach(departmentPO -> {
            DepartmentSimpleDTO departmentSimpleDTO = new DepartmentSimpleDTO();
            departmentSimpleDTO.setDepartmentId(departmentPO.getDepartmentId());
            departmentSimpleDTO.setDepartmentParentId(departmentPO.getDepartmentParentId());
            departmentSimpleDTO.setDepartmentName(departmentPO.getDepartmentName());
            departmentSimpleDTO.setDepartmentCode(departmentPO.getDepartmentCode());
            departmentSimpleDTOs.add(departmentSimpleDTO);
        });
        return departmentSimpleDTOs;
    }

    @Override
    public List<DepartmentUserDTO> listWithUser(Map<String, Object> params) {
        List<DepartmentUserDTO> departmentUserDTOs = list(params);
        setUser(departmentUserDTOs);
        return departmentUserDTOs;
    }

    @Override
    public List<DepartmentUserDTO> list(Map<String, Object> params) {
        return departmentUserDao.list(params);
    }

    @Override
    public List<DepartmentUserDTO> list(String departmentId) {
        Map<String, Object> params = getHashMap(2);
        params.put("departmentId", departmentId);
        return list(params);
    }

    @Override
    public List<DepartmentUserDTO> list(List<String> departmentIds) {
        Map<String, Object> params = getHashMap(2);
        params.put("departmentIds", departmentIds);
        return list(params);
    }

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

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

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

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

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

    @Override
    public SuccessResultList<List<DepartmentUserDTO>> listPage(String departmentId, ListPage page) {
        if (StringUtils.equals(departmentId, ISystemConstant.TREE_BASE_ROOT_ID_VALUE)) {
            return listPageUserByExcludeDepartment(page);
        }
        return listPageUser(departmentId, page);
    }

    @Override
    public List<DepartmentUserDTO> list(String departmentId, Map<String, Object> params) {
        if (StringUtils.equals(departmentId, ISystemConstant.TREE_BASE_ROOT_ID_VALUE)) {
            return listUserByExcludeDepartment(params);
        }
        return listUser(departmentId, params);
    }

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

    /**
     * 没有组织机构的用户分页列表
     *
     * @param page
     * @return
     */
    private SuccessResultList<List<DepartmentUserDTO>> listPageUserByExcludeDepartment(ListPage page) {
        List<DepartmentUserDTO> hasDepartmentUsers = list(getHashMap(0));
        List<String> userIds = new ArrayList<>();
        for (DepartmentUserDTO hasDepartmentUserId : hasDepartmentUsers) {
            userIds.add(hasDepartmentUserId.getUserId());
        }
        SuccessResultList<List<UserDTO>> successResultList = userBaseService.listPageByExcludeIds(userIds, page);
        return listPageExcludeDepartmentUser(successResultList);
    }

    /**
     * 没有组织机构的用户分页列表
     *
     * @param params
     * @return
     */
    private List<DepartmentUserDTO> listUserByExcludeDepartment(Map<String, Object> params) {
        List<DepartmentUserDTO> hasDepartmentUsers = list(getHashMap(0));
        List<String> userIds = new ArrayList<>();
        for (DepartmentUserDTO hasDepartmentUserId : hasDepartmentUsers) {
            userIds.add(hasDepartmentUserId.getUserId());
        }
        List<UserDTO> userDTOs = userBaseService.listByExcludeIds(userIds, params);
        return listExcludeDepartmentUser(userDTOs);
    }

    /**
     * 组织机构的用户分页列表
     *
     * @param departmentId 组织机构ID
     * @param page
     * @return
     */
    private SuccessResultList<List<DepartmentUserDTO>> listPageUser(String departmentId, ListPage page) {
        List<DepartmentUserDTO> hasDepartmentUsers = list(departmentId);
        if (hasDepartmentUsers.isEmpty()) {
            return new SuccessResultList<>(new ArrayList<>(), 1, 0L);
        }
        List<String> userIds = new ArrayList<>();
        for (DepartmentUserDTO hasDepartmentUserId : hasDepartmentUsers) {
            userIds.add(hasDepartmentUserId.getUserId());
        }
        SuccessResultList<List<UserDTO>> successResultList = userBaseService.listPageByIds(userIds, page);
        return listPageDepartmentUser(successResultList, hasDepartmentUsers);
    }

    /**
     * 用户列表
     *
     * @param departmentId 部门ID
     * @param params
     * @return
     */
    private List<DepartmentUserDTO> listUser(String departmentId, Map<String, Object> params) {
        List<DepartmentUserDTO> hasDepartmentUsers = list(departmentId);
        if (hasDepartmentUsers.isEmpty()) {
            return new ArrayList<>();
        }
        List<String> userIds = new ArrayList<>();
        for (DepartmentUserDTO hasDepartmentUserId : hasDepartmentUsers) {
            userIds.add(hasDepartmentUserId.getUserId());
        }
        List<UserDTO> userDTOs = userBaseService.listByIds(userIds, params);
        return listDepartmentUser(userDTOs, hasDepartmentUsers);
    }

    /**
     * 机构用户分页列表
     *
     * @param successResultList
     * @return
     */
    private SuccessResultList<List<DepartmentUserDTO>> listPageExcludeDepartmentUser(SuccessResultList<List<UserDTO>> successResultList) {
        // 查询用户排序
        List<UserDTO> userDTOs = successResultList.getRows();
        List<DepartmentUserDTO> departmentUserDTOs = listExcludeDepartmentUser(userDTOs);
        return new SuccessResultList<>(departmentUserDTOs, successResultList.getPage(), successResultList.getTotal());
    }

    /**
     * 机构用户分页列表
     *
     * @param userDTOs
     * @return
     */
    private List<DepartmentUserDTO> listExcludeDepartmentUser(List<UserDTO> userDTOs) {
        // 查询用户排序
        List<DepartmentUserDTO> departmentUserDTOs = new ArrayList<>();
        for (UserDTO userDTO : userDTOs) {
            DepartmentUserDTO departmentUserDTO = new DepartmentUserDTO(userDTO);
            departmentUserDTO.setDepartmentId("");
            departmentUserDTO.setUserSort("ZZZ-000");
            departmentUserDTOs.add(departmentUserDTO);
        }
        return departmentUserDTOs;
    }

    /**
     * 机构用户分页列表
     *
     * @param successResultList
     * @param hasDepartmentUsers
     * @return
     */
    private SuccessResultList<List<DepartmentUserDTO>> listPageDepartmentUser(SuccessResultList<List<UserDTO>> successResultList, List<DepartmentUserDTO> hasDepartmentUsers) {
        // 查询用户排序
        List<UserDTO> userDTOs = successResultList.getRows();
        List<DepartmentUserDTO> departmentUserDTOs = listDepartmentUser(userDTOs, hasDepartmentUsers);
        return new SuccessResultList<>(departmentUserDTOs, successResultList.getPage(), successResultList.getTotal());
    }

    /**
     * 部门用户列表
     *
     * @param userDTOs
     * @param hasDepartmentUsers
     * @return
     */
    private List<DepartmentUserDTO> listDepartmentUser(List<UserDTO> userDTOs, List<DepartmentUserDTO> hasDepartmentUsers) {
        // 查询用户排序
        List<DepartmentUserDTO> departmentUserDTOs = new ArrayList<>();
        for (DepartmentUserDTO hasDepartmentUserDTO : hasDepartmentUsers) {
            for (UserDTO userDTO : userDTOs) {
                if (StringUtils.equals(userDTO.getUserId(), hasDepartmentUserDTO.getUserId())) {
                    DepartmentUserDTO departmentUserDTO = new DepartmentUserDTO(userDTO);
                    departmentUserDTO.setDepartmentId(hasDepartmentUserDTO.getDepartmentId());
                    departmentUserDTO.setUserSort(hasDepartmentUserDTO.getUserSort());
                    departmentUserDTOs.add(departmentUserDTO);
                }
            }
        }
        return departmentUserDTOs;
    }

    @Override
    public void setUser(List<DepartmentUserDTO> departmentUserDTOs) {
        if (departmentUserDTOs.isEmpty()) {
            return;
        }
        Set<String> userIdSet = new HashSet<>();
        for (DepartmentUserDTO hasDepartmentUserId : departmentUserDTOs) {
            userIdSet.add(hasDepartmentUserId.getUserId());
        }
        List<UserDTO> userDTOs = userBaseService.listByUserIds(new ArrayList<>(userIdSet));
        for (DepartmentUserDTO departmentUserDTO : departmentUserDTOs) {
            for (UserDTO userDTO : userDTOs) {
                if (StringUtils.equals(departmentUserDTO.getUserId(), userDTO.getUserId())) {
                    departmentUserDTO.setUser(userDTO);
                    break;
                }
            }
        }
    }

}
