package com.yeejoin.amos.supervision.business.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.yeejoin.amos.supervision.business.constants.XJConstant;
import com.yeejoin.amos.supervision.business.dao.mapper.CatalogTreeMapper;
import com.yeejoin.amos.supervision.business.dao.mapper.InputItemMapper;
import com.yeejoin.amos.supervision.business.dao.mapper.PointMapper;
import com.yeejoin.amos.supervision.business.dao.repository.ICatalogTreeDao;
import com.yeejoin.amos.supervision.business.service.intfc.ICatalogTreeService;
import com.yeejoin.amos.supervision.exception.YeeException;
import com.yeejoin.amos.supervision.feign.RemoteSecurityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.supervision.business.param.CatalogTreePageParam;
import com.yeejoin.amos.supervision.dao.entity.CatalogTree;

import net.sf.json.JSONObject;

@Service("catalogTreeService")
public class CatalogTreeServiceImpl implements ICatalogTreeService {

	@Autowired
	private ICatalogTreeDao catalogTreeDao;

	@Autowired
	private PointMapper pointMapper;

	@Autowired
	private CatalogTreeMapper catalogTreeMapper;

	@Autowired
    InputItemMapper inputItemMapper;
	@Autowired
	private RemoteSecurityService remoteSecurityService;
	@Override
	public List<Object> getCatalogTree(String orgCode) {
		List<Object> treelist= findTypeTree(orgCode);
		return treelist;
	}

	public List<Object> findTypeTree(String orgCode) {
		long parentId = 0L;
		List<CatalogTree> catalogTreeList = catalogTreeDao.findByParentIdAndOrgCode(parentId,orgCode);
		List<Object> list = new ArrayList<>();
		for (CatalogTree tree : catalogTreeList) {
			JSONObject treeObject = new JSONObject();
			treeObject.put("key", tree.getId());
			treeObject.put("value", tree.getId());
			treeObject.put("label", tree.getName());
			treeObject.put("children", getChildren(tree.getId()));
			list.add(treeObject);
		}
		return list;
	}

	public List<Object> getChildren(Long parentId){
		List<Object> list = new ArrayList<>();
		List<CatalogTree> children = catalogTreeDao.findChildrenByParentId(parentId);
		for (CatalogTree tree : children) {
			if(parentId == tree.getParentId()) {
				JSONObject obj = new JSONObject();
				obj.put("key", tree.getId());
				obj.put("value", tree.getId());
				obj.put("label", tree.getName());
				obj.put("children", getChildren(tree.getId()));
				list.add(obj);
			}
		}
		return list;
	}

	@Override
	public List<CatalogTree> getCatalogList(String orgCode) {
		long parentId = 0L;
		return catalogTreeDao.findByParentIdAndOrgCode(parentId, orgCode);
	}

	@Override
	public void addCatalogTree(HashMap<String, Object> map) {
		CatalogTree tree = (CatalogTree) map.get("param");
		tree.setCreateBy(map.get("user_id") == null ? '0' :Integer.parseInt(map.get("user_id").toString()));
		tree.setOrgCode(map.get("org_code") == null ? null :map.get("org_code").toString());
		catalogTreeDao.save(tree);
	}

	@Override
	public void checkModifyCatalogTreeResult(CatalogTree param) {
		if (param != null && param.getId() != 0) {
			int parentId = param.getParentId();
			List<Object> treeList = getChildren(param.getId());
			// 修改分类检查
			checkModifyCatalogTree(parentId, treeList);
		}
	}

	@Override
	public List<CatalogTree> AllCatalogChrildList(String orgCode,Long parentId) {
		List<CatalogTree> catalogTreeList = catalogTreeDao.findByOrgCode(orgCode);
		List<CatalogTree> allCatalogChrildList = new ArrayList<>();
		return  this.treeMenuList(catalogTreeList,parentId,allCatalogChrildList);
	}

	/**
	 *校验修改时，父目录不能为自己的子目录
	 * @param treeList
	 */
	public void checkModifyCatalogTree(int parentId, List<Object> treeList) {
		if (treeList != null && treeList.size()>0) {
			for (Object object : treeList) {
				JSONObject obj = JSONObject.fromObject(object);
				int id = (int)obj.get("key");
				if (id == parentId) {
					throw new YeeException("上级目录不能是自己的子目录");
				}
				// 子目录还有子目录
				List<Object> childrenList = (List<Object>) obj.get("children");
				if (childrenList != null && childrenList.size()>0) {
					checkModifyCatalogTree(parentId,childrenList);
				}
			}
		}
	}

	@Override
	public void delCatalogTreeById(Long[] ids) {
		//1.校验是否有在使用中的分类，有则结束，父不能删除
		checkUseCatalogTree(ids);
		//2.批量删除
		catalogTreeDao.deleteBatchById(ids);

	}
/**
 * 校验是否有在使用中的分类
 * @param param
 */
	public void checkUseCatalogTree(Long[] param) {
		HashMap<String,Object> paramMap = new HashMap<String,Object>();
		for(int i =0 ;i<param.length; i++){
			paramMap.clear();
			paramMap.put("catalog_id",param[i]);
			paramMap.put("is_delete", XJConstant.IS_DETETE_NO);
			CatalogTree tree = catalogTreeDao.findById(param[i]).get();
			if(tree != null){
				List<CatalogTree> list = catalogTreeDao.findChildrenByParentId((long)tree.getId());
				if(list != null && list.size()>0){
					throw new YeeException(tree.getName()+"为父节点在被使用中,请先删除子节点");
				}
			}
			List<HashMap<String,Object>> pointList = pointMapper.countByCatalogId(paramMap);
			if(pointList.size() > 0){
				throw new YeeException("巡检点:"+pointList.get(0).get("name")+"使用中，不能删除");
			}
			List<HashMap<String,Object>> inputItemList = inputItemMapper.countByCatalogId(paramMap);
			if(inputItemList.size() > 0){
				throw new YeeException("检查项:"+inputItemList.get(0).get("name")+"使用中，不能删除");
			}
		}

	}

@Override
public Page<HashMap<String, Object>> getCatalogTreeInfo(String toke,String product,String appKey,CatalogTreePageParam param) {
	long total = catalogTreeMapper.countCatalogTreeData(param);
	List<HashMap<String, Object>> content = catalogTreeMapper.getCatalogTreePageInfo(param);
	 String userIds = "";
     Set<String> set = new HashSet<>();
     content.forEach(s -> {
         if (s.containsKey("createBy")) {
             set.add(s.get("createBy").toString());
         }
     });

     List<String> list1 = new ArrayList<>(set);
     userIds = String.join(",", list1);

     List<AgencyUserModel> listd = remoteSecurityService.listUserByUserIds(toke, product, appKey, userIds);



     //新安全

         content.forEach(s -> {
        	 Map<String, Object>  listdk= remoteSecurityService.listByOrgCode(toke, product, appKey, s.get("org_Code")+"");
             if(listdk!=null){
            	 Map<String, Object> md= (Map<String, Object>) listdk.get("compnay");
            	 if(md!=null){
            		 s.put("orgName",md.get("companyName") );
            	 }

             }
             if (!ObjectUtils.isEmpty(listd)) {
        	 listd.forEach(s1 -> {
                 if (s.get("createBy").toString().equals(s1.getUserId())) {
                     s.put("createName", s1.getRealName());
                 }



             });
             }
         });

	Page<HashMap<String, Object>> result = new PageImpl<HashMap<String, Object>>(content, param, total);
	return result;
}

@Override
public CatalogTree queryCatalogTreeById(Long id) {
	CatalogTree tree = catalogTreeDao.findById(id).get();
	return tree;
}

@Override
public String[] getCataLogList(String loginOrgCode) {
	long parentId = 0L;
	List<CatalogTree> catalogTreeList = catalogTreeDao.findByParentIdAndOrgCode(parentId, loginOrgCode);
	if (!ObjectUtils.isEmpty(catalogTreeList)) {
		String[] names = new String[catalogTreeList.size()];
		for (int i = 0; i < catalogTreeList.size(); i++) {
			names[i] = catalogTreeList.get(i).getName();
		}
		return names;
	}

	return null;
}

@Override
public List<CatalogTree> queryCatalogTreeByIds(List<Long> ids) {
	return catalogTreeDao.findAllById(ids);
}




	public List<CatalogTree> treeMenuList(List<CatalogTree> treeNodes ,long pid,List<CatalogTree> tempTreeNode) {
		List<CatalogTree>	tempTreeNode1 = new ArrayList<>();
		for(CatalogTree node : treeNodes) {
			if(node.getParentId() == pid) {
				//说明存在子节点
				tempTreeNode.add(node);
				tempTreeNode1 = treeMenuList(treeNodes,node.getId(),tempTreeNode);
				if(tempTreeNode1.isEmpty()) {
					//不存在子节点
					tempTreeNode.add(node);
				}
			}
		}
		return tempTreeNode;
	}

}
