package com.storlead.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.storlead.framework.common.constant.CacheConstant;
import com.storlead.framework.common.constant.CommonConstant;
import com.storlead.framework.mybatis.service.impl.MyBaseServiceImpl;
import com.storlead.user.mapper.DeptMapper;
import com.storlead.user.pojo.entity.DeptEntity;
import com.storlead.user.model.DepartIdModel;
import com.storlead.user.model.DeptTreeModel;
import com.storlead.user.service.IDepartService;
import com.storlead.user.util.FindsDepartsChildrenUtil;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

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

/**
 * <p>
 * 部门表 服务实现类
 * <p>
 *
 * @Author Steve
 * @Since 2019-01-22
 */
@Service
public class DepartServiceImpl extends MyBaseServiceImpl<DeptMapper, DeptEntity> implements IDepartService {

	@Override
	public void truncateDept() {
		 this.baseMapper.truncateDept();
	}

	/**
	 * queryTreeList 对应 queryTreeList 查询所有的部门数据,以树结构形式响应给前端
	 */
	@Cacheable(value = CacheConstant.SYS_DEPARTS_CACHE, unless="#result == null")
	@Override
	public List<DeptTreeModel> queryTreeList() {
		LambdaQueryWrapper<DeptEntity> query = new LambdaQueryWrapper<DeptEntity>();
		query.eq(DeptEntity::getEnabled, CommonConstant.STATUS_NORMAL.toString());
		query.orderByAsc(DeptEntity::getSort);
		List<DeptEntity> list = this.list(query);
		// 调用wrapTreeDataToTreeList方法生成树状数据
		List<DeptTreeModel> listResult = FindsDepartsChildrenUtil.wrapTreeDataToTreeList(list);
		return listResult;
	}

	/**
	 * queryTreeList 对应 queryTreeList 查询所有的部门数据,以树结构形式响应给前端
	 */
	@Override
	public List<DeptTreeModel> queryTreeListWithSubCompanyId(Integer subCompanyId) {
		LambdaQueryWrapper<DeptEntity> query = new LambdaQueryWrapper<DeptEntity>();
		query.eq(DeptEntity::getEnabled, CommonConstant.STATUS_NORMAL.toString());
		query.eq(DeptEntity::getSubCompanyId, subCompanyId);
		query.orderByAsc(DeptEntity::getSort);
		List<DeptEntity> list = this.list(query);
		// 调用wrapTreeDataToTreeList方法生成树状数据
		List<DeptTreeModel> listResult = FindsDepartsChildrenUtil.wrapTreeDataToTreeList(list);
		return listResult;
	}

	@Cacheable(value = CacheConstant.SYS_DEPART_IDS_CACHE)
	@Override
	public List<DepartIdModel> queryDepartIdTreeList() {
		LambdaQueryWrapper<DeptEntity> query = new LambdaQueryWrapper<DeptEntity>();
		query.eq(DeptEntity::getEnabled, CommonConstant.STATUS_NORMAL.toString());
		query.orderByAsc(DeptEntity::getSort);
		List<DeptEntity> list = this.list(query);
		// 调用wrapTreeDataToTreeList方法生成树状数据
		List<DepartIdModel> listResult = FindsDepartsChildrenUtil.wrapTreeDataToDepartIdTreeList(list);
		return listResult;
	}

	/**
	 * <p>
	 * 根据关键字搜索相关的部门数据
	 * </p>
	 */
	@Override
	public List<DeptTreeModel> searhBy(String keyWord) {
		LambdaQueryWrapper<DeptEntity> query = new LambdaQueryWrapper<DeptEntity>();
		query.like(DeptEntity::getName, keyWord);
		query.eq(DeptEntity::getEnabled, 1);
		DeptTreeModel model = new DeptTreeModel();
		List<DeptEntity> departList = this.list(query);
		List<DeptTreeModel> newList = new ArrayList<>();
		if(departList.size() > 0) {
			for(DeptEntity depart : departList) {
				model = new DeptTreeModel(depart);
				model.setChildren(null);
				newList.add(model);
			}
			return newList;
		}
		return null;
	}


	@Override
	public List<DeptTreeModel> queryDeptBySubList(Integer subCompanyId) {
		return baseMapper.queryDeptBySubList(subCompanyId);
	}

//	/**
//	 * 获取部门列表 嵌套结构
//	 *
//	 * @return java.lang.Object
//	 * @author blank
//	 * @date 2021-3-15 下午 2:46
//	 */
//	@Override
//	public Object getRoleDeptList(Long menuId) {
//		User currentUser = SpringContextHolder.getCurrentUser();
//		Set<Long> deptIds = null;
//		if (currentUser != null) {
//			Set roleIds =  userService.selectUserRoleIdsByMenuId(currentUser.getId(),menuId);
//			if (CollectionUtils.isEmpty(roleIds)) {
//				return baseMapper.getRoleDeptList(null, null);
//			}
//			List<Role> roles = roleService.listByIds(roleIds);
//			if (dataScope.isAllDataScope(roles)) {
//				return baseMapper.getRoleDeptList(null, null);
//			}
//			deptIds = dataScope.getDeptIds(roles,currentUser);
//			// 说明可能是admin 或自己
//			if (deptIds == null || deptIds.size() == 0) {
//				//只有自己的权限 只返回自己的数据
//				if (dataScope.isSelfDataScope(roles)) {
//					return baseMapper.getRoleDeptList(null, currentUser.getId());
//				}
//				//说明是admin
//			} else {
//				//说明是自定义的部门权限
//				return baseMapper.getRoleDeptList(deptIds, null);
//			}
//		}
//		return null;
//	}
//
//	@Override
//	public Object getAllDeptList() {
//		return baseMapper.getRoleDeptList(null, null);
//	}

//	/**
//	 * 根据部门id,结合当前用户的权限，查询出能查看的所有部门的数据(包含此部门以及所有子部门)
//	 *
//	 * @param deptId 部门ID
//	 * @return java.util.Set<java.lang.Long>
//	 * @author blank
//	 * @date 2021-3-31 下午 5:06
//	 */
//	@Override
//	public Set<Long> getDeptIdsByDeptId(Long deptId) {
//
//		Set<Long> deptSet = new HashSet<>();
//		Set<Long> result = new HashSet<>();
//		if (!ObjectUtils.isEmpty(deptId)) {
//			deptSet.add(deptId);
//			deptSet.addAll(this.getDeptChildren(this.findByPid(deptId)));
//		}
//		// 数据权限
//		Set<Long> deptIds = dataScope.getDeptIds();
//		// 查询条件不为空并且数据权限不为空则取交集
//		if (!CollectionUtils.isEmpty(deptIds) && !CollectionUtils.isEmpty(deptSet)) {
//			// 取交集
//			result.addAll(deptSet);
//			result.retainAll(deptIds);
//			// 否则取并集
//		} else {
//			result.addAll(deptSet);
//			result.addAll(deptIds);
//		}
//		return result.size() == 0 ? null : result;
//	}

	@Override
	public Set<Long> findDeptIdsBySubCompanyId(Long subCompanyId) {
		List<DeptEntity> depts = this.lambdaQuery().eq(DeptEntity::getSubCompanyId,subCompanyId).list();
		if(null != depts && depts.size()>0){
			return depts.stream().map(DeptEntity:: getId).collect(Collectors.toSet());
		}
		return null;
	}

	/**
	 * 根据角色ID查询部门列表
	 *
	 * @param roleId 角色ID
	 * @return java.util.Set<com.storlead.salary.entity.Dept>
	 * @author blank
	 * @date 2020-3-16 下午 3:34
	 */
	@Override
	public Set<DeptEntity> findByRoleId(Long roleId) {

		return baseMapper.findByRoleId(roleId);
	}

	/**
	 * 根据父ID查询部门列表
	 *
	 * @param id pid
	 * @return java.util.List<com.storlead.salary.entity.Dept>
	 * @author blank
	 * @date 2020-3-16 下午 3:38
	 */
	@Override
	public List<DeptEntity> findByPid(Long id) {

		return this.lambdaQuery().eq(DeptEntity::getPid, id).list();
	}

	@Override
	public List<Long> getDeptChildren(List<DeptEntity> deptList) {
		List<Long> list = new ArrayList<>();
		deptList.forEach(dept -> {
					if (dept != null && dept.getEnabled()) {
						List<DeptEntity> depts = this.findByPid(dept.getId());
						if (deptList.size() != 0) {
							list.addAll(getDeptChildren(depts));
						}
						list.add(dept.getId());
					}
				}
		);
		return list;
	}

	@Override
	public Map<Long, DeptEntity> getDeptMap(List<Long> deptIdList) {
		Map<Long, DeptEntity> deptMap = new HashMap<>();
		List<DeptEntity> deptEntities = baseMapper.selectList(new LambdaQueryWrapper<DeptEntity>().in(DeptEntity::getId, deptIdList));
		if (!CollectionUtils.isEmpty(deptEntities)){
			deptMap = deptEntities.stream().collect(Collectors.toMap(DeptEntity::getId, Function.identity()));
		}
		return deptMap;
	}

}
