package com.hotent.uc.manager.impl;

import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hotent.base.cache.annotation.CacheEvict;
import com.hotent.base.cache.annotation.Cacheable;
import com.hotent.base.constants.CacheKeyConst;
import com.hotent.base.feign.PortalFeignService;
import com.hotent.base.util.StringUtil;
import com.hotent.uc.exception.BaseException;
import com.hotent.uc.model.*;
import com.hotent.uc.params.orgRole.RoleOrgVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hotent.base.manager.impl.BaseManagerImpl;
import com.hotent.base.query.PageBean;
import com.hotent.base.query.PageList;
import com.hotent.base.query.QueryField;
import com.hotent.base.query.QueryFilter;
import com.hotent.base.query.QueryOP;
import com.hotent.base.util.AppUtil;
import com.hotent.base.util.BeanUtils;
import com.hotent.base.util.UniqueIdUtil;
import com.hotent.uc.dao.OrgRoleDao;
import com.hotent.uc.manager.OrgManager;
import com.hotent.uc.manager.OrgRoleManager;
import org.springframework.util.Assert;

/**
 * 
 * <pre> 
 * 描述：组织角色管理 处理实现类
 * 构建组：eip平台-bpmx-platform
 * 作者:liyg
 * 邮箱:liyg@jee-soft.cn
 * 日期:2017-12-25 10:25:20
 * 版权：广州宏天软件有限公司
 * </pre>
 */
@Service
public class OrgRoleManagerImpl extends BaseManagerImpl <OrgRoleDao, OrgRole> implements OrgRoleManager{

	@Resource
	OrgManager orgManager;
	@Resource
    PortalFeignService portalFeignService;

	@Override
    @Transactional
	public void addOrgRole(String orgId, Role role,int isInherit) throws SQLException {

			OrgRole or = baseMapper.getByOrgIdAndRoleId(orgId,role.getId() );
			if(BeanUtils.isNotEmpty(or)){
				or.setIsDelete("0");
				or.setIsInherit(isInherit);
				or.setOrgId(orgId);
				or.setRoleName(role.getName());
				or.setRoleId(role.getId());
				this.update(or);
	
			}else {
				or = new OrgRole();
				or.setId(UniqueIdUtil.getSuid());
				or.setIsInherit(isInherit);
				or.setOrgId(orgId);
				or.setRoleId(role.getId());
				or.setRoleName(role.getName());
				or.setVersion(1);
//				or.setIsDelete("0");
				this.create(or);
			}		
	}

	@Override
    @Transactional
	public void delByOrgIdAndRoleId(String orgId, String roleId) {
		baseMapper.delByOrgIdAndRoleId(orgId, roleId,LocalDateTime.now());
	}
	
	
	
	@Override
	@Transactional(readOnly=true)
	public PageList<OrgRole> query(QueryFilter<OrgRole> queryFilter) {
		
		Map<String, Object> queryFilterParams = getInitParams(queryFilter);
		if (BeanUtils.isNotEmpty(queryFilterParams) && queryFilterParams.containsKey("orgId")) {
			String orgId=(String) queryFilterParams.get("orgId");
			OrgManager orgService=AppUtil.getBean(OrgManager.class);
			Org org=orgService.get(orgId);
			if (BeanUtils.isNotEmpty(org)) {
				queryFilter.addParams("path", org.getPath());
			}
		}
		PageBean pageBean = queryFilter.getPageBean();
		IPage<OrgRole> result=baseMapper.query(convert2IPage(pageBean),convert2Wrapper(queryFilter, currentModelClass()));
		return new PageList<OrgRole>(result);
	}
	
	public Map<String, Object> getInitParams(QueryFilter queryFilter){
		List<QueryField> querys = queryFilter.getQuerys();
		Map<String, Object> initParams = new LinkedHashMap<String, Object>();
		if (BeanUtils.isEmpty(querys))
			return initParams;
		for (QueryField element : querys) {
			QueryField queryField = (QueryField) element;
			QueryOP operation = queryField.getOperation();
			if (QueryOP.IS_NULL.equals(operation) || QueryOP.NOTNULL.equals(operation)
					|| QueryOP.IN.equals(operation)) {
				continue;
			}
			String property = queryField.getProperty();
			if (property.indexOf(".") > -1) {
				property = property.substring(property.indexOf(".") + 1);
			}
			Object value = queryField.getValue();
			initParams.put(property, value);
		}
		initParams.putAll(queryFilter.getParams());
		return initParams;
	}

	@Override
    @Transactional
	public Integer removePhysical() {
		return baseMapper.removePhysical();
	}


	@Override
	public PageList<Org> getRoleOrgs(String roleId, QueryFilter<Org> queryFilter) {
		IPage<Org> page =  baseMapper.getRoleOrgs(convert2IPage(queryFilter.getPageBean()), convert2Wrapper(queryFilter, currentModelClass()), roleId);
		return new PageList<>(page);
	}

	@Override
	public void removeRoleOrgs(RoleOrgVo vo) {
		Assert.notEmpty(vo.getOrgIds(), "组织ID不能为空");
		if (StringUtil.isEmpty(vo.getRoleId())) {
			throw new IllegalArgumentException("角色ID不能为空");
		}
		OrgRoleManager this_ = AppUtil.getBean(OrgRoleManager.class);
		for (String orgId : vo.getOrgIds()) {
            orgManager.removeUserMenuByOrgId(orgId);
            this_.removeByRoleAndOrg(vo.getRoleId(), orgId);
		}
	}

	@Override
	@CacheEvict(value = CacheKeyConst.EIP_UC_ORG_ROLE, key = "#orgId")
	public void removeByRoleAndOrg(String roleId, String orgId) {
		baseMapper.removeRoleOrg(roleId, orgId);
	}

	@Override
	@CacheEvict(value = CacheKeyConst.EIP_UC_ORG_ROLE, key = "#vo.orgIds[0]")
	public void updateInheritStatus(RoleOrgVo vo) {
		String orgId = vo.getOrgIds().get(0);
		QueryWrapper<OrgRole> qw = new QueryWrapper<>();
		qw.eq("ORG_ID_", orgId).eq("ROLE_ID_", vo.getRoleId());
		OrgRole one = this.getOne(qw);
		if (BeanUtils.isEmpty(one)) {
			throw new BaseException("找不到对应的组织角色");
		}
		UpdateWrapper<OrgRole> uw = new UpdateWrapper<>();
		uw.eq("ORG_ID_", orgId).eq("ROLE_ID_", vo.getRoleId())
				.set("IS_INHERIT_", one.getIsInherit() == 1 ? 0 : 1);
		this.update(uw);
        portalFeignService.removeUserMenu();//清除已登录用户菜单缓存
	}

	@Override
	@Cacheable(value = CacheKeyConst.EIP_UC_ORG_ROLE, key = "#orgId")
	public List<OrgRole> getByOrgId(String orgId) {
		QueryWrapper<OrgRole> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("ORG_ID_", orgId);
		List<OrgRole> list = this.list(queryWrapper);
		if (list.isEmpty()) {
			return list;
		}
		return list;
	}

	@Override
	public List<OrgRole> getByRoleCode(String code) {
		return baseMapper.getByRoleCode(code);
	}
}
