package com.blueland.service.impl;


/**
 * @author 代码自动生成工具
 * @version 1.0
 * @since  
 */
 
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blueland.constant.RedisConstant;
import com.blueland.bo.*;
import com.blueland.dao.RoleDao;
import com.blueland.model.TPfRole;
import com.blueland.model.TPfRole2user;
import com.blueland.model.TUcStaff;
import com.blueland.service.IRole2userService;
import com.blueland.service.IRoleService;

import com.blueland.service.SysRedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import static com.blueland.constant.ResponseConstant.*;


@Service
@Slf4j
public class RoleServiceImpl extends ServiceImpl<RoleDao, TPfRole> implements IRoleService {
	@Autowired
	//Role对应的DAO类,主要用于数据库的增删改查等操作
	private RoleDao roleDao;
	
	@Autowired
	private TucStaffServiceImpl pubUserService;

	@Autowired
	IRole2userService role2UserServiceImpl;

	@Autowired
	private SysRedisService sysRedisService;

	/**
	 * 根据应用ID查询角色列表
	 * @param
	 * @param curPage
	 * @param curPageSize
	 * @return
	 */
	@Override
	public Page<RoleEntity> getAppRole(Map<String,Object> map, Integer curPage, Integer curPageSize) {
		// TODO Auto-generated method stub
		Page<RoleEntity> page = new Page<>(curPage, curPageSize);
		Page<RoleEntity> result = roleDao.getAppRolePage(page, map);
		return result;
	}

	@Override
	public void deleteRole(Map<String, Object> queryParams) {
		// TODO Auto-generated method stub
		roleDao.deleteRole(queryParams);
	}

	@Override
	public List<RoleEntity> findRoleUserBy(Map<String, Object> map) {
		List<RoleEntity> result = roleDao.findRoleUserBy(map);
		return result;
	}

	@Override
	public List<RoleEntity> findRolesByUser(String appId, String userId) {
		return roleDao.findRolesByUser(appId, userId);
	}

	@Override
	public void saveUser(Role2userEntity role2user) {
		// TODO Auto-generated method stub
		roleDao.saveUser(role2user);
	}

	@Override
	public int findUserId(String appId, String roleId, String userId) {
		int result = roleDao.findUserId(appId, roleId,userId);
		return result;
	}

	@Override
	public int findAppidByRoleId(String appId, String roleId) {
		int result = roleDao.findAppidByRoleId(appId, roleId);
		return result;
	}

	@Override
	public int deleteUserId(String appId, String roleId, String userId) {
		// 从redis中删除对应缓存
		try {
			sysRedisService.removeRoleByKey(userId);
		} catch (Exception e) {
			log.info("删除reids数据失败，userId：" + userId);
		}
        int result = roleDao.deleteUserId(appId, roleId,userId);
		return result;
	}

	@Override
	public void deluser(String roleId, String appId) {
		roleDao.deluser(roleId,appId);
	}

	@Override
	public List<RoleEntity> findRoleTenantidByUserid(String userId) {
		return roleDao.findRoleTenantidByUserid(userId);
	}
	
	@Transactional
	@Override
	public Map<String, Object> saveRoles(RoleEntity model) {
		Map<String, Object> result = new HashMap<>();
		String[] userIds = model.getUserId();
		roleDao.deluser(model.getRoleId(),model.getAppId());
		if(userIds.length>0) {
			List<String> codes= Arrays.asList(userIds);
			List<TUcStaff> userlist = pubUserService.getListByPostCodes(codes);
			Map<String, TUcStaff> userMap = new HashMap<>();
			for (TUcStaff tucStaff : userlist) {
				userMap.put(tucStaff.getStaffPostCode(), tucStaff);
			}
		   for(int i=0;i<userIds.length;i++){
			  // TucStaffEntity pubUser =  pubUserService.getStaffByStaffIdnoFulldeptname(userIds[i]);
			   TUcStaff pubUser = userMap.get(userIds[i]);
			  // int cout = roleService.findUserId(model.getAppId(),model.getRoleId(),userIds[i]);
			  if(pubUser!=null) {
				  TPfRole2user role2user = new TPfRole2user();
				  role2user.setRoleId(model.getRoleId());
				  role2user.setUserId(pubUser.getStaffCode());
				  role2user.setSTATUS("Y");
				  role2user.setCreatorId("czadmin");
				  role2user.setUpdatorId("czadmin");
				  role2user.setOrgId(pubUser.getOrgId());
				  role2user.setOrgName(pubUser.getOrgName());
				  role2user.setTitleId(null);
				  role2user.setAppId(model.getAppId());
				  role2user.setCreateDate(new Date());
				  role2user.setUpdateDate(new Date());
				  role2user.setStaffPostCode(pubUser.getStaffPostCode());
//				  roleDao.insert(role2user);
				  role2UserServiceImpl.save(role2user);
                  //redis新增
				  sysRedisService.flushRole();
			  }
		   }
		   result.put("resultCode", RESULT_CODE_SUCCESS_CODE);
		  result.put("resultMsg", "处理成功");
		  result.put("result", "true");
		   //20200316 BUG9562 IVD-角色管理-选择一个角色，当选择项内容都为空的时候点击确定按钮，弹出错误提示，但保存是成功的
		} else {
			result.put("resultCode", RESULT_CODE_SUCCESS_CODE);
			result.put("resultMsg", "处理成功");
			result.put("result", "true");
		}
		return result;
	}

	@Override
	public TPfRole get(RoleEntity bo) {
		return this.baseMapper.selectOne(buildQueryWrapper(bo));
	}

	@Override
	public Page<RoleEntity> findPage(RoleEntity bo) {
		Page<RoleEntity> page = new Page(bo.getPageNum(), bo.getPageSize());
		return this.baseMapper.findPage(page, bo);
	}

	@Override
	public List<RoleEntity> findRolesByPostCode(String appId, String postCode) {
		return this.baseMapper.findRolesByPostCode(appId, postCode);
	}

	@Override
	public List<RoleEntity> findRoleAllByPostCode(String postCode) {
		return roleDao.findRoleAllByPostCode(postCode);
	}

	@Override
	public int deleteByPostCode(String appId, String roleId, String postCode) {
		int result = roleDao.deleteByPostCode(appId, roleId,postCode);
		return result;
	}

	@Override
	public List<RoleEntity> findRoleUserByCode(String appId, String roleId, String postCode) {
		return roleDao.findRoleUserByCode(appId, roleId, postCode);
	}

	@Override
	public void deleteByAppId(String appId) {
		this.baseMapper.deleteByAppId(appId);
	}

	@Override
	public List<RoleEntity> findListByAppId(String appId) {
		return this.baseMapper.findListByAppId(appId);
	}

	private LambdaQueryWrapper<TPfRole> buildQueryWrapper(RoleEntity bo) {
		LambdaQueryWrapper<TPfRole> lqw = Wrappers.lambdaQuery();
		lqw.eq(ObjectUtil.isNotEmpty(bo.getRoleId()), TPfRole::getRoleId, bo.getRoleId());
		lqw.eq(ObjectUtil.isNotEmpty(bo.getAppId()), TPfRole::getAppId, bo.getAppId());
		lqw.like(ObjectUtil.isNotEmpty(bo.getRoleName()), TPfRole::getRoleName, bo.getRoleName());
		lqw.eq(ObjectUtil.isNotEmpty(bo.getRoleType()), TPfRole::getRoleType, bo.getRoleType());
		lqw.eq(ObjectUtil.isNotEmpty(bo.getRoleModule()), TPfRole::getRoleModule, bo.getRoleModule());
		lqw.eq(ObjectUtil.isNotEmpty(bo.getOrgId()), TPfRole::getOrgId, bo.getOrgId());
		lqw.like(ObjectUtil.isNotEmpty(bo.getRemark()), TPfRole::getRemark, bo.getRemark());
		lqw.eq(ObjectUtil.isNotEmpty(bo.getStatus()), TPfRole::getStatus, bo.getStatus());
		lqw.eq(ObjectUtil.isNotEmpty(bo.getCreatorId()), TPfRole::getCreatorId, bo.getCreatorId());
		lqw.eq(ObjectUtil.isNotEmpty(bo.getUpdatorId()), TPfRole::getUpdatorId, bo.getUpdatorId());
		return lqw;
	}
}
