package com.yonyou.hrcloud.pm.ps.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.yonyou.hrcloud.adder.context.AppContext;
import com.yonyou.hrcloud.adder.data.jdbc.DialectHelper;
import com.yonyou.hrcloud.adder.exception.AdderBusinessException;
import com.yonyou.hrcloud.adder.model.param.PagerRequest;
import com.yonyou.hrcloud.adder.model.param.Sorter;
import com.yonyou.hrcloud.adder.model.query.Condition;
import com.yonyou.hrcloud.adder.model.query.Operator;
import com.yonyou.hrcloud.commons.org.model.CommonOrg;
import com.yonyou.hrcloud.pm.base.model.Grade;
import com.yonyou.hrcloud.pm.base.model.Period;
import com.yonyou.hrcloud.pm.base.service.IDimService;
import com.yonyou.hrcloud.pm.base.service.IGradeService;
import com.yonyou.hrcloud.pm.base.service.IPeriodService;
import com.yonyou.hrcloud.pm.base.service.IScoreRuleService;
import com.yonyou.hrcloud.pm.common.model.CommonValue;
import com.yonyou.hrcloud.pm.common.model.CommonValue.EnumWorkStep;
import com.yonyou.hrcloud.pm.common.model.PmStaff;
import com.yonyou.hrcloud.pm.helper.ListHelper;
import com.yonyou.hrcloud.pm.helper.LoggerDecorator;
import com.yonyou.hrcloud.pm.helper.OrgHelper;
import com.yonyou.hrcloud.pm.helper.StaffHelper;
import com.yonyou.hrcloud.pm.ps.dao.ISchemeDao;
import com.yonyou.hrcloud.pm.ps.dao.ISheetDao;
import com.yonyou.hrcloud.pm.ps.dao.ISummarySchemeDao;
import com.yonyou.hrcloud.pm.ps.model.EvaAppraiser;
import com.yonyou.hrcloud.pm.ps.model.EvaGroup;
import com.yonyou.hrcloud.pm.ps.model.EvaObject;
import com.yonyou.hrcloud.pm.ps.model.Scheme;
import com.yonyou.hrcloud.pm.ps.model.SchemeExtend;
import com.yonyou.hrcloud.pm.ps.model.SchemeFlow;
import com.yonyou.hrcloud.pm.ps.model.SchemeRelation;
import com.yonyou.hrcloud.pm.ps.service.IEvaAppraiserService;
import com.yonyou.hrcloud.pm.ps.service.IEvaGroupService;
import com.yonyou.hrcloud.pm.ps.service.ISheetService;
import com.yonyou.hrcloud.pm.ps.service.ISummarySchemeService;

/**
 * 绩效汇总方案实现层
 *
 * @author Flysea
 *
 */
@Service
@Transactional
public class SummarySchemeServiceImpl implements ISummarySchemeService {

	@Resource
	public com.yonyou.hrcloud.adder.service.IGenericService daoex;

	@Resource
	public ISchemeDao dao;

	@Resource
	ISummarySchemeDao sumdao;

	@Resource
	public IPeriodService periodSrv;

	@Resource
	public IEvaGroupService groupSrv;

	@Resource
	public IDimService dimSrv;

	@Resource
	public IScoreRuleService scoreRuleSrv;

	@Resource
	public IGradeService gradeSrv;

	@Resource
	public ISheetDao daoSheet;

	@Resource
	public IEvaAppraiserService evaApprSrv;

	@Resource
	public ISheetService sheetSrv;

	protected static final Logger logger = new LoggerDecorator(SummarySchemeServiceImpl.class);

	@Override
	public Page<Scheme> querySchemeByConditon(Condition cond, Sorter sort, Pageable pageable) {
		if (pageable == null)
			pageable = new PagerRequest(0, 100);
		if (sort != null)
			((PagerRequest) pageable).setSort(sort);
		Page<Scheme> objPage = daoex.findPage(Scheme.class, cond, pageable);
		List<Scheme> objs = objPage.getContent();

		for (Scheme obj : objs) {
			obj.setSchememodename(CommonValue.EnumSchemeMode.valueOf(obj.getSchememode()).getDescription());
			obj.setSchemestatename(CommonValue.EnumSchemeState.values()[obj.getSchemestate()].getDescription());
		}
		return objPage;
	}

	@Override
	public Page<Scheme> querySummarySchemeList(Condition cond, Sorter sort, Pageable pageable) {
		OrgHelper.setOrgCondition(cond, CommonValue.EnumServiceCode.SCHEME.getCode());
		Page<Scheme> schemePage = querySchemeByConditon(cond, sort, pageable);
		List<Scheme> schemeList = schemePage.getContent();
		if (schemeList.isEmpty())
			return schemePage;
		List<String> schemeids = new ArrayList<>();
		List<String> orgids = new ArrayList<>();
		for (Scheme obj : schemeList) {
			Period p = periodSrv.queryPeriodByID(obj.getPeriodid());
			obj.setPeriodname(p.getPeriodname());
			if (obj.getSchemestate() <= CommonValue.EnumSchemeState.State2.getIndex())
				obj.setPercent(0);
			else if (obj.getSchemestate() == CommonValue.EnumSchemeState.State7.getIndex()) {
				// 各轮审核都完成的人数与总人数的比例
				int percent = daoSheet.queryResultRatio(obj.getId());
				obj.setPercent(percent);
			} else
				obj.setPercent(100);
			if (!schemeids.contains(obj.getId()))
				schemeids.add(obj.getId());
			if (obj.getOrgid().length() > 0
                    && !CommonValue.EnumDataBaseSpecial.Empty.getSymbol().equals(obj.getOrgid())
                    && !orgids.contains(obj.getOrgid()))
				orgids.add(obj.getOrgid());
		}
		// 查询扩展属性
		cond = new Condition();
		cond.addExpression("schemeid", schemeids, Operator.IN);
		List<SchemeExtend> extList = daoex.find(SchemeExtend.class, cond, null);
		// Map<String, SchemeExtend> extMap = extList.stream()
		// .collect(Collectors.toMap(SchemeExtend::getSchemeid, Function.identity()));
		Map<String, SchemeExtend> extMap = ListHelper.toMap(extList, "getSchemeid");
		// 获取组织名称
		Map<String, String> orgMap = new Hashtable<>();
		logger.error("@@@nijb.logger==>###orgids.size="+orgids.size());
		logger.error("@@@nijb.logger==>###orgids.json="+JSONObject.toJSONString(orgids));
		if (!orgids.isEmpty()) {
			cond = new Condition();
			cond.addExpression("id", orgids, Operator.IN);
			List<CommonOrg> orgList = OrgHelper.queryOrgListByCondition(cond, null);
			// orgMap = orgList.stream().collect(Collectors.toMap(CommonOrg::getId,
			// CommonOrg::getName));
			orgMap = ListHelper.toMap(orgList, "getId", "getName");
		}
		for (Scheme obj : schemeList) {
			obj.setOSchemeExtend(extMap.get(obj.getId()));
			if (orgMap.containsKey(obj.getOrgid()))
				obj.setOrgname(orgMap.get(obj.getOrgid()));
		}
		return schemePage;
	}

	@Override
	public List<Period> querySummaryPeriods() {
		Condition cond = new Condition();
		// start 汇总方案查询期间 过滤掉部门问题修复  徐鹏 xupeng 20211103
//		List<String> orgids = OrgHelper.getHasRightCorpIdList(CommonValue.EnumServiceCode.SCHEME.getCode());
//		if (orgids == null)
//			orgids = new ArrayList<>();
//		orgids.add(CommonValue.EnumDataBaseSpecial.Empty.getSymbol());
//		cond.addExpression("orgid", orgids, Operator.IN);
		OrgHelper.setOrgCondition(cond, CommonValue.EnumServiceCode.SCHEME.getCode());
		// end 汇总方案查询期间 过滤掉部门问题修复  徐鹏 xupeng 20211103
		cond.addExpression("schememode", CommonValue.EnumSchemeMode.pm_sum.getIndex());
		cond.addExpression("tenantid", AppContext.getContext().getScope());
		List<Period> objs = sumdao.querySummaryPeriods(cond);
		return objs;
	}

	@Override
	public Scheme querySchemeByID(String id, boolean isAll) throws AdderBusinessException {
		if (isAll)
			return querySchemeByID(id, true, true);
		else
			return querySchemeByID(id, false, false);
	}

	@Override
	public Scheme querySchemeByID(String id, boolean hasGroup, boolean hasRelation) throws AdderBusinessException {
		Condition condObj = new Condition();
		condObj.addExpression("id", id);
		//OrgHelper.setOrgCondition(condObj, CommonValue.EnumServiceCode.SCHEME.getCode());
		List<Scheme> objs = daoex.find(Scheme.class, condObj, null);
		if (objs.size() > 0) {
			//绩效期间
			Scheme obj = objs.get(0);
			Period p = periodSrv.queryPeriodByID(obj.getPeriodid());
			obj.setPeriodname(p.getPeriodname());
			//组织
			if(StringUtils.isNoneEmpty(obj.getOrgid())){
					/*condObj = new Condition();
					condObj.addExpression("id", Arrays.asList(obj.getOrgid()), Operator.IN);
					List<CommonOrg> orgList = OrgHelper.queryOrgListByCondition(condObj, null);
					if(orgList.size()>0){
						obj.setOrgname(orgList.get(0).getName());
					}*/
//					CommonOrg org = OrgHelper.loadOrgById(obj.getOrgid());
//					if(org != null){
//						obj.setOrgname(org.getName());
//					}
				// 20211124 修复汇总方案查询所属组织部门逻辑（原逻辑只查组织）
				Condition cond = new Condition();
				cond.addExpression("id", Arrays.asList(obj.getOrgid()), Operator.IN);
				List<CommonOrg> orgList = OrgHelper.queryOrgListByCondition(cond, null);
				if (orgList != null && !orgList.isEmpty()) {
                    obj.setOrgname(orgList.get(0).getName());
                }
			}
			// 汇总对象来源
			condObj = new Condition();
			condObj.addExpression("schemeid", obj.getId());
			List<SchemeExtend> extendlist = daoex.find(SchemeExtend.class, condObj, null);
			if(extendlist.size() > 0){
				obj.setOSchemeExtend(extendlist.get(0));
			}
			//考核结果等级
			Grade grade = gradeSrv.queryGradeByID(obj.getGradeid(), false);
			if(grade!=null){
				obj.setGradename(grade.getGradename());
			}
			if (!hasGroup && !hasRelation)
				return obj;

			// 1、查询考核对象组信息
			condObj = new Condition();
			condObj.addExpression("schemeid", obj.getId());
			List<EvaGroup> groups = groupSrv.queryEvaGroupByConditon(condObj, null);
			if (hasGroup) {
				for(EvaGroup group : groups){
					condObj = new Condition();
					condObj.addExpression("groupid", group.getId());
					List<EvaObject> objectlist = groupSrv.queryEvaObjectByConditon(condObj, null); // new Sorter(Direction.ASC, Arrays.asList("turn", "workstep"))
					// List<String> staffidList =
					// objectlist.stream().map(EvaObject::getStaffid).distinct().collect(Collectors.toList());
					List<String> staffidList = ListHelper.collect(objectlist, "getStaffid");
					Map<String, PmStaff> staffList = StaffHelper
							.queryStaffByIds(staffidList);
					for (EvaObject psn : objectlist) {
						PmStaff pmStaff = staffList.get(psn.getStaffid());
						psn.setStaff(pmStaff);
					}
					group.setOEvaObjects(objectlist);
				}
			}
			obj.setOGroups(groups);
			if (hasRelation) {
				condObj = new Condition();
				condObj.addExpression("schemeid", obj.getId());
				List<SchemeRelation> relationList = daoex.find(SchemeRelation.class, condObj, null);
				for(SchemeRelation relation : relationList){ // TODO 待优化遍历
					Period oPeriod = daoex.load(Period.class,relation.getFormulaperiodid());
					relation.setOPeriod(oPeriod);
				}
				obj.setOSchemeRelation(relationList);
			}
			return obj;
		} else
			return null;
	}

	@Override
	public Scheme queryAuthorizedSchemeByID(String id, boolean isAll) throws AdderBusinessException {
		if (isAll)
			return queryAuthorizedSchemeByID(id, true, true);
		else
			return queryAuthorizedSchemeByID(id, false, false);
	}

	@Override
	public Scheme queryAuthorizedSchemeByID(String id, boolean hasGroup, boolean hasRelation) throws AdderBusinessException {
		Condition condObj = new Condition();
		condObj.addExpression("id", id);
		OrgHelper.setOrgCondition(condObj, CommonValue.EnumServiceCode.SCHEME.getCode());
		List<Scheme> objs = daoex.find(Scheme.class, condObj, null);
		if (objs.size() > 0) {
			//绩效期间
			Scheme obj = objs.get(0);
			Period p = periodSrv.queryPeriodByID(obj.getPeriodid());
			obj.setPeriodname(p.getPeriodname());
			//组织
			if(StringUtils.isNoneEmpty(obj.getOrgid())){
				try{ // TODO 人员服务不稳定，暂时try-catch
					/*condObj = new Condition();
					condObj.addExpression("id", Arrays.asList(obj.getOrgid()), Operator.IN);
					List<AdminOrg> orgList = orgService.queryOrgListByCondition(condObj, null);
					if(orgList.size()>0){
						obj.setOrgname(orgList.get(0).getName());
					}*/
					CommonOrg org = OrgHelper.loadOrgById(obj.getOrgid());
					if(org != null){
						obj.setOrgname(org.getName());
					}
				}catch(Exception e){
					logger.error(e.getMessage());
				}
			}
			// 汇总对象来源
			condObj = new Condition();
			condObj.addExpression("schemeid", obj.getId());
			List<SchemeExtend> extendlist = daoex.find(SchemeExtend.class, condObj, null);
			if(extendlist.size() > 0){
				obj.setOSchemeExtend(extendlist.get(0));
			}
			//考核结果等级
			Grade grade = gradeSrv.queryGradeByID(obj.getGradeid(), false);
			if(grade!=null){
				obj.setGradename(grade.getGradename());
			}
			if (!hasGroup && !hasRelation)
				return obj;

			// 1、查询考核对象组信息
			condObj = new Condition();
			condObj.addExpression("schemeid", obj.getId());
			List<EvaGroup> groups = groupSrv.queryEvaGroupByConditon(condObj, null);
			if (hasGroup) {
				for(EvaGroup group : groups){
					condObj = new Condition();
					condObj.addExpression("groupid", group.getId());
					List<EvaObject> objectlist = groupSrv.queryEvaObjectByConditon(condObj, null); // new Sorter(Direction.ASC, Arrays.asList("turn", "workstep"))
					// List<String> staffidList =
					// objectlist.stream().map(EvaObject::getStaffid).distinct().collect(Collectors.toList());
					List<String> staffidList = ListHelper.collect(objectlist, "getStaffid");
					Map<String, PmStaff> staffList = StaffHelper
							.queryStaffByIds(staffidList);
					for (EvaObject psn : objectlist) {
						PmStaff pmStaff = staffList.get(psn.getStaffid());
						psn.setStaff(pmStaff);
					}
					group.setOEvaObjects(objectlist);
				}
			}
			obj.setOGroups(groups);
			if (hasRelation) {
				condObj = new Condition();
				condObj.addExpression("schemeid", obj.getId());
				List<SchemeRelation> relationList = daoex.find(SchemeRelation.class, condObj, null);
				for(SchemeRelation relation : relationList){ // TODO 待优化遍历
					Period oPeriod = daoex.load(Period.class,relation.getFormulaperiodid());
					relation.setOPeriod(oPeriod);
				}
				obj.setOSchemeRelation(relationList);
			}
			return obj;
		} else
			return null;
	}

	@Override
	public void insert(Scheme scheme) {
		checkScheme(scheme);
		checkNameRepeat(scheme.getSchemename(), null);
		daoex.insert(scheme);
		// 保存方案流程
		/*if (!CollectionUtils.isEmpty(scheme.getOEvaAppraiser())) {
			List<EvaAppraiser> newEvaAppraiser = cloneApprove(scheme);
			if (newEvaAppraiser.size() > 0)
				scheme.getOEvaAppraiser().addAll(newEvaAppraiser);
			daoex.insertBatch(scheme.getOEvaAppraiser());
		}*/
		//检查方案明细权重是否为100%，以及相同期间的汇总方案
		checkSumWeight(scheme);

		if (!CollectionUtils.isEmpty(scheme.getOSchemeRelation())) {
			List<SchemeRelation> newSchemeRelation = cloneSchemeRelation(scheme);
			if (newSchemeRelation.size() > 0)
				scheme.setOSchemeRelation(newSchemeRelation);
			daoex.insertBatch(scheme.getOSchemeRelation());
		}

		if (scheme.getOSchemeExtend() != null) {
			SchemeExtend oSchemeExtend = scheme.getOSchemeExtend();
			oSchemeExtend.setSchemeid(scheme.getId());
			scheme.setOSchemeExtend(oSchemeExtend);
			daoex.insert(oSchemeExtend);
		}
		createDefaultEvaObjectAndGroup(scheme);
		// 保存默认流程
		List<SchemeFlow> flows = new ArrayList<SchemeFlow>();
		int iStepCount = 3;
		if (!scheme.isIsresultaudited())
			iStepCount = 2;
		for (int i = 1; i <= iStepCount; i++) {
			SchemeFlow flow = new SchemeFlow();
			flow.setSchemeid(scheme.getId());
			flow.setWorkstep(i * 10);
			flow.setWorksteporder(i);
			flows.add(flow);
		}
		daoex.insertBatch(flows);
	}

	@Override
	public void update(Scheme scheme) {
		checkScheme(scheme);
		checkNameRepeat(scheme.getSchemename(), scheme.getId());
		Scheme schemeold = daoex.load(Scheme.class, scheme.getId());
		if (scheme.getSchemestate() == CommonValue.EnumSchemeState.State2.getIndex()) {
			//检查方案明细权重是否为100%，以及相同期间的汇总方案
			checkSumWeight(scheme);
			//如果修改时 考核明细和汇总对象来源不变，不用更新考核对象和考核组。
			Boolean whether_update_eva = checkSumDetails(scheme);

			// 更新汇总明细
			Condition condRelation = new Condition();
			condRelation.addExpression("schemeid", scheme.getId());
			sumdao.deleteSchemerelation(condRelation);
			if (!CollectionUtils.isEmpty(scheme.getOSchemeRelation())) {
				List<SchemeRelation> newEvaAppraiser = cloneSchemeRelation(scheme);
				if (newEvaAppraiser.size() > 0)
					scheme.setOSchemeRelation(newEvaAppraiser);
				daoex.insertBatch(scheme.getOSchemeRelation());
			}
			// 更新汇总对象来源
			//Condition extendRelation = new Condition();
			//extendRelation.addExpression("schemeid", scheme.getId());
			sumdao.deleteSchemerExtend(condRelation);
			if(scheme.getOSchemeExtend() != null){
				SchemeExtend oSchemeExtend = scheme.getOSchemeExtend();
				oSchemeExtend.setId(null);
				oSchemeExtend.setSchemeid(scheme.getId());
				scheme.setOSchemeExtend(oSchemeExtend);
				daoex.insert(oSchemeExtend);
			}
			//sumdao.deleteGroupAndObjectBySchemeId(scheme.getId());
			if(whether_update_eva)
				createDefaultEvaObjectAndGroup(scheme);
		}
		if (schemeold.isIsresultaudited() != scheme.isIsresultaudited()) {
			// 如果没有结果审核，检查是否设置了结果审核设置
			if (!scheme.isIsresultaudited()) {
				if (evaApprSrv.isExistWorkStep(scheme.getId(), EnumWorkStep.step3))
					throw new AdderBusinessException("已存在结果审核设置，不能取消考核结果需要审核选项", "pm.i18n_core.ps.010");
			}
			// 调整pm_scheme_flow
			updateSchemeFlow(scheme.getId(), scheme.isIsresultaudited());
		}
		daoex.update(scheme);
	}

	private void checkSumWeight(Scheme newScheme){
		List<SchemeRelation> newrelationlist = newScheme.getOSchemeRelation();
		if(newrelationlist != null && newrelationlist.size() > 0){
			BigDecimal indi_total = new BigDecimal(0);
			for(SchemeRelation relation : newrelationlist){
				BigDecimal rate = relation.getRate();
				indi_total = indi_total.add(rate);
			}
			if (indi_total.compareTo(new BigDecimal(1)) != 0) {
	            throw new AdderBusinessException("汇总明细的方案权重之和不等于100%","pm.i18n_core.ps.056");
	        }
			//检查汇总明细中的方案，是否是同期间下的汇总方案
			String periodid = newScheme.getPeriodid();
			// List<String> schemeids =
			// newrelationlist.stream().map(SchemeRelation::getFormulaschemeid).collect(Collectors.toList());
			List<String> schemeids = ListHelper.collect(newrelationlist, "getFormulaschemeid");
			Condition cond = new Condition();
			cond.addExpression("periodid", periodid);
			cond.addExpression("id", schemeids, Operator.IN);
			cond.addExpression("schememode", CommonValue.EnumSchemeMode.pm_sum.getIndex());
			List<Scheme> schemeList = daoex.find(Scheme.class, cond, null);
			if( schemeList!=null &&schemeList.size() > 0){
				throw new AdderBusinessException("汇总明细中不能存在相同考核期间的其他汇总方案","pm.i18n_core.ps.057");
			}
		}
	}
	/**
	 * 检查汇总方案来源和汇总明细是否发生变化
	 */
	private Boolean checkSumDetails(Scheme newScheme){
		Boolean whether_update_eva = false; // false 不需要更新
		//首先判断汇总来源是否相同
		Condition cond = new Condition();
		cond.addExpression("schemeid", newScheme.getId());
		List<SchemeExtend> oldextendlist = daoex.find(SchemeExtend.class, cond, null);
		if(oldextendlist.size() > 0){ // 肯定大于0
			if(oldextendlist.get(0).getSumsource() != newScheme.getOSchemeExtend().getSumsource()){
				whether_update_eva = true; // 需要更新
			}
		}
		// 如果不需要更新,则进一步判断汇总明细是否发生改变
		if(!whether_update_eva){
			//判断汇总明细方案是否完全相同
			List<SchemeRelation> oldrelationlist = daoex.find(SchemeRelation.class, cond, null);
			List<SchemeRelation> newrelationlist = newScheme.getOSchemeRelation();
			if(oldrelationlist.size() == newrelationlist.size()){
				// List<String> oldschemeids =
				// oldrelationlist.stream().map(SchemeRelation::getFormulaschemeid).collect(Collectors.toList());
				List<String> oldschemeids = ListHelper.collect(oldrelationlist, "getFormulaschemeid");
				// List<String> newschemeids =
				// newrelationlist.stream().map(SchemeRelation::getFormulaschemeid).collect(Collectors.toList());
				List<String> newschemeids = ListHelper.collect(newrelationlist, "getFormulaschemeid");
				//集合长度相同时，求差集
				oldschemeids.removeAll(newschemeids);
				if(oldschemeids.size() > 0){
					whether_update_eva = true; // 需要更新
				}
			} else{
				whether_update_eva = true; // 需要更新
			}
		}
		return whether_update_eva;
	}
	@Override
	public void delete(String id) {
		String dbType = DialectHelper.getDBType();
		dao.delete(id, dbType);
	}

	@Override
	public List<EvaAppraiser> queryEvaAppraiserByConditon(Condition cond, Sorter sort) {
		List<EvaAppraiser> objs = daoex.find(EvaAppraiser.class, cond, sort);
		return objs;
	}

	/**
	 * 汇总方案创建和修改时，创建默认的考核组和考核人
	 */
	private List<EvaGroup> createDefaultEvaObjectAndGroup(Scheme sumscheme){
		//先删除原有的组和考核对象
		//groupSrv.deleteBySumschemeid(sumscheme.getId());
		sumdao.deleteGroupAndObjectBySchemeId(sumscheme.getId());
		List<SchemeRelation> relationList = sumscheme.getOSchemeRelation();
		SchemeExtend oSchemeExtend = sumscheme.getOSchemeExtend();
		if(relationList == null || relationList.size() <= 0 || oSchemeExtend == null){
			return null;
		}
		// 组的优先级 就按方案的排序
		// List<String> schemeids =
		// relationList.stream().map(SchemeRelation::getFormulaschemeid).distinct().collect(Collectors.toList());
		List<String> schemeids = ListHelper.collect(relationList, "getFormulaschemeid");
		Condition schemeObj = new Condition();
		schemeObj.addExpression("id", schemeids, Operator.IN);
		List<Scheme> schemelist = dao.querySchemeByConditon(schemeObj, new Sorter(Direction.DESC, "creationtime" ,"tdate", "fdate")); // 按创建时间查询所有方案
		//List<String> schemeidsort = schemelist.stream().map(Scheme::getId).distinct().collect(Collectors.toList());
		final List<String> schemeidsort = ListHelper.collect(schemelist,"getId");
		//根据方案创建时间排序  对分组进行排序
		Condition condObj = new Condition();
		condObj.addExpression("schemeid", schemeids, Operator.IN);
		List<EvaGroup> grouplist = groupSrv.queryEvaGroupByConditon(condObj, new Sorter(Direction.DESC, "schemeid")); // 查询所有组
		// 所有的考核组进行排序
		// List<String> groupidsort = grouplist.stream().sorted((evagroup1,evagroup2) ->
		// {
		// return schemeidsort.indexOf(evagroup1.getSchemeid()) -
		// schemeidsort.indexOf(evagroup2.getSchemeid());
		// }).map(EvaGroup::getId).collect(Collectors.toList());
		Collections.sort(grouplist, new Comparator<EvaGroup>() {
			@Override
			public int compare(EvaGroup evagroup1, EvaGroup evagroup2) {
				return schemeidsort.indexOf(evagroup1.getSchemeid()) - schemeidsort.indexOf(evagroup2.getSchemeid());
			}
		});
		final List<String> groupidsort = ListHelper.collect(grouplist, "getId");
		// Map<String, String> groupinfo =
		// grouplist.stream().collect(Collectors.toMap(EvaGroup::getId,
		// EvaGroup::getGroupname));
		Map<String, String> groupinfo = ListHelper.toMap(grouplist, "getId", "getGroupname");

		//List<EvaObject> objectlist = groupSrv.queryEvaObjectByConditon(condObj, new Sorter(Direction.DESC, "schemeid")); //查询所有人
		List<EvaObject> objectlist = groupSrv.queryEnableEvaObjectByConditon(schemeids); //查询所有人
		if(objectlist.size() <= 0){
			return null;
		}
		// 定义方法最终返回数据格式
		HashMap<String, EvaGroup> result = new HashMap<String, EvaGroup>();
		// Map<String, List<String>> objectGroup = objectlist.stream()
		// .collect(Collectors.groupingBy(evaobject -> evaobject.getStaffid(),
		// Collectors.mapping(evaobject -> evaobject.getGroupid(),
		// Collectors.toList())));
		Map<String, List<String>> objectGroup = ListHelper.groupingBy(objectlist, "getStaffid", "getGroupid");
		int schemecnt = relationList.size();
		for(String staffid : objectGroup.keySet()){
			List<String> list = objectGroup.get(staffid);
			String groupid = null;
			if (oSchemeExtend.getSumsource() == 0) {// 并集
				if (list.size() == 1) {
					groupid = list.get(0);
				} else {
					// list = list.stream().sorted((groupid1,groupid2) -> {
					// return groupidsort.indexOf(groupid1) - groupidsort.indexOf(groupid2);
					// }).collect(Collectors.toList());
					Collections.sort(list,new Comparator<String>() {
						@Override
						public int compare(String groupid1, String groupid2) {
							return groupidsort.indexOf(groupid1) - groupidsort.indexOf(groupid2);
						}
					});
					groupid = list.get(0);
				}
			} else { // 交集
				if (list.size() >= schemecnt) { // 只有全部都有才计算
					// list = list.stream().sorted((groupid1,groupid2) -> {
					// return groupidsort.indexOf(groupid1) - groupidsort.indexOf(groupid2);
					// }).collect(Collectors.toList());
					Collections.sort(list, new Comparator<String>() {
						@Override
						public int compare(String groupid1, String groupid2) {
							return groupidsort.indexOf(groupid1) - groupidsort.indexOf(groupid2);
						}
					});
					groupid = list.get(0);
				} else {
					continue;
				}
			}
			EvaObject evaObject = new EvaObject();
			evaObject.setStaffid(staffid);
			evaObject.setSchemeid(sumscheme.getId());
			EvaGroup evaGroup = result.get(groupid);
			if(evaGroup == null){
				evaGroup = new EvaGroup();
				evaGroup.setGroupname(groupinfo.get(groupid));
				evaGroup.setSchemeid(sumscheme.getId());
				evaGroup.setOEvaObjects(new ArrayList<EvaObject>());
				result.put(groupid, evaGroup);
			}
			evaGroup.getOEvaObjects().add(evaObject);
		}
		if(result.size() <= 0){
			return null;
		}
		//把重名的组合并
		// Map<String, List<String>> groupnamemap = grouplist.stream()
		// .collect(Collectors.groupingBy(EvaGroup::getGroupname,
		// Collectors.mapping(EvaGroup::getId, Collectors.toList())));
		Map<String, List<String>> groupnamemap = ListHelper.groupingBy(grouplist, "getGroupname", "getId");

		ArrayList<EvaGroup> returndata = new ArrayList<EvaGroup>();
		for(String groupname : groupnamemap.keySet()){
			List<String> groupidlist = groupnamemap.get(groupname);
			EvaGroup evaGroup = null;
			for(String groupid : groupidlist){
				if(result.get(groupid) != null){
					if(evaGroup == null)
						evaGroup = result.get(groupid);
					else{
						evaGroup.getOEvaObjects().addAll(result.get(groupid).getOEvaObjects());
					}
				}
			}
			if(evaGroup != null){
				groupSrv.insert2(evaGroup);
				returndata.add(evaGroup);
			}
		}
		sumscheme.setOGroups(returndata);
		return returndata;
	}

	/**
	 * 选择了指标审核，要新生成一行记录
	 *
	 * @param scheme
	 * @return
	 */
	private List<EvaAppraiser> cloneApprove(Scheme scheme) {
		List<EvaAppraiser> newEvaAppraiser = new ArrayList<EvaAppraiser>();
		for (EvaAppraiser obj : scheme.getOEvaAppraiser()) {
			if (StringUtils.isEmpty(obj.getDimid()))
				throw new AdderBusinessException("方案流程考核人类别不正确", "pm.i18n_core.ps.011");
			// 先删除后增加，所以清空id
			obj.setId(null);
			obj.setSchemeid(scheme.getId());
			obj.setWorkstep(EnumWorkStep.step2.getIndex());
			// clone指标审核，结果审核的顺序不调整，显示时可以匹配
			if (obj.getIsapprove()) {
				try {
					EvaAppraiser newobj = (EvaAppraiser) obj.clone();
					newobj.setWorkstep(EnumWorkStep.step1.getIndex());
					newobj.setWeight(null);
					newEvaAppraiser.add(newobj);
				} catch (CloneNotSupportedException e) {
					throw new AdderBusinessException(e, e.getMessage(), "");
				}
			}
		}
		if (newEvaAppraiser.isEmpty())
			throw new AdderBusinessException("方案流程中没有选择指标审核", "pm.i18n_core.ps.012");
		return newEvaAppraiser;
	}

	/**
	 * 选择了指标审核，要新生成一行记录
	 *
	 * @param scheme
	 * @return
	 */
	private List<SchemeRelation> cloneSchemeRelation(Scheme scheme) {
		List<SchemeRelation> newSchemeRelation = new ArrayList<SchemeRelation>();
		int i = 0;
		for (SchemeRelation obj : scheme.getOSchemeRelation()) {
			if (StringUtils.isEmpty(obj.getFormulaschemeid()))
				throw new AdderBusinessException("汇总方案明细设置不正确", "pm.i18n_core.ps.011");  // TODO 多语
			// 先删除后增加，所以清空id
			obj.setId(null);
			obj.setSchemeid(scheme.getId());
			obj.setOrdernum( i++ );
			Scheme load = daoex.load(Scheme.class, obj.getFormulaschemeid());
			obj.setFormulaperiodid(load.getPeriodid());
			obj.setFormulaschememode(load.getSchememode());
			obj.setFormulaschemename(load.getSchemename());
			newSchemeRelation.add(obj);
		}
		if (newSchemeRelation.isEmpty())
			throw new AdderBusinessException("方案流程中没有选择汇总明细", "pm.i18n_core.ps.012");
		return newSchemeRelation;
	}

	/**
	 * 检查方案数据正确性
	 *
	 * @param scheme
	 */
	private void checkScheme(Scheme scheme) {
		if ("".equals(scheme.getId()))
			throw new AdderBusinessException("方案id不正确", "pm.i18n_core.ps.013");
		if (scheme.getSchemename().length() > 40)
			throw new AdderBusinessException("方案名称不能超过{0}个字符", "pm.i18n_core.ps.014", "40");
		if (scheme.getRemark() != null && scheme.getRemark().length() > 200)
			throw new AdderBusinessException("方案数据不正确", "pm.i18n_core.ps.021");

		Period p = periodSrv.queryPeriodByID(scheme.getPeriodid());
		if (p == null)
			throw new AdderBusinessException("方案中周期不存在", "pm.i18n_core.ps.015");
		if (scheme.getOrgid() == null)
			throw new AdderBusinessException("方案所属组织不正确", "pm.i18n_core.ps.016");
		if (!scheme.getPeriodcode().equals(p.getPeriodcode()))
			throw new AdderBusinessException("方案中周期不存在", "pm.i18n_core.ps.015");
		/*ScoreRule sr = scoreRuleSrv.queryScoreRuleByID(scheme.getScoreruleid());
		if (sr == null)
			throw new AdderBusinessException("方案中评分规则不存在", "pm.i18n_core.ps.017");
		if (sr.getOrgid().length() > 0 && !sr.getOrgid().equals(scheme.getOrgid()))
			throw new AdderBusinessException("方案与评分规则所属组织不一致", "pm.i18n_core.ps.018");*/
		Grade grade = gradeSrv.queryGradeByID(scheme.getGradeid(), true);
		if (grade == null)
			throw new AdderBusinessException("方案中考核结果等级不存在", "pm.i18n_core.ps.019");
		// if (grade.getOrgid().length() > 0 && !grade.getOrgid().equals(scheme.getOrgid()))
		if (!CommonValue.EnumDataBaseSpecial.Empty.getSymbol().equals(grade.getOrgid()) && !grade.getOrgid().equals(scheme.getOrgid()))
			throw new AdderBusinessException("方案与考核等级所属组织不一致", "pm.i18n_core.ps.020");
		boolean ok = true;
		if (scheme.getSchememode() != 10 )
			ok = false;
		else if (scheme.getAbstentionmode() < 0 || scheme.getAbstentionmode() > 2)
			ok = false;
		else if (scheme.getApplyobj() > 2 || scheme.getApplyobj() < 1)
			ok = false;
		/*else if (scheme.getScoreway() < 1 || scheme.getScoreway() > 3) // 汇总方案没有方案汇总规则
			ok = false;*/
		if (!ok)
			throw new AdderBusinessException("方案数据不正确", "pm.i18n_core.ps.021");
		/*if (scheme.getOEvaAppraiser() != null) { // 汇总方案没有 审核人
			BigDecimal bignum1 = new BigDecimal("100");
			BigDecimal bignum2 = BigDecimal.ZERO;
			for (EvaAppraiser item : scheme.getOEvaAppraiser()) {
				// 循环每一个轮次
				if (item.getTurn() < 0 && item.getTurn() > scheme.getOEvaAppraiser().size())
					throw new AdderBusinessException("方案流程轮次不正确", "pm.i18n_core.ps.022");
				else if ("".equals(item.getStaffid()))
					item.setStaffid(null);
				if (item.getWeight() != null)
					bignum2 = bignum2.add(item.getWeight());
			}
			if (bignum1.compareTo(bignum2) < 0)
				throw new AdderBusinessException("方案数据不正确", "pm.i18n_core.ps.021");
		}*/
		// 检查考核等级是否涵盖了评分方式
		/*BigDecimal upper = grade.getOGradeItem().get(0).getUpperlimit();
		BigDecimal lower = grade.getOGradeItem().get(grade.getOGradeItem().size() - 1).getLowerlimit();
		BigDecimal srupper = sr.getUpperlimit();
		BigDecimal srlower = sr.getLowerlimit();
		if (sr.getRuletype() == CommonValue.EnumScoreRuleType.Grade.getIndex()) {
			// 等级式判断标准分范围
			Collections.sort(sr.getOGradeItem(), new Comparator<GradeItem>() {
				@Override
				public int compare(GradeItem o1, GradeItem o2) {
					int i = o1.getStandardscore().compareTo(o2.getStandardscore());
					return i;
				}
			});
			srlower = sr.getOGradeItem().get(0).getStandardscore();
			srupper = sr.getOGradeItem().get(sr.getOGradeItem().size() - 1).getStandardscore();
		}*/
		/*if (upper != null && upper.compareTo(srupper) < 0 || lower != null && lower.compareTo(srlower) > 0)
			throw new AdderBusinessException("考核等级范围要覆盖评分方式，请修改", "pm.i18n_core.ps.023");*/
	}

	/**
	 * 检查名称是否重复
	 *
	 * @param name
	 *            方案名称
	 * @param id
	 *            修改时id
	 */
	private void checkNameRepeat(String name, String id) {
		Condition condObj = new Condition();
		condObj.addExpression("schemename", name);
		Pageable page = new PagerRequest(0, 2);
		List<Scheme> objs = daoex.findPage(Scheme.class, condObj, page).getContent();
		if (!objs.isEmpty()) {
			for (Scheme item : objs) {
				if (id == null || !item.getId().equals(id))
					throw new AdderBusinessException("考核方案名称重复", "pm.i18n_core.ps.024");
			}
		}
	}

	/**
	 * 调整方案流程顺序
	 *
	 * @param schemeid
	 * @param isResultaudited
	 *            是否结果审核
	 */
	private void updateSchemeFlow(String schemeid, boolean isResultaudited) {
		if (isResultaudited) {
			SchemeFlow flow = new SchemeFlow();
			flow.setSchemeid(schemeid);
			flow.setWorkstep(EnumWorkStep.step3.getIndex());
			flow.setWorksteporder(3);
			daoex.insert(flow);
		} else {
			Condition condObj = new Condition();
			condObj.addExpression("schemeid", schemeid);
			condObj.addExpression("workstep", EnumWorkStep.step3.getIndex());
			List<SchemeFlow> flows = daoex.find(SchemeFlow.class, condObj, null);
			for (SchemeFlow item : flows)
				daoex.delete(SchemeFlow.class, item.getId());
		}
	}

	@Override
	public Scheme getSchemeInfoForUpdate(String schemeid) {
		Scheme load = daoex.load(Scheme.class, schemeid);
		return load;
	}

	@Override
	public List queryEvaObjectByCond(JSONObject data) {
		String schemeid = data.getString("schemeid");
		Scheme sumscheme = daoex.load(Scheme.class, schemeid);
		String groupid = data.getString("groupid");
		if(StringUtils.isNotEmpty(groupid)){
			Condition groupRelation = new Condition();
			groupRelation.addExpression("schemeid", schemeid);
			groupRelation.addExpression("groupid", groupid);
			List<EvaObject> objectlist = daoex.find(EvaObject.class, groupRelation, null);
			// List<String> staffids =
			// objectlist.stream().map(EvaObject::getStaffid).collect(Collectors.toList());
			List<String> staffids = ListHelper.collect(objectlist, "getStaffid");
			Map<String, PmStaff> staffMap = StaffHelper.queryStaffByIds(staffids);
			List<PmStaff> stafflist = filterEvaojbData(sumscheme,staffMap,data);
			// Map<String, EvaObject> collect =
			// objectlist.stream().collect(Collectors.toMap(EvaObject::getStaffid,
			// EvaObject->EvaObject));
			Map<String, EvaObject> collect = ListHelper.toMap(objectlist, "getStaffid");
			List<EvaObject> resultList = new ArrayList<EvaObject>();
			for(PmStaff sstaff : stafflist){
				EvaObject evaObject = collect.get(sstaff.id);
				evaObject.setStaff(sstaff);
				resultList.add(evaObject);
			}
			return resultList;
		} else {
			List<SchemeRelation> relationList = sumscheme.getOSchemeRelation();
			if(relationList == null){
				Condition condRelation = new Condition();
				condRelation.addExpression("schemeid", schemeid);
				relationList = daoex.find(SchemeRelation.class, condRelation, null);
			}
			SchemeExtend oSchemeExtend = sumscheme.getOSchemeExtend();
			if(oSchemeExtend == null){
				Condition condRelation = new Condition();
				condRelation.addExpression("schemeid", schemeid);
				List<SchemeExtend> extendlist = daoex.find(SchemeExtend.class, condRelation, null);
				if(extendlist.size() > 0){
					oSchemeExtend = extendlist.get(0);
				} else
					return new ArrayList<>();
			}
			//Scheme scheme
			// 组的优先级 就按方案的排序
			// List<String> schemeids =
			// relationList.stream().map(SchemeRelation::getFormulaschemeid).distinct().collect(Collectors.toList());
			List<String> schemeids = ListHelper.collect(relationList, "getFormulaschemeid");

			// 查询所有明细方案所有人
			Condition allSchemeObj = new Condition();
			allSchemeObj.addExpression("schemeid", schemeids, Operator.IN);
			//List<EvaObject> allschemeobjlist = groupSrv.queryEvaObjectByConditon(allSchemeObj, new Sorter(Direction.DESC, "schemeid")); //查询所有明细方案所有人
			List<EvaObject> allschemeobjlist = groupSrv.queryEnableEvaObjectByConditon(schemeids); //查询所有明细方案有效考核人
			// Map<String, List<String>> objectGroup = allschemeobjlist.stream()
			// .collect(Collectors.groupingBy(evaobject -> evaobject.getStaffid(),
			// Collectors.mapping(evaobject -> evaobject.getGroupid(),
			// Collectors.toList())));
			Map<String, List<String>> objectGroup = ListHelper.groupingBy(allschemeobjlist, "getStaffid", "getGroupid");

			List<String> staffids = new ArrayList<>();
			if(oSchemeExtend.getSumsource() == 0){ // 并集
				// staffids =
				// objectGroup.keySet().stream().distinct().collect(Collectors.toList());
				staffids = ListHelper.distinct(new ArrayList<>(objectGroup.keySet()));
			} else {
				// staffids = objectGroup.keySet().stream().filter(staffid ->
				// objectGroup.get(staffid).size() >=
				// schemeids.size()).collect(Collectors.toList());
				for (Map.Entry<String, List<String>> entry : objectGroup.entrySet()) {
					if (entry.getValue().size() >= schemeids.size())
						staffids.add(entry.getKey());
				}
			}

			int nogroup = data.getIntValue("nogroup"); // 取没有分组的人员吗。
			if(nogroup == 1){ // 所有明细方案的考核对象（交集或并集）  - 当前汇总方案的考核对象  = 没有分组的人
				 //查询汇总方案下所有人
				Condition sumcondObj = new Condition();
				sumcondObj.addExpression("schemeid", sumscheme.getId());
				List<EvaObject> sumschemeobjlist = groupSrv.queryEvaObjectByConditon(sumcondObj, new Sorter(Direction.DESC, "schemeid"));
				// List<String> sumschemeobjectids =
				// sumschemeobjlist.stream().map(EvaObject::getStaffid).distinct().collect(Collectors.toList());
				List<String> sumschemeobjectids = ListHelper.collect(sumschemeobjlist, "getStaffid");
				// 取集合差
				List<String> staffidsTmp = new ArrayList<>();
				// staffids = staffids.stream().filter(staffid ->
				// !sumschemeobjectids.contains(staffid)).distinct().collect(Collectors.toList());
				for (String item : staffids) {
					if (!sumschemeobjectids.contains(item))
						staffidsTmp.add(item);
				}
				staffids = staffidsTmp;
			}
			Map<String, PmStaff> staffMap = StaffHelper.queryStaffByIds(staffids);
			List<PmStaff> filterEvaojbData = filterEvaojbData(sumscheme, staffMap, data);
			return filterEvaojbData;
		}
	}

	/**
	 * 过滤考核对象信息
	 *
	 * @param sumscheme
	 * @param data
	 */
	private List<PmStaff> filterEvaojbData(Scheme sumscheme, Map<String, PmStaff> staffMap, JSONObject data) {
		// List<PmStaff> stafflist =
		// staffMap.values().stream().collect(Collectors.toList());
		List<PmStaff> stafflist = new ArrayList<>(staffMap.values());
		// 过滤
		String name = data.getString("name"); // 模糊匹配人员姓名
		String jobid = data.getString("jobid"); // 参照人员职务id
		String postid = data.getString("postid"); // 参照人员岗位id
		String psnclid = data.getString("psnclid"); // 参照人员类别id
		if (StringUtils.isNotEmpty(name) || StringUtils.isNotEmpty(jobid) || StringUtils.isNotEmpty(postid)
				|| StringUtils.isNotEmpty(psnclid)) {
			List<PmStaff> stafflistTmp = new ArrayList<>();
			for (PmStaff staff : stafflist) {
				boolean result = true;
				if (StringUtils.isNotEmpty(name) && !staff.name.contains(name))
					result = false;
				if (StringUtils.isNotEmpty(jobid) && !jobid.equals(staff.jobid))
					result = false;
				if (StringUtils.isNotEmpty(postid) && !postid.equals(staff.postid))
					result = false;
				if (StringUtils.isNotEmpty(psnclid) && !psnclid.equals(staff.psnclid))
					result = false;
				if (result)
					stafflistTmp.add(staff);
			}
			stafflist = stafflistTmp;
			// stafflist = stafflist.stream().filter(staff -> {
			// if (StringUtils.isNotEmpty(name) && !staff.name.contains(name))
			// return false;
			// if (StringUtils.isNotEmpty(jobid) && !jobid.equals(staff.jobid))
			// return false;
			// if (StringUtils.isNotEmpty(postid) && !postid.equals(staff.postid))
			// return false;
			// if (StringUtils.isNotEmpty(psnclid) && !psnclid.equals(staff.psnclid))
			// return false;
			// return true;
			// }).collect(Collectors.toList());
		}
		// 查询已有汇总方案的人员
		/*
		 * List<String> beenEva = groupSrv.getEvaobjBeenAggregated(sumscheme,
		 * stafflist.stream().map(staff ->
		 * staff.id).distinct().collect(Collectors.toList()));
		 */
		// List<EvaObject> beenEva = groupSrv.findBasedOnExistingSumschemes(sumscheme,
		// stafflist.stream().map(staff ->
		// staff.id).distinct().collect(Collectors.toList()));
		List<String> stafflistTmp = ListHelper.collect(stafflist, "id");
		List<EvaObject> beenEva = groupSrv.findBasedOnExistingSumschemes(sumscheme, stafflistTmp);

		Map<String, Scheme> schemeObj = new HashMap<String, Scheme>();
		if (beenEva != null && beenEva.size() > 0) {
			// List<String> schemeids =
			// beenEva.stream().map(EvaObject::getSchemeid).distinct().collect(Collectors.toList());
			List<String> schemeids = ListHelper.collect(beenEva, "getSchemeid");
			Condition schemecont = new Condition();
			schemecont.addExpression("id", schemeids, Operator.IN);
			List<Scheme> schemelist = daoex.find(Scheme.class, schemecont, null);
			// schemeObj = schemelist.stream().collect(Collectors.toMap(Scheme::getId,
			// Scheme-> Scheme));
			schemeObj = ListHelper.toMap(schemelist, "getId");
		}
		// Map<String, List<String>> staffofscheme = beenEva.stream()
		// .collect(Collectors.groupingBy(EvaObject :: getStaffid,
		// Collectors.mapping(EvaObject :: getSchemeid, Collectors.toList())));
		Map<String, List<String>> staffofscheme = ListHelper.groupingBy(beenEva, "getStaffid", "getSchemeid");
		Set<String> has_staffids = staffofscheme.keySet();
		for (PmStaff psn : stafflist) {
			if(has_staffids.contains(psn.id)){
				psn.define1 = true;
				String schemenames = "";
				for(String schemeid : staffofscheme.get(psn.id)){
					schemenames = schemenames+","+schemeObj.get(schemeid).getSchemename();
				}
				psn.define2 = schemenames.substring(1, schemenames.length());
				psn.define3 = staffofscheme.get(psn.id);
			} else {
				psn.define1 = false;
				psn.define2 = "";
				psn.define3 = "";
			}
		}

		return stafflist;
	}

	@Override
	public List<SchemeRelation> querySchemeRelationList(Condition cond,Sorter sorter) {
		return daoex.find(SchemeRelation.class,cond,sorter);
	}

    @Override
	public HashMap<String,Object> checkEvaBeenSummary(String schemeid) {
		HashMap<String,Object> resultmap = new HashMap<String,Object>();
		Scheme sumscheme = daoex.load(Scheme.class, schemeid);
		Condition evacont = new Condition();
		evacont.addExpression("schemeid", sumscheme.getId() );
		List<EvaObject> objectList = daoex.find(EvaObject.class, evacont, null);
		if(objectList.size() <= 0){
			resultmap.put("errorCode", 1);
			resultmap.put("message", "请设置考核对象");
		} else {
			// List<String> evastaffid =
			// objectList.stream().map(EvaObject::getStaffid).distinct().collect(Collectors.toList());
			List<String> evastaffid = ListHelper.collect(objectList, "getStaffid");
			List<String> evaBeenStaffid = groupSrv.getEvaobjBeenAggregated(sumscheme, evastaffid);
			if(evaBeenStaffid.size() > 0){
				// Map<String, List<String>> groupmapstaffid = objectList.stream().filter(obj ->
				// evaBeenStaffid.contains(obj.getStaffid()))
				// .collect(Collectors.groupingBy(EvaObject::getGroupid,
				// Collectors.mapping(EvaObject::getStaffid,Collectors.toList())));
				List<EvaObject> objectListTmp = new ArrayList<>();
				for (EvaObject item : objectList) {
					if (evaBeenStaffid.contains(item.getStaffid()))
						objectListTmp.add(item);
				}
				Map<String, List<String>> groupmapstaffid = ListHelper.groupingBy(objectListTmp, "getGroupid",
						"getStaffid");
				//查询考核方案组
				// List<String> groupids =
				// groupmapstaffid.keySet().stream().collect(Collectors.toList());
				List<String> groupids = new ArrayList<>(groupmapstaffid.keySet());
				Condition groupcont = new Condition();
				groupcont.addExpression("schemeid", sumscheme.getId() );
				groupcont.addExpression("id", groupids, Operator.IN );
				List<EvaGroup> groupList = daoex.find(EvaGroup.class, groupcont, null);

				Map<String, PmStaff> staffList = StaffHelper.queryStaffByIds(evaBeenStaffid);

				List<String> resultlist = new ArrayList<String>();
				for(EvaGroup group : groupList){
					String message = group.getGroupname() + ": ";
					List<String> list = groupmapstaffid.get(group.getId());
					for(String staffid : list){
						if(staffList.get(staffid) != null){
							message += staffList.get(staffid).name+"," ;
						}
					}
					message = message.substring(0, message.length()-1);//截取最后一个
					resultlist.add(message);
				}
				resultmap.put("errorCode", 2);
				resultmap.put("message", resultlist);
			}
		}
		return resultmap;
	}

	@Override
	public Map<String, Integer> querySummaryStatistics(String periodcode) {
		Map<String, Integer> sumMap = new LinkedHashMap<>();
		// 已有汇总方案人数：对应绩效期间下，有多少人已经存在于汇总方案中；
		Condition condObj = new Condition();
		condObj.addExpression("schememode", CommonValue.EnumSchemeMode.pm_sum.getIndex());
		condObj.addExpression("periodcode", periodcode);
		condObj.addExpression("tenantid", AppContext.getContext().getScope());
		OrgHelper.setOrgCondition(condObj, CommonValue.EnumServiceCode.SCHEME.getCode());
		sumMap.put("existpsn", queryExistPsn(condObj));
		// 汇总方案个数：统计对应绩效期间下，共有多少个汇总方案；
		sumMap.put("existsummaryscheme", queryExistSummaryScheme(condObj));
		/*
		 * 无汇总方案人数：存在基础考核方案中，但尚无所属的汇总方案的人员个数。举例如下：
		 * 2018年共有四次考核，2018年1季度、2018年2季度、2018年3季度、2018年4季度各有一个基础考核方案，包含的人数并集为50人。
		 * 则2018年度，总人数为50人，其中有20人已经有了汇总方案，则无汇总方案的为30人；
		 * 2018年上半年，总人数含2018年1季度和2018年2季度，共25人。其中有15人已经有了汇总方案，则无汇总方案的为10人。
		 */
		Condition condObj2 = new Condition();
		condObj2.addExpression("schememode", CommonValue.EnumSchemeMode.pm_pbc.getIndex());
		condObj2.addExpression("periodcode", periodcode, Operator.LIKESTART);
		condObj2.addExpression("tenantid", AppContext.getContext().getScope());
		OrgHelper.setOrgCondition(condObj2, CommonValue.EnumServiceCode.SCHEME.getCode());
		sumMap.put("nosummaryscheme", queryNoSummarySchemePsn(condObj2, condObj));
		// 基础考核方案个数：尚无所属汇总方案的这些员工，分布在几个已存在的基础考核方案中。
		sumMap.put("scheme", queryNoPsnInScheme(condObj2, condObj));
		return sumMap;
	}

	@Override
	public List<PmStaff> queryNoSummaryStaff(String periodcode) {
		Condition condObj = new Condition();
		condObj.addExpression("schememode", CommonValue.EnumSchemeMode.pm_sum.getIndex());
		condObj.addExpression("periodcode", periodcode);
		condObj.addExpression("tenantid", AppContext.getContext().getScope());
		OrgHelper.setOrgCondition(condObj, CommonValue.EnumServiceCode.SCHEME.getCode());
		Condition condObj2 = new Condition();
		condObj2.addExpression("schememode", CommonValue.EnumSchemeMode.pm_pbc.getIndex());
		condObj2.addExpression("periodcode", periodcode, Operator.LIKESTART);
		condObj2.addExpression("tenantid", AppContext.getContext().getScope());
		OrgHelper.setOrgCondition(condObj2, CommonValue.EnumServiceCode.SCHEME.getCode());

		List<PmStaff> staffList = new ArrayList<>();
		List<String> staffids = sumdao.queryNoSummaryStaff(condObj2, condObj);
		if (!staffids.isEmpty()) {
			Map<String, PmStaff> staffMap = StaffHelper.queryStaffByIds(staffids);
			staffList = StaffHelper.convertStaffMapToList(staffMap);
		}
		return staffList;
	}

	/**
	 * 删除已经存在汇总方案的其他方案人员;并将删除信息返回给pbc。
	 * @param sumschemeid
	 */
	@Override
	public List<Map<String,String>> dealingExistSumschemesByCore(String sumschemeid){
		List<EvaObject> evaobjlist = groupSrv.getBasedOnExistingSumschemes(sumschemeid);
		List<Map<String,String>> othermember = new ArrayList<Map<String,String>>();
	   	for (EvaObject evaobject : evaobjlist) {
	   		HashMap<String,String> sheetinfo = new HashMap<String,String>(); // 封装范围数据，需要什么就put什么。
	   		sheetinfo.put("schemeid", evaobject.getSchemeid());
	   		sheetinfo.put("staffid", evaobject.getStaffid());
	   		String objectid = evaobject.getId();
            String sheetid = groupSrv.querySheetidByEvaObject(objectid);
    		daoex.delete(EvaObject.class, objectid);//// 删除考核对象，
    		if (sheetid != null) {
    			sheetinfo.put("sheetid", sheetid);
    			//sheetSrv.deleteSheetAll(sheetid);
    			//删除全部和量表有关的数据
    			sumdao.deleteExistSumschemeSheet(sheetid);
    		}
    		othermember.add(sheetinfo);
        }
	   	return othermember;
	}

	private int queryExistPsn(Condition condObj) {
		int ret = sumdao.queryExistPsn(condObj);
		return ret;
	}

	private int queryExistSummaryScheme(Condition condObj) {
		int ret = sumdao.queryExistSummaryScheme(condObj);
		return ret;
	}

	private int queryNoSummarySchemePsn(Condition condObj1, Condition condObj2) {
		int ret = sumdao.queryNoSummarySchemePsn(condObj1, condObj2);
		return ret;
	}

	private int queryNoPsnInScheme(Condition condObj1, Condition condObj2) {
		int ret = sumdao.queryNoPsnInScheme(condObj1, condObj2);
		return ret;
	}
}
