package nc.impl.hrcm.contopinion;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.NCLocator;
import nc.bs.logging.Logger;
import nc.bs.uif2.validation.ValidationException;
import nc.bs.uif2.validation.ValidationFailure;
import nc.hr.frame.persistence.HrBaseServiceImpl;
import nc.hr.frame.persistence.SimpleDocServiceTemplate;
import nc.hr.utils.HRCMTermUnitUtils;
import nc.hr.utils.InSQLCreator;
import nc.hr.utils.MultiLangHelper;
import nc.hr.utils.PubEnv;
import nc.hr.utils.ResHelper;
import nc.itf.hi.IPsndocQryService;
import nc.itf.hr.frame.IPersistenceRetrieve;
import nc.itf.hr.hrss.IURLGenerator;
import nc.itf.hr.managescope.ManagescopeFacade;
import nc.itf.hr.message.IHRMessageSend;
import nc.itf.hrcm.IContopinionManageService;
import nc.itf.hrcm.IContopinionQueryService;
import nc.itf.uap.rbac.IUserManageQuery;
import nc.pub.tools.HRCMBusilogUtil;
import nc.pub.tools.HRCMCommonValue;
import nc.pubitf.rbac.IUserPubService;
import nc.vo.bd.meta.BatchOperateVO;
import nc.vo.hi.psndoc.PsnJobVO;
import nc.vo.hi.psndoc.PsndocAggVO;
import nc.vo.hi.psndoc.PsndocVO;
import nc.vo.hr.managescope.ManagescopeBusiregionEnum;
import nc.vo.hr.message.HRBusiMessageVO;
import nc.vo.hrcm.contopinion.ContopinionVO;
import nc.vo.hrcm.share.PsnSelListVO;
import nc.vo.ml.LanguageVO;
import nc.vo.ml.MultiLangContext;
import nc.vo.om.hrdept.HRDeptVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.VOStatus;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.pub.lang.UFLiteralDate;
import nc.vo.sm.UserVO;
import nc.vo.sm.enumfactory.UserIdentityTypeEnumFactory;
import nc.vo.uif2.LoginContext;
import nc.vo.util.BDVersionValidationUtil;
import nccloud.commons.lang.ArrayUtils;
import nccloud.commons.lang.StringUtils;

/**
 * 批量维护 Service实现
 * 
 * @author fengwei
 */
public class ContopinionManageServiceImpl extends HrBaseServiceImpl<ContopinionVO> implements IContopinionManageService
{

	private BaseDAO	baseDAO;

	private BaseDAO getBaseDAO()
	{
		if (null == baseDAO)
		{
			baseDAO = new BaseDAO();
		}
		return baseDAO;
	}

	private final String				DOC_NAME	= "hrcm_contopinion";

	private SimpleDocServiceTemplate	serviceTemplate;

	private SimpleDocServiceTemplate getServiceTemplate()
	{
		if (null == serviceTemplate)
		{
			serviceTemplate = new SimpleDocServiceTemplate(DOC_NAME);
		}
		return serviceTemplate;
	}

	public ContopinionManageServiceImpl()
	{
		super("60e4471d-f208-4407-bdf7-682247ed0068");
	}

	@Override
	public ContopinionVO[] batchSave(ContopinionVO[] vos) throws BusinessException {
		if(vos == null || vos.length == 0){
			return null;
		}
		//待修改的数据
		List<ContopinionVO> updList = new ArrayList<ContopinionVO>();
		//待删除的数据
		List<ContopinionVO> delList = new ArrayList<ContopinionVO>();
		for(ContopinionVO vo : vos){
			if(vo.getStatus() == VOStatus.DELETED){
				delList.add(vo);
			}else{
				updList.add(vo);
			}
		}
		if(delList != null && !delList.isEmpty()){
			deleteValidate(delList);
			delete(delList.toArray(new ContopinionVO[0]));
		}
		if(updList != null && !updList.isEmpty()){
			BatchOperateVO batchVO = new BatchOperateVO();
			batchVO.setUpdObjs(updList.toArray());
			BatchOperateVO returnObj = batchSave(batchVO, ContopinionVO.class);
			return (ContopinionVO[]) returnObj.getUpdObjs();
		}
		return null;
	}
	
	/**
	 * 合同删除校验
	 * @author tianxfc
	 * @param vos
	 * @throws ValidationException
	 * @exception 异常描述
	 */
	public void deleteValidate(List<ContopinionVO> delList) throws ValidationException{
		
		List<ValidationFailure> failures = new ArrayList<ValidationFailure>();
		for(ContopinionVO vo : delList){
			int conttype = vo.getConttype();  //处理结果: 0=未征询，1=未反馈，2=反馈中，3=已反馈，4=已续签，5=已终止
			if (HRCMCommonValue.STATE_NOCONSULT != conttype && HRCMCommonValue.STATE_NOFEEDBACK != conttype){
				failures.add(new ValidationFailure(ResHelper.getString("6011opin", "06011opin0024")/* @res"只能删除状态为“未征询”和“未反馈”的征询记录！" */));
				break;
			}
		}
		if (!failures.isEmpty()){
			throw new ValidationException(failures);
		}
	}

	@Override
	public HashMap<String, Object> sendNoticeToDeptManager(Map<String, List<String>> psndeptMap, Map<String, List<ContopinionVO>> contopMap,
			String pk_group, String pk_org, ContopinionVO[] vos,ArrayList<ContopinionVO> inFeedbackList) throws BusinessException {
		if(!ArrayUtils.isEmpty(vos)){
			//时间戳校验
			BDVersionValidationUtil.validateSuperVO(vos);
		}
		int icntsucc = 0;
		IHRMessageSend messageSendService = NCLocator.getInstance().lookup(IHRMessageSend.class);
		/**给部门负责人发送消息*/
		if(!ArrayUtils.isEmpty(vos)){
			Set<String> keySet = psndeptMap.keySet();
			Iterator<String> it = keySet.iterator();
			while (it.hasNext()) {
				String pk_dept = it.next();// 部门主键
				List<String> pk_psndocs = psndeptMap.get(pk_dept);// 部门内要续签的人员
				List<ContopinionVO> opinionVOList = contopMap.get(pk_dept);// 部门内要续签人员的征询意见VO。
				
				// 续签人员列表
				String employeeList = "";
				InSQLCreator creator = new InSQLCreator();
				
				String inSQL = creator.getInSQL(pk_psndocs.toArray(new String[pk_psndocs.size()]));
				ContopinionDAO dao = new ContopinionDAO();
				List<String> nameList = dao.getPsnnameByPkjob(inSQL);
				for (String name : nameList) {
					employeeList += name + ", ";
				}
				
				if (!StringUtils.isBlank(employeeList)) {
					employeeList = employeeList.substring(0, employeeList.length() - 2);
				}
				
				// 得到URL
				//String url = getURL(pk_dept, opinionVOList);
//				String url = SysinitAccessor.getInstance().getParaString(IOrgConst.GLOBEORG, "HR0002");
//				if (StringUtils.isBlank(url)) {
//					url = "";
//				}
				//url += "/nccloud/resources/hrcm/contractmgt/contopinion/main/index.html?appcode=60110313";
				//url = "<a target='balck' href ='/nccloud/resources/hrcm/contractmgt/contopinion/main/index.html?appcode=60110313'>/nccloud/resources/hrcm/contractmgt/contopinion/main/index.html</a>";
				String url = "请前往移动端【续签意见征询-经理】节点处理";
				// 组织消息VO
				HRBusiMessageVO messageInfoVO = new HRBusiMessageVO();
				messageInfoVO.setBillVO(opinionVOList.get(0));// 关联元数据实体VO
				messageInfoVO.setMsgrescode(HRCMCommonValue.DEPT_MSGTEMP_CODE);// 消息源编码
				Hashtable<String, Object> transferValues = new Hashtable<String, Object>();
				transferValues.put(HRCMCommonValue.EMPLOYEELIST, employeeList);
				transferValues.put(HRCMCommonValue.URL, url);
				messageInfoVO.setBusiVarValues(transferValues);// 业务函数值
				messageInfoVO.setPkorgs(new String[] { opinionVOList.get(0).getPk_org() });
				
				setReciverInfo(messageInfoVO, pk_dept);
				//征询意见-记录日志
				HRCMBusilogUtil.writeContopinion(vos,"Contopin");
				// 发送消息
				//messageSendService.sendBuziMessage_RequiresNew(messageInfoVO, new String[] { getUserContentLangCode(PubEnv.getPk_user()) });
				messageSendService.sendBuziMessage_RequiresNew(messageInfoVO);
				icntsucc++;
			}
			
			for(ContopinionVO vo : vos){
				vo.setConttype(HRCMCommonValue.STATE_NOFEEDBACK);// 修改状态为未反馈
				vo.setOpdate(PubEnv.getServerTime());// 征询时间为当前时间
				vo.setIssendsuccess(UFBoolean.TRUE);
			}
			// 更新修改状态
			vos = NCLocator.getInstance().lookup(IContopinionManageService.class).updateArray(vos);
		}

		/**如果需要发送催办消息的vo list 不为空  员工消息暂时不能发送*/
		if(!inFeedbackList.isEmpty()){
			int succ = sendMessageToEmp(inFeedbackList, pk_org, messageSendService);
			icntsucc += succ;
		}
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("cnt", icntsucc);
		return map;
	}
	
	private String getUserContentLangCode(String userPk) throws BusinessException {
		UserVO[] users = NCLocator.getInstance().lookup(IUserPubService.class).getUsersByPKs(new String[] { userPk });
		if (ArrayUtils.isEmpty(users))
			return null;
		UserVO user = users[0];
		String pk_langcode = user.getContentlang();
		LanguageVO[] all = getAllEnabledLangVO();
		if (ArrayUtils.isEmpty(all))
			return null;
		for (LanguageVO languageVO : all) {
			if (languageVO.getPk_multilang().equals(pk_langcode))
				return languageVO.getLangcode();
		}
		return null;

	}

	private static LanguageVO[] getAllEnabledLangVO() {
		LanguageVO[] langvos = MultiLangContext.getInstance().getEnableLangVOs();
		if (ArrayUtils.isEmpty(langvos))
			return null;
		return langvos;
	}
	
	/**
	 * 给员工发送征询催办消息
	 * 2019-09-02 下午02:07:30
	 * tianxfc
	 * @param inFeedbackList
	 * @param pk_org
	 * @param messageSendService
	 * @return
	 * @throws BusinessException
	 */
	@SuppressWarnings("rawtypes")
	private int sendMessageToEmp(ArrayList<ContopinionVO> inFeedbackList, String pk_org, IHRMessageSend messageSendService) throws BusinessException{
		/**征询意见的工作记录主键*/
		String[] psnjobPks = new String[inFeedbackList.size()];
		for(int i=0; i<psnjobPks.length; i++){
			psnjobPks[i] = inFeedbackList.get(i).getPk_psnjob();
		}
		/**查询每个工作记录主键所对应的aggVO*/
		IPsndocQryService is = NCLocator.getInstance().lookup(IPsndocQryService.class);
		PsndocAggVO[] psnaggVos = is.queryPsndocVOByPks(psnjobPks);
		/**工作记录主键为KEY，aggVO为VALUE*/
		HashMap<String,PsndocAggVO> psnMap = new HashMap<String, PsndocAggVO>();
		/**K:pk_psndoc, V:pk_psnjob*/
		HashMap<String,String> psndocPkMap = new HashMap<String, String>();
		for (PsndocAggVO vo : psnaggVos) {// 缓存人员信息
			String psndocPk = vo.getParentVO().getPk_psndoc();
			String psnjobPk = vo.getParentVO().getPsnJobVO().getPk_psnjob();
			psnMap.put(psnjobPk, vo);
			psndocPkMap.put(psndocPk, psnjobPk);
		}
		/**人员主键*/
		String[] psndocPks = new String[psnaggVos.length];
		for (int i = 0; i < psnaggVos.length; i++) {
			psndocPks[i] = psnaggVos[i].getParentVO().getPk_psndoc();
		}
		
		InSQLCreator isc1 = new InSQLCreator();
		String docInSql = isc1.getInSQL(psndocPks);
		String userCondition = " pk_base_doc in ("+docInSql+") and base_doc_type = " + UserIdentityTypeEnumFactory.TYPE_PERSON + " ";
		/**自助用户*/
		UserVO[] uservos = (UserVO[]) NCLocator.getInstance().lookup(IPersistenceRetrieve.class).retrieveByClause(null, UserVO.class, userCondition);
		/**K：工作记录主键，V：UserVO的Cuserid*/
		HashMap<String,String> userMap = new HashMap<String, String>();
		if(ArrayUtils.isEmpty(uservos)){
			throw new BusinessException(ResHelper.getString("6011opin", "06011opin0064")/*"当前员工未设置自助用户不能发送催办消息"*/);
		}
		for(int i=0; i<uservos.length; i++){
			String pk_psndoc = uservos[i].getPk_base_doc();
			String psnjobPk = psndocPkMap.get(pk_psndoc);
			userMap.put(psnjobPk, uservos[i].getCuserid());
		}
		int icntsucc = 0;
		//组装消息VO
		for (Iterator iterator = inFeedbackList.iterator(); iterator.hasNext();) {
			ContopinionVO contopinionVO = (ContopinionVO) iterator.next();
			HRBusiMessageVO messageInfoVO = new HRBusiMessageVO();
			messageInfoVO.setMsgrescode(HRCMCommonValue.EMPLOYEE_MSGTEMP_CODE);// 消息源编码
			messageInfoVO.setPkorgs(new String[] { pk_org });
			setReciverInfoForEmp(messageInfoVO, contopinionVO, psnMap, userMap);
			// 发送消息
			messageSendService.sendBuziMessage_RequiresNew(messageInfoVO);
			icntsucc++;
		}
		return icntsucc;
	}
	
	private void setReciverInfoForEmp(HRBusiMessageVO messageInfoVO,ContopinionVO contopinionVO,HashMap<String,PsndocAggVO> psnMap,HashMap<String,String> userMap) throws BusinessException{
		String psnjobPk = contopinionVO.getPk_psnjob();
		PsndocVO psndocVO = psnMap.get(psnjobPk).getParentVO();
		String[] emails = { psndocVO.getEmail() };
		String[] mobiles = { psndocVO.getMobile() };
		String userPk = userMap.get(psnjobPk);
		String[] userpks = { userPk };
		messageInfoVO.setReceiverEmails(emails);
		messageInfoVO.setReceiverMobiles(mobiles);
		messageInfoVO.setReceiverPkUsers(userpks);
		messageInfoVO.setBillVO(contopinionVO);// 关联元数据实体VO
		
		Hashtable<String, Object> transferValues = new Hashtable<String, Object>();
		String url = "请前往移动端【续签意见征询-员工】节点处理";
		transferValues.put(HRCMCommonValue.URL, url);
		messageInfoVO.setBusiVarValues(transferValues);// 业务函数值
		
//		//添加URL
//		SSOInfo ssinfo = new SSOInfo();
//		ssinfo.setUserPK(userPk);
//		UFDateTime ut = new UFDateTime();
//		ssinfo.setTtl(ut.getDateTimeAfter(30));
//		ssinfo.setLocation("/portal/app/MyContopinApp?nodecode=E20200704&pk_opinion=" + contopinionVO.getPk_opinion());
//		ssinfo.setWindowType(SSOInfo.WINDOW_TYPE_CURRENT);
//		IURLGenerator IurlDirect = OpinionHrssUtils.getUrlDirect();
//		if(IurlDirect!=null){			
//			Hashtable<String, Object> transferValues = new Hashtable<String, Object>();
//			transferValues.put(HRCMCommonValue.URL, IurlDirect.buildURLString(ssinfo));
//			messageInfoVO.setBusiVarValues(transferValues);// 业务函数值
//		}
	}
	
	private IURLGenerator getUrlDirect() {
		try {
//			return ServiceLocator.lookup(IURLGenerator.class);
			return null;
		} catch (Throwable e) {
			Logger.error(e.getMessage(), e);
		}
		return null;
	}
	
	private void setReciverInfo(HRBusiMessageVO messageInfoVO, String pk_dept) throws BusinessException{
		PsndocVO psndocVO = this.getDeptManager(pk_dept);
		String[] emails = { psndocVO.getEmail() };
		String[] mobiles = { psndocVO.getMobile() };
		messageInfoVO.setReceiverEmails(emails);
		messageInfoVO.setReceiverMobiles(mobiles);
		UserVO uservo = getUserManageQuery(psndocVO.getPk_psndoc());
		if(uservo != null){
			String[] userpks = { uservo.getCuserid() };
			messageInfoVO.setReceiverPkUsers(userpks);
		}
	}

	private UserVO getUserManageQuery(String pk_psndoc) throws BusinessException{
		return NCLocator.getInstance().lookup(IUserManageQuery.class).queryUserVOByPsnDocID(pk_psndoc);
	}

	private PsndocVO getDeptManager(String pk_dept) throws BusinessException{
		HRDeptVO deptVO = (HRDeptVO) NCLocator.getInstance().lookup(IPersistenceRetrieve.class).retrieveByPk(null, HRDeptVO.class, pk_dept);
		String pk_managerPk = deptVO.getPrincipal();
		PsndocVO psndocVO = (PsndocVO) NCLocator.getInstance().lookup(IPersistenceRetrieve.class).retrieveByPk(null, PsndocVO.class, pk_managerPk);
		return psndocVO;
	}

//	private String getURL(String pk_dept, List<ContopinionVO> opinionVOList) throws BusinessException
//	{
//		IContopinionQueryService queryService = NCLocator.getInstance().lookup(IContopinionQueryService.class);
//		HRDeptVO deptVO = queryService.queryDeptManagerByPK(pk_dept);// 得到部门负责人VO
//		// 部门负责人主键
//		String principal = deptVO.getPrincipal();
//		if (principal == null)
//		{
//			return null;
//		}
//
//		// 续签人员主键
//		String pk_opinionList = "";
//		for (ContopinionVO opinionVO : opinionVOList)
//		{
//			pk_opinionList += opinionVO.getPk_opinion() + ", ";
//		}
//		if (!StringUtils.isBlank(pk_opinionList))
//		{
//			pk_opinionList = pk_opinionList.substring(0, pk_opinionList.length() - 2);
//		}
//
//		// 得到部门负责人输信息
//		GeneralVO vo = queryService.getDeptManagerInfo(principal);
//
//		// 得到部门负责人对应的用户
//		String pk_psndoc = (String) vo.getAttributeValue("pk_psndoc");
//		UserVO user = NCLocator.getInstance().lookup(IUserManageQuery.class).queryUserVOByPsnDocID(pk_psndoc);
//
//		SSOInfo info = new SSOInfo();
//		info.setFuncode("E20400704");
//		if(user==null){	
//			throw new BusinessException(ResHelper.getString("6011opin", "06011opin0063")/*"当前人员的部门负责人未设置自助用户，不能发送通知"*/);
//		}
//		info.setUserPK(user.getCuserid());
//
//		UFDateTime ut = new UFDateTime();
//		info.setTtl(ut.getDateTimeAfter(30));
//		info.addParam("pk_opinion", pk_opinionList);
//		//String title = nc.vo.ml.NCLangRes4VoTransl.getNCLangRes().getStrByID("6011opin", "06011opin0052")/* @res "员工续签意见征询" */;
//		//String url = NCLocator.getInstance().lookup(IURLGenerator.class).buildHTML(info, title);
//		String url = NCLocator.getInstance().lookup(IURLGenerator.class).buildURLString(info);
//
//		return url;
//	}

	@Override
	public ContopinionVO[] updateArray(ContopinionVO[] vos) throws BusinessException
	{
		getBaseDAO().updateVOArray(vos);
		/*
		 * @hujr 添加 记录日志文件
		 * 2015年10月9日14:45:17
		 */
		//记录日志
        HRCMBusilogUtil.writeContopinion(vos,"Contopin");
		return (ContopinionVO[]) NCLocator.getInstance().lookup(IPersistenceRetrieve.class)
				.retrieveByClause(null, ContopinionVO.class, " pk_opinion in (" + new InSQLCreator().getInSQL(vos, ContopinionVO.PK_OPINION) + ")");
	}

	@Override
	public void delete(ContopinionVO[] vos) throws BusinessException
	{
		//记录日志
		HRCMBusilogUtil.writeContopinion(vos,"delete");
		
		getBaseDAO().deleteVOArray(vos);
	}

	/**
	 * 根据部门主键，判断部门是否有负责人
	 * 
	 * @author fengwei on 2011-1-25
	 * @param pk_dept
	 * @return
	 * @exception 异常描述
	 * @see 需要参见的其它内容
	 * @since 从类的V60版本，此方法被添加进来。（可选）
	 */
	public boolean hasDeptManager(String pk_dept)
	{
		if (pk_dept != null)
		{
			try
			{
				HRDeptVO deptVO = NCLocator.getInstance().lookup(IContopinionQueryService.class).queryDeptManagerByPK(pk_dept);
				if (null == deptVO.getPrincipal())
				{
					return false;
				}
			}
			catch (BusinessException e)
			{
				Logger.error(e.getMessage());
			}
		}
		return true;
	}

	private Map<String, String> getPkpsnjob(PsnSelListVO[] psnSelListVOs) throws BusinessException
	{
		Map<String, String> pkjobMap = new HashMap<String, String>();
		List<String> psndocList = new ArrayList<String>();
		for (int i = 0; i < psnSelListVOs.length; i++)
		{
			psndocList.add(psnSelListVOs[i].getPk_psndoc());
		}

		InSQLCreator isc = new InSQLCreator();

		String insql = isc.getInSQL(psndocList.toArray(new String[0]));
		String condition = " pk_psndoc in (" + insql + ") and lastflag = 'Y' and ismainjob = 'Y' and endflag = 'N'";
		PsnJobVO[] psnjobVOs = getServiceTemplate().queryByCondition(PsnJobVO.class, condition);
		if (!ArrayUtils.isEmpty(psnjobVOs))
		{
			for (int i = 0; i < psnjobVOs.length; i++)
			{
				String pk_psndoc = psnjobVOs[i].getPk_psndoc();
				pkjobMap.put(pk_psndoc, psnjobVOs[i].getPk_psnjob());
				psndocList.remove(pk_psndoc);
			}
		}

		if (!psndocList.isEmpty())
		{
			String psndocSql = isc.getInSQL(psndocList.toArray(new String[0]));
			String cond = " pk_psndoc in (" + psndocSql + ")";
			//PsndocVO[] psndocVOs = getServiceTemplate().queryByCondition(PsndocVO.class, cond);
			PsndocVO[] psndocVOs = (PsndocVO[]) NCLocator.getInstance().lookup(IPersistenceRetrieve.class).retrieveByClause(null, PsndocVO.class, cond);
			StringBuffer nameBuf = new StringBuffer();
			for (int i = 0; i < psndocVOs.length; i++)
			{
				PsndocVO psndocVO = psndocVOs[i];
				nameBuf.append(",").append(MultiLangHelper.getName(psndocVO));
			}
			String psnNames = nameBuf.toString().substring(1);
			if (!StringUtils.isEmpty(psnNames))
			{
				throw new BusinessException(ResHelper.getString("6011opin", "06011opin0053", psnNames)/* @res "[{0}]是已离职人员,不能进续签意见征询！" */);
			}
		}

		return pkjobMap;
	}

	/**
	 * 得到业务委托人员过滤sql
	 * 
	 * @return
	 * @throws BusinessException
	 * @throws BusinessException
	 */
	@SuppressWarnings("unused")
	private String getYwwt(String pk_org) throws BusinessException
	{
		String ywwtsql;
		// 当前组织人员
		HashMap<String, String> orgPkToYwwtSqlMap = new HashMap<String, String>();
		ywwtsql = orgPkToYwwtSqlMap.get(pk_org);
		if (ywwtsql == null)
		{
			// ywwtsql =
			// ManagescopeFacade.queryPsnjobPksSQLByHrorgAndBusiregion(
			// pk_org, ManagescopeBusiregionEnum.psndoc);
			ywwtsql = ManagescopeFacade.queryPkOrgsSQLByHrorgAndBusiregion(pk_org, ManagescopeBusiregionEnum.psndoc, false);
			// orgPkToYwwtSqlMap.put(pk_org, ywwtsql);
			orgPkToYwwtSqlMap.put(pk_org, ywwtsql);
		}
		return ywwtsql;
	}

	@Override
	public ContopinionVO[] insertContOpVO(PsnSelListVO[] psnVOs, String remenddate, String remmonth, String pk_psndoc_sub, String termtype,
			Integer termUnit, LoginContext context) throws BusinessException
	{
		String[] remenddates = null;
		String[] remmonths = null;
		if (remenddate != null)
		{
			remenddates = remenddate.split("_");
			remmonths = remmonth.split("_");
		}

		String[] pk_psndoc_subs = null;
		if (pk_psndoc_sub != null)
		{
			pk_psndoc_subs = pk_psndoc_sub.split("_");
		}

		Map<String, String> map = getPkpsnjob(psnVOs);
		ContopinionVO[] contopinionVOs = new ContopinionVO[pk_psndoc_subs.length];
		for (int i = 0; i < pk_psndoc_subs.length; i++)
		{
			for (int j = 0; j < psnVOs.length; j++)
			{
				if (!psnVOs[j].getPk_psndoc_sub().equals(pk_psndoc_subs[i]))
				{
					continue;
				}
				ContopinionVO vo = new ContopinionVO();
				vo.setPk_psndoc_sub(pk_psndoc_subs[i]);
				vo.setTermtype(termtype);
				vo.setContopinion_unit(termUnit);
				if (HRCMTermUnitUtils.TERM_TYPE_NONFIXED.equals(termtype) || HRCMTermUnitUtils.TERM_TYPE_TASK.equals(termtype))
				{
					vo.setSedenddate(null);
					vo.setItermmonth(null);
				}
				else
				{
					vo.setSedenddate(remenddates[i] == null ? null : new UFLiteralDate(remenddates[i]));
					vo.setItermmonth(remmonths[i].equals("null") ? null : new Integer(remmonths[i]));

				}
				vo.setConttype(HRCMCommonValue.STATE_NOCONSULT);
				vo.setDeptopinion(null);
				vo.setDeptdirection(null);
				vo.setHropinion(null);
				vo.setPk_psnjob(map.get(psnVOs[i].getPk_psndoc()));
				vo.setPk_org(context.getPk_org());
				vo.setPk_group(context.getPk_group());
				vo.setOpdate(PubEnv.getServerTime());
				vo.setCreator(context.getPk_loginUser());
				vo.setCreationtime(PubEnv.getServerTime());
				contopinionVOs[i] = vo;
			}
		}
		String[] pks = new ContopinionDAO().insertContopVOs(contopinionVOs);
		/**modify start:记录合同续签意见征询增加业务日志 yunana 2013-06-08*/	
		HRCMBusilogUtil.writeContopinionAdd(contopinionVOs);
		/**modify end:yunana 2013-06-08*/
		InSQLCreator isc = new InSQLCreator();
		return (ContopinionVO[]) NCLocator.getInstance().lookup(IPersistenceRetrieve.class)
				.retrieveByClause(null, ContopinionVO.class, " pk_opinion in (" + isc.getInSQL(pks) + ")");
	}

	

	
	@Override
	public HashMap<String, Object> getPsnjobDeptMap(ContopinionVO[] contopinionVOs) throws BusinessException
	{
		PsnJobVO[] job = (PsnJobVO[]) NCLocator
				.getInstance()
				.lookup(IPersistenceRetrieve.class)
				.retrieveByClause(null, PsnJobVO.class,
						" pk_psnjob in (" + new InSQLCreator().getInSQL(contopinionVOs, ContopinionVO.PK_PSNJOB) + ")");
		HashMap<String, String> map = new HashMap<String, String>();
		for (int i = 0; job != null && i < job.length; i++)
		{
			map.put(job[i].getPk_psnjob(), job[i].getPk_dept());
		}

		for (int i = 0; i < contopinionVOs.length; i++)
		{
			String pk_dept = map.get(contopinionVOs[i].getPk_psnjob());
			if (StringUtils.isBlank(pk_dept))
			{
				continue;
			}
			contopinionVOs[i].setPk_dept(pk_dept);
		}

		ArrayList<String> temp = new ArrayList<String>();// 部门id集合
		for (ContopinionVO vo : contopinionVOs)
		{
			String pk_dept = vo.getPk_dept();
			if (!temp.contains(pk_dept))
			{
				temp.add(pk_dept);
			}
		}
		
		/**拥有部门负责人的部门的主键*/
		String[] deptPKs = getDeptHasPrincipal(temp.toArray(new String[0]));
		HashMap<String, Object> result = new HashMap<String, Object>();
		// 如果不存在部门没有负责人的情况，则提示用户是否继续进行操作
		String msg = ResHelper.getString("6011opin", "06011opin0009")/* @res "即将向您所选人员的部门负责人发送通知，征询部门续签意见，确认发送吗？" */;
		// 如果所有人员的所属部门都没有部门负责人，直接返回null
		if (deptPKs == null || deptPKs.length == 0)
		{
			/* @res "您选中的人员的所属部门没有维护部门负责人,请维护部门负责人后再发送征询通知！" */
			msg = ResHelper.getString("6011opin", "06011opin0019");
			//throw new BusinessException(ResHelper.getString("6011opin", "06011opin0019"));
			result.put("vos", null);
			result.put("pks", null);
			result.put("msg", msg);
			return result;
		}
		
		ArrayList<String> deptPkList = new ArrayList<String>();
		for(int i=0; i<deptPKs.length;i++){
			deptPkList.add(deptPKs[i]);
		}
		/**所在部门有负责人的征询意见*/
		ArrayList<ContopinionVO> opinVOhasPrincipalList = new ArrayList<ContopinionVO>();
		for(int i=0; i<contopinionVOs.length;i++){
			if(!StringUtils.isEmpty(contopinionVOs[i].getPk_dept()) && deptPkList.contains(contopinionVOs[i].getPk_dept())){
				opinVOhasPrincipalList.add(contopinionVOs[i]);
			}
		}

		if (deptPKs.length < temp.size())
		{
			msg = ResHelper.getString("6011opin", "06011opin0020")/* @res"您选中的部分人员的所属部门没有维护部门负责人,系统将给符合条件人员的部门负责人发送征询通知！" */;
		}

		result.put("vos", opinVOhasPrincipalList.toArray(new ContopinionVO[0]));
		result.put("pks", deptPKs);
		result.put("msg", msg);

		return result;
	}

	@Override
	public String[] getDeptHasPrincipal(String[] deptPKs) throws BusinessException
	{
		if (deptPKs == null || deptPKs.length == 0)
		{
			return null;
		}
		HRDeptVO[] dept = (HRDeptVO[]) NCLocator.getInstance().lookup(IPersistenceRetrieve.class)
				.retrieveByClause(null, HRDeptVO.class, " pk_dept in (" + new InSQLCreator().getInSQL(deptPKs) + ") and principal <> '~' ");

		if (dept == null || dept.length == 0)
		{
			return null;
		}
		String[] result = new String[dept.length];
		for (int i = 0; i < dept.length; i++)
		{
			result[i] = dept[i].getPk_dept();
		}
		return result;
	}

	@Override
	public HashMap<String, Object> sendNoticeToPsn(Map<String, List<String>> psndeptMap,
			Map<String, List<ContopinionVO>> contopMap, String pk_group, String pk_org, ContopinionVO[] vos,
			ArrayList<ContopinionVO> inFeedbackList) throws BusinessException {
		if(!ArrayUtils.isEmpty(vos)){
			//时间戳校验
			BDVersionValidationUtil.validateSuperVO(vos);
		}
		int icntsucc = 0;
		IHRMessageSend messageSendService = NCLocator.getInstance().lookup(IHRMessageSend.class);
		/** 员工消息发送*/
		int succ = sendMessageToEmpEx(inFeedbackList, pk_org, messageSendService);
		icntsucc += succ;
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("cnt", icntsucc);
		return map;
	}
	
	/**
	 * 给员工发送征询催办消息
	 * 2019-09-02 下午02:07:30
	 * tianxfc
	 * @param inFeedbackList
	 * @param pk_org
	 * @param messageSendService
	 * @return
	 * @throws BusinessException
	 */
	@SuppressWarnings("rawtypes")
	private int sendMessageToEmpEx(ArrayList<ContopinionVO> inFeedbackList, String pk_org, IHRMessageSend messageSendService) throws BusinessException{
		/**征询意见的工作记录主键*/
		String[] psnjobPks = new String[inFeedbackList.size()];
		for(int i=0; i<psnjobPks.length; i++){
			psnjobPks[i] = inFeedbackList.get(i).getPk_psnjob();
		}
		/**查询每个工作记录主键所对应的aggVO*/
		IPsndocQryService is = NCLocator.getInstance().lookup(IPsndocQryService.class);
		PsndocAggVO[] psnaggVos = is.queryPsndocVOByPks(psnjobPks);
		/**工作记录主键为KEY，aggVO为VALUE*/
		HashMap<String,PsndocAggVO> psnMap = new HashMap<String, PsndocAggVO>();
		/**K:pk_psndoc, V:pk_psnjob*/
		HashMap<String,String> psndocPkMap = new HashMap<String, String>();
		for (PsndocAggVO vo : psnaggVos) {// 缓存人员信息
			String psndocPk = vo.getParentVO().getPk_psndoc();
			String psnjobPk = vo.getParentVO().getPsnJobVO().getPk_psnjob();
			psnMap.put(psnjobPk, vo);
			psndocPkMap.put(psndocPk, psnjobPk);
		}
		/**人员主键*/
		String[] psndocPks = new String[psnaggVos.length];
		for (int i = 0; i < psnaggVos.length; i++) {
			psndocPks[i] = psnaggVos[i].getParentVO().getPk_psndoc();
		}
		
		InSQLCreator isc1 = new InSQLCreator();
		String docInSql = isc1.getInSQL(psndocPks);
		String userCondition = " pk_base_doc in ("+docInSql+") and base_doc_type = " + UserIdentityTypeEnumFactory.TYPE_PERSON + " ";
		/**自助用户*/
		UserVO[] uservos = (UserVO[]) NCLocator.getInstance().lookup(IPersistenceRetrieve.class).retrieveByClause(null, UserVO.class, userCondition);
		/**K：工作记录主键，V：UserVO的Cuserid*/
		HashMap<String,String> userMap = new HashMap<String, String>();
		if(ArrayUtils.isEmpty(uservos)){
			throw new BusinessException(ResHelper.getString("6011opin", "06011opin0064")/*"当前员工未设置自助用户不能发送催办消息"*/);
		}
		for(int i=0; i<uservos.length; i++){
			String pk_psndoc = uservos[i].getPk_base_doc();
			String psnjobPk = psndocPkMap.get(pk_psndoc);
			userMap.put(psnjobPk, uservos[i].getCuserid());
		}
		int icntsucc = 0;
		//组装消息VO
		for (Iterator iterator = inFeedbackList.iterator(); iterator.hasNext();) {
			ContopinionVO contopinionVO = (ContopinionVO) iterator.next();
			HRBusiMessageVO messageInfoVO = new HRBusiMessageVO();
			messageInfoVO.setMsgrescode(HRCMCommonValue.EMPLOYEE_MSGTEMP_CODE);// 消息源编码
			messageInfoVO.setPkorgs(new String[] { pk_org });
			setReciverInfoForEmpEx(messageInfoVO, contopinionVO, psnMap, userMap);
			// 发送消息
			messageSendService.sendBuziMessage_RequiresNew(messageInfoVO);
			icntsucc++;
		}
		return icntsucc;
	}
	
	private void setReciverInfoForEmpEx(HRBusiMessageVO messageInfoVO,ContopinionVO contopinionVO,HashMap<String,PsndocAggVO> psnMap,HashMap<String,String> userMap) throws BusinessException{
		String psnjobPk = contopinionVO.getPk_psnjob();
		PsndocVO psndocVO = psnMap.get(psnjobPk).getParentVO();
		String[] emails = { psndocVO.getEmail() };
		String[] mobiles = { psndocVO.getMobile() };
		String userPk = userMap.get(psnjobPk);
		String[] userpks = { userPk };
		messageInfoVO.setReceiverEmails(emails);
		messageInfoVO.setReceiverMobiles(mobiles);
		messageInfoVO.setReceiverPkUsers(userpks);
		messageInfoVO.setBillVO(contopinionVO);// 关联元数据实体VO
		
		Hashtable<String, Object> transferValues = new Hashtable<String, Object>();
		String url = "请前往移动端【续签意见征询-员工】节点处理";
		transferValues.put(HRCMCommonValue.URL, url);
		messageInfoVO.setBusiVarValues(transferValues);// 业务函数值
		
	}
}
