package cn.com.ctop.common.module.service.impl;

import cn.com.ctop.common.module.entity.SysUserDepart;
import cn.com.ctop.common.module.mapper.SysUserDepartMapper;
import cn.com.ctop.common.module.model.DepartIdModel;
import cn.com.ctop.common.module.model.SysUserDepartsVO;
import cn.com.ctop.common.module.service.ISysDepartService;
import cn.com.ctop.common.module.service.ISysUserDepartService;
import cn.com.ctop.common.module.service.ISysUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.system.entity.SysDepart;
import org.jeecg.common.system.entity.SysUser;
import org.jeecg.common.util.oConvertUtils;
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;
import java.util.stream.Collectors;

/**
 * <P>
 * 用户部门表实现类
 * <p/>
 * @Author ZhiLin
 *@since 2019-02-22
 */
@Service
public class SysUserDepartServiceImpl extends ServiceImpl<SysUserDepartMapper, SysUserDepart> implements ISysUserDepartService {
	@Autowired
	private ISysDepartService sysDepartService;
	@Autowired
	private ISysUserService sysUserService;

	/**
	 *根据用户id添加部门信息
	 */
	@Override
	public boolean addSysUseWithrDepart(SysUserDepartsVO sysUserDepartsVO) {
		LambdaQueryWrapper<SysUserDepart> query = new LambdaQueryWrapper<>();
		if(sysUserDepartsVO != null) {
			String userId = sysUserDepartsVO.getUserId();
			List<String> departIdList = sysUserDepartsVO.getDepartIdList();
			if(departIdList != null && departIdList.size() > 0) {
				for(String depId : departIdList) {
					query.eq(SysUserDepart::getDepId, depId);
					query.eq(SysUserDepart::getUserId, userId);
					List<SysUserDepart> uDepList = this.list(query);
					if(uDepList == null || uDepList.size() == 0) {
						this.save(new SysUserDepart("",userId,depId));
					}
				}
			}
			return true;
		}else {
			return false;
		}

	}


	/**
	 * 根据用户id查询部门信息
	 */
	@Override
	public List<DepartIdModel> queryDepartIdsOfUser(String userId) {
		LambdaQueryWrapper<SysUserDepart> queryUDep = new LambdaQueryWrapper<SysUserDepart>();
		LambdaQueryWrapper<SysDepart> queryDep = new LambdaQueryWrapper<SysDepart>();
		try {
			queryUDep.eq(SysUserDepart::getUserId, userId);
			List<String> depIdList = new ArrayList<>();
			List<DepartIdModel> depIdModelList = new ArrayList<>();
			List<SysUserDepart> userDepList = this.list(queryUDep);
			if(userDepList != null && userDepList.size() > 0) {
			for(SysUserDepart userDepart : userDepList) {
					depIdList.add(userDepart.getDepId());
				}
			queryDep.in(SysDepart::getId, depIdList);
			List<SysDepart> depList = sysDepartService.list(queryDep);
			if(depList != null || !depList.isEmpty()) {
				for(SysDepart depart : depList) {
					depIdModelList.add(new DepartIdModel().convertByUserDepart(depart));
				}
			}
			return depIdModelList;
			}
		}catch(Exception e) {
			e.fillInStackTrace();
		}
		return null;


	}

	/**
	 * 根据用户id修改部门信息
	 */
	@Override
	public boolean editSysUserWithDepart(SysUserDepartsVO sysUserDepartsVO) {
        LambdaQueryWrapper<SysUserDepart> queryUserDepart = new LambdaQueryWrapper<SysUserDepart>();
		List<String> depIdList = sysUserDepartsVO.getDepartIdList();
		if(depIdList != null && depIdList.size() > 0) {
            queryUserDepart.eq(SysUserDepart::getUserId, sysUserDepartsVO.getUserId());
            boolean ok = this.remove(queryUserDepart);
			if(ok) {
				for(String str : depIdList) {
					this.save(new SysUserDepart("", sysUserDepartsVO.getUserId(), str));
				}
			return ok;
			}
		}
        queryUserDepart.eq(SysUserDepart::getUserId, sysUserDepartsVO.getUserId());
        boolean ok = this.remove(queryUserDepart);
		return ok;
	}

	/**
	 * 根据部门id查询用户信息
	 */
	@Override
	public List<SysUser> queryUserByDepId(String depId) {
        LambdaQueryWrapper<SysUserDepart> queryUserDepart = new LambdaQueryWrapper<>();
        queryUserDepart.eq(SysUserDepart::getDepId, depId);
		List<String> userIdList = new ArrayList<>();
        List<SysUserDepart> uDepList = this.list(queryUserDepart);
		if(uDepList != null && uDepList.size() > 0) {
			for(SysUserDepart uDep : uDepList) {
				userIdList.add(uDep.getUserId());
			}
			List<SysUser> userList = (List<SysUser>) sysUserService.listByIds(userIdList);
			//update-begin-author:taoyan date:201905047 for:接口调用查询返回结果不能返回密码相关信息
			for (SysUser sysUser : userList) {
				sysUser.setSalt("");
				sysUser.setPassword("");
			}
			//update-end-author:taoyan date:201905047 for:接口调用查询返回结果不能返回密码相关信息
			return userList;
		}
		return new ArrayList<SysUser>();
	}

	/**
	 * 根据部门code，查询当前部门和下级部门的 用户信息
	 */
	@Override
	public List<SysUser> queryUserByDepCode(String depCode, String realname) {
		LambdaQueryWrapper<SysDepart> queryByDepCode = new LambdaQueryWrapper<SysDepart>();
		queryByDepCode.likeRight(SysDepart::getOrgCode,depCode);
		List<SysDepart> sysDepartList = sysDepartService.list(queryByDepCode);
		List<String> depIds = sysDepartList.stream().map(SysDepart::getId).collect(Collectors.toList());

		LambdaQueryWrapper<SysUserDepart> queryUDep = new LambdaQueryWrapper<SysUserDepart>();
		queryUDep.in(SysUserDepart::getDepId, depIds);
		List<String> userIdList = new ArrayList<>();
		List<SysUserDepart> uDepList = this.list(queryUDep);
		if(uDepList != null && uDepList.size() > 0) {
			for(SysUserDepart uDep : uDepList) {
				userIdList.add(uDep.getUserId());
			}
			LambdaQueryWrapper<SysUser> queryUser = new LambdaQueryWrapper<SysUser>();
			queryUser.in(SysUser::getId,userIdList);
			if(oConvertUtils.isNotEmpty(realname)){
				queryUser.like(SysUser::getRealname,realname.trim());
			}
			List<SysUser> userList = (List<SysUser>) sysUserService.list(queryUser);
			//update-begin-author:taoyan date:201905047 for:接口调用查询返回结果不能返回密码相关信息
			for (SysUser sysUser : userList) {
				sysUser.setSalt("");
				sysUser.setPassword("");
			}
			//update-end-author:taoyan date:201905047 for:接口调用查询返回结果不能返回密码相关信息
			return userList;
		}
		return new ArrayList<>();
	}

	@Override
	public IPage<SysUser> queryDepartUserPageList(String departId, String username, String realname, int pageSize, int pageNo) {
		IPage<SysUser> pageList = null;
		// 部门ID不存在 直接查询用户表即可
		Page<SysUser> page = new Page<SysUser>(pageNo, pageSize);
		if(oConvertUtils.isEmpty(departId)){
			LambdaQueryWrapper<SysUser> query = new LambdaQueryWrapper<>();
			if(oConvertUtils.isNotEmpty(username)){
				query.like(SysUser::getUsername, username);
			}
			pageList = sysUserService.page(page, query);
		}else{
			// 有部门ID 需要走自定义sql
			SysDepart sysDepart = sysDepartService.getById(departId);
			pageList = this.baseMapper.queryDepartUserPageList(page, sysDepart.getOrgCode(), username, realname);
		}
		List<SysUser> userList = pageList.getRecords();
		if(userList!=null && userList.size()>0){
			List<String> userIds = userList.stream().map(SysUser::getId).collect(Collectors.toList());
			Map<String, SysUser> map = new HashMap<String, SysUser>();
			if(userIds.size()>0){
				// 查部门名称
				Map<String,String>  useDepNames = sysUserService.getDepNamesByUserIds(userIds);
				userList.forEach(item->{
					//TODO 临时借用这个字段用于页面展示
					item.setOrgCodeTxt(useDepNames.get(item.getId()));
					item.setSalt("");
					item.setPassword("");
					// 去重
					map.put(item.getId(), item);
				});
			}
			pageList.setRecords(new ArrayList<>(map.values()));
		}
		return pageList;
	}


}
