package ncc.pub.wywgpt.utils;

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

import com.alibaba.fastjson.JSONObject;

import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.logging.Logger;
import nc.bs.uap.tools.formula.ExtFormulaParser;
import nc.itf.sap.bill.IResponseBill;
import nc.itf.sap.log.ISapLog;
import nc.itf.sap.valid.ISapItfValid;
import nc.itf.uap.IUAPQueryBS;
import nc.itf.uap.pf.IPFBusiAction;
import nc.itf.uap.pf.IWorkflowMachine;
import nc.itf.uif.pub.IUifService;
import nc.itf.ws.esb.IEsbDAO;
import nc.jdbc.framework.SQLParameter;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.net.pu.utils.PubUtils;
import nc.pub.sap.constant.SapConstants;
import nc.pub.sap.sort.SapVOSort;
import nc.vo.esb.EsbInfoVO;
import nc.vo.esb.EsbVO;
import nc.vo.esb.QueryInfoVO;
import nc.vo.jcom.lang.StringUtil;
import nc.vo.pub.AggregatedValueObject;
import nc.vo.pub.BusinessException;
import nc.vo.pub.CircularlyAccessibleValueObject;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.pub.workflownote.WorkflownoteVO;
import nc.vo.pubapp.AppContext;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.sap.result.SAPResultVO;
import nc.vo.sap.syproconfig.SyProConfigBVO;
import nc.vo.wfengine.definition.WorkflowTypeEnum;
import nc.vo.wfengine.pub.WfTaskOrInstanceStatus;
import nc.vo.ws.esb.EsbinfoVO;
import nccloud.commons.collections.CollectionUtils;
import nccloud.commons.lang.ArrayUtils;
import nccloud.commons.lang.StringUtils;
import nccloud.framework.service.ServiceLocator;
/**
 * @Description: 公具类
 * 
 * @author 谢文如 【碧桂园SAP专项】
 * @date 2018-4-8
 * @version with NCC
 */
@SuppressWarnings("unchecked")
public class WyWGPTUtils {
	/**
	 * 查询公式
	 * @param code			表头编码
	 * @param direction		方向【SAP->NC ? NC->SAP】
	 * @return
	 * @throws BusinessException
	 */
	public static HashMap<String,ArrayList<String>> getFormulas(String code,int direction) throws BusinessException{
			StringBuffer sqlstr = new StringBuffer("");
			sqlstr.append("item = (select pk_head").append("\r\n");
			sqlstr.append("  from sap_syproconfig").append("\r\n");
			sqlstr.append(" where billno = '");
			sqlstr.append(code);
			sqlstr.append("'").append("\r\n");
			sqlstr.append("   and nvl(dr, 0) = 0) and nvl(dr, 0) = 0  and isenable_sn='Y' "); 
			List<SyProConfigBVO> syProConfigBVOs = (List<SyProConfigBVO>)getQueryBS().retrieveByClause(SyProConfigBVO.class, sqlstr.toString());
			if(syProConfigBVOs!=null && syProConfigBVOs.size()>0){
			HashMap<String,ArrayList<String>> formulasMap = new HashMap<String,ArrayList<String>>();
			//非空字段
			ArrayList<String> notNullField = new ArrayList<String>();
			//SAP->NC ？ NC->SAP 公式
			ArrayList<String> formula = new ArrayList<String>();
			//NC字段编码
			ArrayList<String> nc_field_code = new ArrayList<String>();
			//NC字段名称
			ArrayList<String> nc_field_name = new ArrayList<String>();
			//SAP字段编码
			ArrayList<String> sap_field_code = new ArrayList<String>();
			Collections.sort(syProConfigBVOs, new SapVOSort(direction));
			for(SyProConfigBVO syProConfigBVO:syProConfigBVOs){
				if(SapConstants.DIRECTION_SAP2NC==direction){
					//SAP->NC
					if(syProConfigBVO.getIsenable_sn().booleanValue()){
						if(!syProConfigBVO.getNullflag().booleanValue()){
							notNullField.add(syProConfigBVO.getField_code());
							nc_field_name.add(syProConfigBVO.getField_name());
						}
						formula.add(syProConfigBVO.getFormula_sn());
					}
					//把NC编码也放进去 begin
					nc_field_code.add(syProConfigBVO.getField_code());
					//把NC编码也放进去 end
				}else if(SapConstants.DIRECTION_NC2SAP==direction){
					//NC->SAP
					if(syProConfigBVO.getIsenable_ns().booleanValue()){
						formula.add(syProConfigBVO.getFormula_ns());
						nc_field_code.add(syProConfigBVO.getField_code());
						sap_field_code.add(syProConfigBVO.getField_code_sap());
					}
				}
			}
			formulasMap.put(SapConstants.NOTNULL_FIELD_KEY, notNullField);
			formulasMap.put(SapConstants.FORMULA_KEY, formula);
			formulasMap.put(SapConstants.NC_FIELD_CODE, nc_field_code);
			formulasMap.put(SapConstants.SAP_FIELD_CODE, sap_field_code);
			formulasMap.put(SapConstants.NC_FIELD_NAME, nc_field_name);
			return formulasMap;
		}
		return null;
	}
	
	/**
	 * 非空校验+执行公式
	 * @param hConfigCode
	 * 				表头公式配置编码
	 * @param bConfigCode
	 * 				表体公式配置编码
	 * @param headVO
	 * 				表头VO
	 * @param bodyVOs
	 * 				表体VO
	 * @throws BusinessException
	 */
	public static void notNullCheckAndExFormula(String hConfigCode,String bConfigCode,AggregatedValueObject aggVO) throws Exception {
		HashMap<String,ArrayList<String>> hFormulaone = WyWGPTUtils.getFormulas(hConfigCode,SapConstants.DIRECTION_SAP2NC);
		HashMap<String,ArrayList<String>> bFormulaone = WyWGPTUtils.getFormulas(bConfigCode,SapConstants.DIRECTION_SAP2NC);
		List<String> headKeys = hFormulaone.get(SapConstants.NOTNULL_FIELD_KEY);
		List<String> headKeYsName = hFormulaone.get(SapConstants.NC_FIELD_NAME);
		List<String> bodyKeys = new ArrayList<String>();
		List<String> bodyKeysName = new ArrayList<String>();
		if(bFormulaone!=null){
			bodyKeys=bFormulaone.get(SapConstants.NOTNULL_FIELD_KEY);	
			 bodyKeysName=bFormulaone.get(SapConstants.NC_FIELD_NAME);	
		}
		
		
		ArrayList<String> hFormula = hFormulaone.get(SapConstants.FORMULA_KEY);
		ArrayList<String> bFormula = new ArrayList<String>(); 
		if(bFormulaone!=null){
			bFormula =bFormulaone.get(SapConstants.FORMULA_KEY);
		}
		ExtFormulaParser extFormulaParser = new ExtFormulaParser();
//		if(aggVO instanceof BXVO){//报销单
//			
//			BXVO bxvo=(BXVO)aggVO;
//			// 费用分摊单信息有误但NC没有返回报错给sap  begin
//			CShareDetailVO[] shareVO=bxvo.getcShareDetailVo();
//			if(shareVO!=null&&shareVO.length>0){
//				notNullCheck(headKeys,headKeYsName,bodyKeysName,bodyKeys, aggVO.getParentVO(), bxvo.getcShareDetailVo(),1);	
//				extFormulaParser.execFormulas(hFormula.toArray(new String[0]), bFormula.toArray(new String[0]), bxvo, null);
//				notNullCheck(headKeys,headKeYsName,bodyKeysName,bodyKeys, aggVO.getParentVO(),bxvo.getcShareDetailVo(),2);
//			}else {
//				notNullCheck(headKeys,headKeYsName,bodyKeysName,bodyKeys, aggVO.getParentVO(), aggVO.getChildrenVO(),1);	
//				extFormulaParser.execFormulas(hFormula.toArray(new String[0]), bFormula.toArray(new String[0]), bxvo, null);
//				notNullCheck(headKeys,headKeYsName,bodyKeysName,bodyKeys, aggVO.getParentVO(),aggVO.getChildrenVO(),2);
//			}
//			//费用分摊单信息有误但NC没有返回报错给sap end
//			
//		}else 
			notNullCheck(headKeys,headKeYsName,bodyKeysName,bodyKeys, aggVO.getParentVO(), aggVO.getChildrenVO(),1);
			extFormulaParser.execFormulas(hFormula.toArray(new String[0]), bFormula.toArray(new String[0]),aggVO);
			notNullCheck(headKeys,headKeYsName,bodyKeysName,bodyKeys, aggVO.getParentVO(),aggVO.getChildrenVO(),2);
	
	}
	/**
	 * 非空校验+执行公式
	 * @param hConfigCode
	 * 				表头公式配置编码
	 * @param bConfigCode
	 * 				表体公式配置编码
	 * @param headVO
	 * 				表头VO
	 * @param bodyVOs
	 * 				表体VO
	 * @throws BusinessException
	 */
	public static void notNullCheckAndExFormulaTwo(String hConfigCode,String bConfigCode,AggregatedValueObject aggVO) throws Exception {
		HashMap<String,ArrayList<String>> hFormulaone = WyWGPTUtils.getFormulas(hConfigCode,SapConstants.DIRECTION_SAP2NC);
		HashMap<String,ArrayList<String>> bFormulaone = WyWGPTUtils.getFormulas(bConfigCode,SapConstants.DIRECTION_SAP2NC);
		List<String> headKeys = hFormulaone.get(SapConstants.NOTNULL_FIELD_KEY);
		List<String> headKeYsName = hFormulaone.get(SapConstants.NC_FIELD_NAME);
		List<String> bodyKeys = new ArrayList<String>();
		List<String> bodyKeysName = new ArrayList<String>();
		if(bFormulaone!=null){
			bodyKeys=bFormulaone.get(SapConstants.NOTNULL_FIELD_KEY);	
			 bodyKeysName=bFormulaone.get(SapConstants.NC_FIELD_NAME);	
		}
		
		
		ArrayList<String> hFormula = hFormulaone.get(SapConstants.FORMULA_KEY);
		ArrayList<String> bFormula = new ArrayList<String>(); 
		if(bFormulaone!=null){
			bFormula =bFormulaone.get(SapConstants.FORMULA_KEY);
		}
		ExtFormulaParser extFormulaParser = new ExtFormulaParser();
//		if(aggVO instanceof BXVO){//报销单
//			
//			BXVO bxvo=(BXVO)aggVO;
//			// 费用分摊单信息有误但NC没有返回报错给sap  begin
//			CShareDetailVO[] shareVO=bxvo.getcShareDetailVo();
//			if(shareVO!=null&&shareVO.length>0){
//				notNullCheck(headKeys,headKeYsName,bodyKeysName,bodyKeys, aggVO.getParentVO(), bxvo.getcShareDetailVo(),1);	
//				extFormulaParser.execFormulas(hFormula.toArray(new String[0]), bFormula.toArray(new String[0]), bxvo, null);
//				notNullCheck(headKeys,headKeYsName,bodyKeysName,bodyKeys, aggVO.getParentVO(),bxvo.getcShareDetailVo(),2);
//			}else {
//				notNullCheck(headKeys,headKeYsName,bodyKeysName,bodyKeys, aggVO.getParentVO(), aggVO.getChildrenVO(),1);	
//				extFormulaParser.execFormulas(hFormula.toArray(new String[0]), bFormula.toArray(new String[0]), bxvo, null);
//				notNullCheck(headKeys,headKeYsName,bodyKeysName,bodyKeys, aggVO.getParentVO(),aggVO.getChildrenVO(),2);
//			}
//			//费用分摊单信息有误但NC没有返回报错给sap end
//			
//		}else 
			//notNullCheck(headKeys,headKeYsName,bodyKeysName,bodyKeys, aggVO.getParentVO(), aggVO.getChildrenVO(),1);
			extFormulaParser.execFormulas(hFormula.toArray(new String[0]), bFormula.toArray(new String[0]),aggVO);
			notNullCheck(headKeys,headKeYsName,bodyKeysName,bodyKeys, aggVO.getParentVO(),aggVO.getChildrenVO(),2);
	
	}
	/**
	 * 基本档案非空校验
	 */
	public static void notNullCheck(List<String> keys,List<String> keYsName,List<CircularlyAccessibleValueObject> lst_bdvo)throws Exception{
		Set<String> keySetName = new HashSet<String>();
		Object value;
		CircularlyAccessibleValueObject bdvo=null;
		if(null!=lst_bdvo&&lst_bdvo.size()>0){
			for(int j=0;j<lst_bdvo.size();j++){
				bdvo=lst_bdvo.get(j);
				if(CollectionUtils.isNotEmpty(keys) && bdvo!=null){
					for (int i = 0; i < keys.size(); i++) {
						String key=keys.get(i);
						value = bdvo.getAttributeValue(key);
						if(value==null || StringUtil.isEmptyWithTrim(value.toString())){
							keySetName.add(keYsName.get(i));
						}
					}
					if(keySetName.size()>0){
						String keyName = StringUtils.join(keySetName.toArray(), "、");
						throw new BusinessException( "以下字段不能为空或者NC对应的档案不存在："+keyName);	
					}
				}
			}
		}
	}
	
	/**
	 * 非空字段校验
	 * @param headKeys
	 * 			表头字段
	 * @param bodyKeys
	 * 			表体字段
	 * @param bodyKeys2 
	 * @param bodyKeysName 
	 * @param headVO
	 * 			表头VO
	 * @param bodyVOs
	 * 			表体VO
	 * @param type
	 * 			1：第一次非空校验，2：转换后非空校验
	 * @throws Exception
	 */
	public static void notNullCheck(List<String> headKeys,List<String> headKeYsName,List<String> bodyKeysName, List<String> bodyKeys, CircularlyAccessibleValueObject headVO,CircularlyAccessibleValueObject[] bodyVOs,int type) throws Exception{
		Set<String> keySetName = new HashSet<String>();
		Object value;
		if(CollectionUtils.isNotEmpty(headKeys) && headVO!=null){
			for (int i = 0; i < headKeys.size(); i++) {
				String key=headKeys.get(i);
				value = headVO.getAttributeValue(key);
				if(value==null || StringUtil.isEmptyWithTrim(value.toString())){
					keySetName.add(headKeYsName.get(i));
				}
			}
		}
		if(CollectionUtils.isNotEmpty(bodyKeys) && ArrayUtils.isNotEmpty(bodyVOs)){
		     for (int i = 0; i < bodyKeys.size(); i++) {
				for(CircularlyAccessibleValueObject bodyVO:bodyVOs){
					String key=bodyKeys.get(i);
					value = bodyVO.getAttributeValue(key);
					if(value==null || StringUtil.isEmptyWithTrim(value.toString())){
						keySetName.add(bodyKeysName.get(i));
					}
				}
			}
		}
		if(keySetName.size()>0){
			String keyName = StringUtils.join(keySetName.toArray(), "、");
			if(type==1){
				throw new BusinessException( "以下字段不能为空："+keyName);	
			}else{
				throw new BusinessException( "以下字段转换失败："+keyName);	
			}
		}
	}
	
	
	/**
	 * 查询NC字段编码和SAP编码对照
	 * @param code			表头编码
	 * @param direction		方向【SAP->NC ? NC->SAP】
	 * @return SAP->NC
	 * @throws BusinessException
	 */
	public static HashMap<String,String> getTranNCcodes(String code,int direction) throws BusinessException{
		StringBuffer sqlstr = new StringBuffer("");
		sqlstr.append("item = (select pk_head").append("\r\n");
		sqlstr.append("  from sap_syproconfig").append("\r\n");
		sqlstr.append(" where billno = '");
		sqlstr.append(code);
		sqlstr.append("'").append("\r\n");
		sqlstr.append("   and nvl(dr, 0) = 0) and nvl(dr, 0) = 0 "); 
		List<SyProConfigBVO> syProConfigBVOs = (List<SyProConfigBVO>)getQueryBS().retrieveByClause(SyProConfigBVO.class, sqlstr.toString());
		if(syProConfigBVOs!=null && syProConfigBVOs.size()>0){
			HashMap<String,String> tranNCcodeMap = new HashMap<String,String>();
			for(SyProConfigBVO syProConfigBVO:syProConfigBVOs){
				if(SapConstants.DIRECTION_SAP2NC==direction){
					//SAP->NC					
					if(syProConfigBVO.getIsenable_sn().booleanValue()){//是否启用sap-nc
						String code_sap=syProConfigBVO.getField_code_sap();
						if(code_sap!=null&&!"".equals(code_sap.trim())&&!"1".equals(code_sap.trim())){
							tranNCcodeMap.put(code_sap,syProConfigBVO.getField_code());
						}
					}					
				}
			}
			return tranNCcodeMap;
		}
		return null;
	}
	/**
	 * 是否传递SAP
	 * @param pk_transtypecode
	 * 			交易类型编码
	 * @return
	 * table 表名 finfield 查询字段
	 * @throws Exception
	 */
	public static boolean isSendToSAP(String pk_transtypecode,String table,String finfield) throws Exception{
		StringBuffer sqlstr = new StringBuffer("");
		sqlstr.append("select "+finfield+" from "+table+" where DJLXBM = '"); //def2  er_djlx
		sqlstr.append(pk_transtypecode); 
		sqlstr.append("'"); 
		String isSendToSAP = (String)getQueryBS().executeQuery(sqlstr.toString(), new ColumnProcessor());
		if(UFBoolean.TRUE.toString().equals(isSendToSAP)){
			return true;
		}
		return false;
	}
	
	/**
	 * 是否传递SAP(自定义查询条件)
	 * @author 符耀铭
	 * @time 2018年9月17日
	 * @param table
	 * @param finfield
	 * @param condition
	 * @return
	 * @throws Exception
	 */
	public static boolean isSendToSAP(String pk_transtypecode,String table,String finfield,String condition) throws Exception{
		StringBuffer sqlstr = new StringBuffer("");
		sqlstr.append("select "+finfield+" from "+table+" where ");
		sqlstr.append(condition); 
		String isSendToSAP = (String)getQueryBS().executeQuery(sqlstr.toString(), new ColumnProcessor());
		if(UFBoolean.TRUE.toString().equals(isSendToSAP)){
			return true;
		}
		return false;
	}
	
	/**
	 * 通过Esb发送JSon数据到SAP/融资
	 * @param jsonData
	 * @param itfCode
	 * @return
	 * @throws Exception
	 */
	public static JSONObject sendToESB_GX(String jsonData,String itfCode) throws Exception {
		JSONObject resultinfo = null;
		IEsbDAO service = ServiceLocator.find(IEsbDAO.class);
		EsbinfoVO[] esbinfos = (EsbinfoVO[]) service.findESB("code='"+itfCode+"'");
		if(esbinfos==null){
			ExceptionUtils.wrappBusinessException("没有找到接口配置信息-接口编码："+itfCode);
		}
		if(esbinfos.length>1){
			ExceptionUtils.wrappBusinessException("接口配置信息查询结果大于1【"+esbinfos.length+"】-接口编码："+itfCode);
		}
		String isstart = esbinfos[0].getIsstart();
		if("1".equals(isstart)){
			//接口启用
			String url = esbinfos[0].getUrl();
			String code = esbinfos[0].getCode();
			String msg = "发送请求：接口编码："+itfCode+"\n"+"请求报文：\n"+jsonData;
			Logger.error(msg);
			resultinfo = PubUtils.sendJsonPost_GX(url, jsonData, code);
			if(resultinfo!=null){
				msg += "\n返回报文：\n"+resultinfo.toString();
			}
			Logger.error(msg);
		}else{
			Logger.error("接口未启用！接口编码："+itfCode);
		}
		return resultinfo;
	}
	
	/**
	 * 通过Esb发送JSon数据到SAP/融资
	 * @param jsonData
	 * @param itfCode
	 * @return
	 * @throws Exception
	 */
	public static JSONObject sendToESB(String jsonData,String itfCode) throws Exception {
		JSONObject resultinfo = null;
		IEsbDAO service = ServiceLocator.find(IEsbDAO.class);
		EsbinfoVO[] esbinfos = (EsbinfoVO[]) service.findESB("code='"+itfCode+"'");
		if(esbinfos==null){
			ExceptionUtils.wrappBusinessException("没有找到接口配置信息-接口编码："+itfCode);
		}
		if(esbinfos.length>1){
			ExceptionUtils.wrappBusinessException("接口配置信息查询结果大于1【"+esbinfos.length+"】-接口编码："+itfCode);
		}
		String isstart = esbinfos[0].getIsstart();
		if("1".equals(isstart)){
			//接口启用
			String url = esbinfos[0].getUrl();
			String code = esbinfos[0].getCode();
			String msg = "发送请求：接口编码："+itfCode+"\n"+"请求报文：\n"+jsonData;
			Logger.error(msg);
			resultinfo = PubUtils.sendJsonPost(url, jsonData, code);
			if(resultinfo!=null){
				msg += "\n返回报文：\n"+resultinfo.toString();
			}
			Logger.error(msg);
		}else{
			Logger.error("接口未启用！接口编码："+itfCode);
		}
		return resultinfo;
	}
	
	public static String getSendToEsbData(String instId,Object requestInfo){
		EsbVO esbVO = new EsbVO();
		EsbInfoVO esbInfoVO = new EsbInfoVO();
		QueryInfoVO queryInfoVO = new QueryInfoVO();
		//接口唯一 ID（填写说明：接口编码+Long 型当前时间，例：D02S-SAPMDM-1804-008-301235201459）
		esbInfoVO.setInstId(instId);
		//调用方调用接口时间,格式：“yyyy-MM-dd HH24:mm:ss:SSS”
		esbInfoVO.setRequestTime(AppContext.getInstance().getServerTime().toString());
		//弹性字段 （填写说明：必有字段，暂时无需填值）
		esbInfoVO.setAttr1("");
		esbInfoVO.setAttr2("");
		esbInfoVO.setAttr3("");
		
		//页大小
		queryInfoVO.setPageSize("1");
		//第几页
		queryInfoVO.setCurrentPage("1");
		
		esbVO.setEsbInfo(esbInfoVO);
		esbVO.setQueryInfo(queryInfoVO);
		esbVO.setRequestInfo(requestInfo);
		return JSONObject.toJSONString(esbVO);
	}
	
	/**
	 * 通过交易类型及单据主键查询结算信息
	 * @param pk_tradetype 业务单据交易类型
	 * @param pk_busibill 业务单据主表主键
	 * @return 结算信息
	 * @throws BusinessException
	 */
//	public SettlementAggVO findSettlementByBillPK(String pk_tradetype,String pk_busibill) throws BusinessException{
//		Object pk_settlement=getQueryBS().executeQuery("select pk_settlement from cmp_settlement where pk_tradetype='"+pk_tradetype+"' and pk_busibill='"+pk_busibill+"' and isnull(dr,0)=0", new ColumnProcessor());
//		if(pk_settlement==null || "".equals(pk_settlement.toString().trim()))
//			return null;
//		SettlementAggVO aggvo=(SettlementAggVO) getService().queryBillVOByPrimaryKey(
//				new String[]{
//				SettlementAggVO.class.getName(),
//				SettlementHeadVO.class.getName(),
//				SettlementBodyVO.class.getName()}
//				, pk_settlement.toString());
//		return aggvo;
//	}
	/**
	 * 自动结算已签字结算信息
	 * @param aggvos
	 * @throws BusinessException
	 */
//	public void autoSettles(final SettlementAggVO[] aggvos) throws BusinessException{
//		UFDate date=new UFDate();
//		for(int i=0;i<aggvos.length;i++){
//			SettlementHeadVO headvo=(SettlementHeadVO)aggvos[i].getParentVO();
//			headvo.setSettletype(SettleType.HAND_SETTLE.getStatus());
//			headvo.setPk_executor(headvo.getPk_signer());//设置签字人为当前结算人
//			headvo.setLastupdater(headvo.getPk_signer());//设置签字人为最新更新人
//			//headvo.setLastupdatedate(date);
//			aggvos[i].setParentVO(headvo);
//		}
//		SettleUtils.fillSettleDate(date, aggvos);//填充结算日期
//		getSettle().settleArray(aggvos);
//	}
	/**
	 * 自动签字结算信息
	 * @param aggvos
	 * @throws BusinessException
	 */
//	public void autoSign(final SettlementAggVO[] aggvos) throws BusinessException{
//		UFDate date=new UFDate();
//		for(int i=0;i<aggvos.length;i++){
//			SettlementHeadVO headvo=(SettlementHeadVO)aggvos[i].getParentVO();
//			//headvo.setBusistatus(8);
//			headvo.setPk_signer(INCSystemUserConst.NC_USER_PK);//设置 NC系统 为当前签字人
//			//headvo.setLastupdatedate(date);
//			headvo.setLastupdater(INCSystemUserConst.NC_USER_PK);//设置 NC系统 为最新更新人
//			aggvos[i].setParentVO(headvo);
//		}
//		SettleUtils.fillSignDate(date, aggvos);//填充签字日期
//		getSettle().signArray(aggvos);
//	}
	
	/**
	 * 查询流程处理人
	 * @param billType
	 * @param billId
	 * @return
	 * @throws Exception
	 */
	public static String queryWorkUserID(String billType,String billId)throws Exception {
		String userID = null;
		String strWfTypeSql = " and workflow_type in" + WorkflowTypeEnum.getInstanceTypeInSql(WorkflowTypeEnum.Approveflow.getIntValue());
		String where = "pk_billtype=? and billversionpk=? and ismsgbind='N' "
				+ strWfTypeSql
				+ " and actiontype<>'"
				+ WorkflownoteVO.WORKITEM_TYPE_BIZ
				+ "' and approvestatus in("
				+ WfTaskOrInstanceStatus.getUnfinishedStatusSet()
				+ ") order by senddate";
		SQLParameter para = new SQLParameter();
		para.addParam(billType);
		para.addParam(billId);
		List<WorkflownoteVO> co = (List<WorkflownoteVO>)new BaseDAO().retrieveByClause(WorkflownoteVO.class, where, para);
		if(co!=null && co.size()>0){
			userID = co.get(0).getCheckman();
		}
		if(userID==null || userID.trim().length()<20){
			userID = InvocationInfoProxy.getInstance().getUserId();
		}
		return userID;
	}
	/**
	 * 查询流程信息
	 * @param actionCode
	 * @param billType
	 * @param billVO
	 * @return
	 * @throws BusinessException
	 */
	public static WorkflownoteVO getWorkflownoteVO(String actionCode,String billType,AggregatedValueObject billVO,HashMap hmPfExParams) throws BusinessException{
		WorkflownoteVO worknoteVO = getIWorkflowMachine().checkWorkFlow(actionCode, billType, billVO, hmPfExParams);
		if(worknoteVO!=null){
			worknoteVO.setApproveresult("Y");
			worknoteVO.setChecknote("批准");
		}
		return worknoteVO;
	}
	public static void setResultVO(String billno,String issuccess,String msg,SAPResultVO sapResultVO){
		sapResultVO.setBillid(billno);
		sapResultVO.setIssuccess(issuccess);
		sapResultVO.setMsg(msg);
	}
	/**
	 * 只保留2000长度字符串
	 * @param str
	 * @return
	 */
	public static String getNewStr(String str) {
		if(str==null || "".equals(str)){
			return str;
		}
        int length = 0;
        int j = 0;
        for(int i = 0; i < str.length(); i++){
            int ascii = Character.codePointAt(str, i);  
            if(ascii >= 0 && ascii <=255){
            	length++;
            }else{
            	length += 2;
            }
            if(length>2000){
            	break;
            }
            j = i;
        }
       return str.substring(0,j+1);
    }
	
	public static IUAPQueryBS getQueryBS() {
		return NCLocator.getInstance().lookup(IUAPQueryBS.class);
	}

	public IUifService getService(){
		return NCLocator.getInstance().lookup(IUifService.class);
	}
	
//	public ISAPAutoSettles getSettle(){
//		return NCLocator.getInstance().lookup(ISAPAutoSettles.class);
//	}
	/**
	 * 校验接口
	 * @return	ISapItfValid
	 */
	public static ISapItfValid getISapItfValid(){
		return ServiceLocator.find(ISapItfValid.class);
	}
	/**
	 * 日志接口
	 * @return	ISapLog
	 */
	public static ISapLog getISapLog(){
		return NCLocator.getInstance().lookup(ISapLog.class);
	}
	
//	public static IBXBillPrivate getIBXBillPrivate(){
//		return NCLocator.getInstance().lookup(IBXBillPrivate.class);
//	}
	
	public static IResponseBill getIResponseBill(){
		return NCLocator.getInstance().lookup(IResponseBill.class);
	}
	
	public static IPFBusiAction getIPFBusiAction(){
		return NCLocator.getInstance().lookup(IPFBusiAction.class);
	}
	public static IWorkflowMachine getIWorkflowMachine() {
		return NCLocator.getInstance().lookup(IWorkflowMachine.class);
	}
}
