package nc.bs.pu.wgpt.process;

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

import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.uap.tools.formula.ExtFormulaParser;
import nc.impl.pubapp.pattern.data.bill.BillQuery;
import nc.impl.pubapp.pattern.data.vo.VOQuery;
import nc.itf.pu.m21.IOrderQuery;
import nc.itf.wgpt.process.IWuYeWgptBusiService;
import nc.jdbc.framework.SQLParameter;
import nc.jdbc.framework.processor.BeanListProcessor;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.jdbc.framework.processor.MapProcessor;
import nc.net.servlet.IReturnStatus;
import nc.pub.sap.constant.SapConstants;
import nc.pubitf.org.ICloseAccQryPubServicer;
import nc.util.uap.wgpt.WuYeWgptUtil;
import nc.vo.cache.CacheManager;
import nc.vo.cache.ICache;
import nc.vo.cache.config.CacheConfig;
import nc.vo.esb.ResultEsbVO;
import nc.vo.esb.ResultVO;
import nc.vo.ia.pub.util.IAScaleUtil;
import nc.vo.ic.m45.entity.PurchaseInBodyVO;
import nc.vo.ic.m45.entity.PurchaseInHeadVO;
import nc.vo.ic.m45.entity.PurchaseInVO;
import nc.vo.ic.m4d.entity.MaterialOutBodyVO;
import nc.vo.ic.m4d.entity.MaterialOutVO;
import nc.vo.pf.pub.BusitypeVO;
import nc.vo.pu.m21.entity.OrderItemVO;
import nc.vo.pu.m21.entity.OrderVO;
import nc.vo.pub.AggregatedValueObject;
import nc.vo.pub.BusinessException;
import nc.vo.pub.CircularlyAccessibleValueObject;
import nc.vo.pub.VOStatus;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.pub.lang.UFDate;
import nc.vo.pub.lang.UFDouble;
import nc.vo.pubapp.AppContext;
import nc.vo.pubapp.pattern.data.ValueUtils;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.pubapp.pattern.pub.MathTool;
import nc.vo.tmpub.util.DateUtil;
import nc.vo.tmpub.util.MathUtil;
import nc.vo.tmpub.util.SqlUtil;
import nc.vo.wgpt.log.WuYeWgptLogVO;
import ncc.bs.wy.tools.WyWGPTJsonTools;
import ncc.pub.wywgpt.utils.WyWGPTUtils;
import nccloud.commons.lang.ArrayUtils;
import uap.json.JSONObject;
/**
 * 二开新加的类，物业网购平台协同采购入库单/退库
 * @author 符耀铭
 * @time 2019年7月15日
 */
public class WritePurchaseinInfoProcess {

	public String WritePurchasein(JSONObject jsonobj) throws BusinessException {
		String rsdata = null;
		ResultEsbVO<ResultVO> esb = new ResultEsbVO<ResultVO>();
		ResultVO result = new ResultVO();
		Object wgptbillcode = null;
		String pk_bill=null;
		String billno=null;
		WuYeWgptLogVO logVO = new WuYeWgptLogVO();
		try {
			logVO = new WuYeWgptLogVO();
			logVO.setItfname("【网购平台->NC】新增/退库采购入库2");
			BaseDAO baseDAO=new BaseDAO();
			if (jsonobj == null || "".equals(jsonobj)) {// 无Post提交值
				result.setCode(IReturnStatus.FAILING);// 失败
				result.setMessage("Post所提交请求Json格式错误或者无值!");
				WuYeWgptUtil.createResultEsbVO(esb);
				esb.getEsbInfo().setReturnStatus(IReturnStatus.ESB_FAILING);
				esb.getEsbInfo().setReturnMsg("失败");
				esb.setResultInfo(result);
			} else {
				/** begin 获取请求值 **/
				JSONObject obj = jsonobj.getJSONObject("requestInfo");
				JSONObject header = obj.getJSONObject("Header");

				UFBoolean freplenishflag=ValueUtils.getUFBoolean(header.get("freplenishflag"));

				ICloseAccQryPubServicer closeAccQryPubServicer=NCLocator.getInstance().lookup(ICloseAccQryPubServicer.class);

				Object dcrkd=header.get("vdef25");//网购平台发货单号

				if(freplenishflag.booleanValue()){//退库
					logVO.setItfname("【网购平台->NC】退库采购入库");
					if(null==dcrkd){
						ExceptionUtils.wrappBusinessException("退库操作对冲入库单不能为空！");
					}
					String sql="select distinct ib.csourcebillhid,ib.cgeneralbid\n" +
							"  from ic_purchasein_h ih\n" + 
							" inner join ic_purchasein_b ib\n" + 
							"    on ih.cgeneralhid = ib.cgeneralhid\n" +
							" where ih.vdef16 = '"+dcrkd+"'\n" + 
							"   and nvl(ih.dr, 0) = 0\n" + 
							"   and nvl(ib.dr, 0) = 0 \n"+
							"  and nvl(ih.freplenishflag,'N') ='N'";
					Map map=(Map) baseDAO.executeQuery(sql, new MapProcessor());

					if(null==map || map.size()<1){
						ExceptionUtils.wrappBusinessException("在NC找不到发货单号为:"+dcrkd+"的采购入库单！");
					}
					PurchaseInVO purchaseInVO=WyWGPTJsonTools.jsonToOrderVO(jsonobj, PurchaseInVO.class, PurchaseInHeadVO.class, PurchaseInBodyVO.class, null);
					//TODO 批次查询，把批次根据批次+物料+dr=0找scm_batchcode批次主键设置到purchaseInVO
					
					/**
					 *  添加物业仓库的校验  begin
					 */
					PurchaseInHeadVO headVO =purchaseInVO.getHead();
					
					if(!"ZCC".equals(headVO.getCwarehouseid())){
						String countsql="select count(doc.pk_stordoc) from bd_stordoc doc left join org_orgs o on doc.pk_org = o.pk_org where doc.def3 = ?  and o.code = ?  and o.isbusinessunit = 'Y' and doc.dr=0";
						SQLParameter parameter=new SQLParameter();
						parameter.addParam(headVO.getVdef7());
						parameter.addParam(headVO.getPk_org());
						Object object =baseDAO.executeQuery(countsql, parameter, new ColumnProcessor());
						if(ValueUtils.getInt(object)>1){
							ExceptionUtils.wrappBusinessException("人力组织："+headVO.getVdef7()+"分配了多个仓库！");
						}
					}
					/**
					 * add by 添加物业仓库的校验  end
					 */

					// 转换前非空校验、执行公式、翻译后各项非空校验
					WyWGPTUtils.notNullCheckAndExFormulaTwo("WY_45HEAD", "WY_45BODY", purchaseInVO);

					IOrderQuery orderQuery=NCLocator.getInstance().lookup(IOrderQuery.class);

					OrderVO[] orderVOs =orderQuery.queryOrderVOsByIds(new String[]{map.get("csourcebillhid").toString()}, UFBoolean.FALSE);

					Map<String, OrderItemVO> orderitemMap=new HashMap<String, OrderItemVO>();
					List<OrderItemVO> orderItemVOs=new ArrayList<OrderItemVO>();
					for(int i=0;i<orderVOs[0].getBVO().length;i++){
						orderitemMap.put(orderVOs[0].getBVO()[i].getCrowno(), orderVOs[0].getBVO()[i]);
					}
					/**
					 * modify by 符耀铭 2020-2-10  修改映射字段  begin
					 */
					for(int j=0;j<purchaseInVO.getBodys().length;j++){

						OrderItemVO itemVO =(OrderItemVO) orderitemMap.get(purchaseInVO.getBodys()[j].getVsourcerowno()).clone();

						itemVO.setCproductorid(purchaseInVO.getBodys()[j].getCrowno());
						itemVO.setNnum(purchaseInVO.getBodys()[j].getNnum().abs());
						orderItemVOs.add(itemVO);
					}
					orderVOs[0].setBVO(orderItemVOs.toArray(new OrderItemVO[0]));
					PurchaseInVO[] excPurchaseInVOs=(PurchaseInVO[]) WuYeWgptUtil.getExchangeService().runChangeDataAry("21", "45", orderVOs, null);

					HashMap<String, ArrayList<String>> hFormulaone = WyWGPTUtils.getFormulas("WY_45HEAD", SapConstants.DIRECTION_SAP2NC);
					List<String> headKeys = hFormulaone.get(SapConstants.NC_FIELD_CODE);
					for (int j = 0; j < headKeys.size(); j++) {
						excPurchaseInVOs[0].getParentVO().setAttributeValue(headKeys.get(j), purchaseInVO.getParentVO().getAttributeValue(headKeys.get(j)));
					}
					HashMap<String, ArrayList<String>> bFormulaone = WyWGPTUtils.getFormulas("WY_45BODY", SapConstants.DIRECTION_SAP2NC);
					headKeys = bFormulaone.get(SapConstants.NC_FIELD_CODE);

					for(int a=0;a<excPurchaseInVOs[0].getBodys().length;a++){
						for(int b=0;b<purchaseInVO.getBodys().length;b++){
							if(excPurchaseInVOs[0].getBodys()[a].getVsourcerowno().equals(purchaseInVO.getBodys()[b].getVsourcerowno()) && excPurchaseInVOs[0].getBodys()[a].getCproductorid().equals(purchaseInVO.getBodys()[b].getCrowno())){
								excPurchaseInVOs[0].getBodys()[a].setCproductorid(null);
								for(int h=0;h<headKeys.size();h++){
									excPurchaseInVOs[0].getBodys()[a].setAttributeValue(headKeys.get(h), purchaseInVO.getBodys()[b].getAttributeValue(headKeys.get(h)));
//									excPurchaseInVOs[0].getBodys()[a].setAttributeValue("pk_batchcode",purchaseInVO.getBody(b).getAttributeValue("pk_batchcode"));//
								}
								break;
							}
						}
					}
					/**
					 * 修改映射字段  end
					 */
					sql= SqlUtil.buildSqlForIn("csourcebillbid", new String[]{map.get("cgeneralbid").toString()});

					VOQuery tool = new VOQuery(MaterialOutBodyVO.class);

					MaterialOutBodyVO[] bodys = (MaterialOutBodyVO[])tool.query(" and (" + sql + ") ", (String)null);

					IWuYeWgptBusiService busiService=NCLocator.getInstance().lookup(IWuYeWgptBusiService.class);
					Map<String, PurchaseInBodyVO> mnyMap=new HashMap<String, PurchaseInBodyVO>();

					if(!ArrayUtils.isEmpty(bodys)){

						Set hids = getVOsValueSet(bodys, "cgeneralhid");

						BillQuery billQuery = new BillQuery(MaterialOutVO.class);

						MaterialOutVO[] materialOutVOs=(MaterialOutVO[])billQuery.query((String[])hids.toArray(new String[0]));

						//获取没关账的会计月
						/**
						 * 修改关账判断逻辑  begin
						 */
						//String period=closeAccQryPubServicer.getFirstNoClosePeriodByPk_org("4008", excPurchaseInVOs[0].getHead().getPk_org());

						String period=excPurchaseInVOs[0].getHead().getDbilldate().getYear()+"-"+excPurchaseInVOs[0].getHead().getDbilldate().getStrMonth();

						Map<String, Boolean> perMap =closeAccQryPubServicer.isCloseByModuleIdAndPk_org("4008",excPurchaseInVOs[0].getHead().getPk_org(), new String[]{period});

						Map<String, Boolean> iaperMap =closeAccQryPubServicer.isCloseByModuleIdAndPk_org("2014",excPurchaseInVOs[0].getHead().getPk_org(), new String[]{period});
						if((perMap.get(period) || iaperMap.get(period))){
							excPurchaseInVOs[0].getHead().setDbilldate(DateUtil.getEndDateByMonth(new UFDate(excPurchaseInVOs[0].getHead().getDbilldate().getYear()+"-"+excPurchaseInVOs[0].getHead().getDbilldate().getStrMonth()+"-01"), 1));
							for(int i=0;i<excPurchaseInVOs[0].getBodys().length;i++){
								excPurchaseInVOs[i].getBody(i).setDbizdate(DateUtil.getEndDateByMonth(new UFDate(excPurchaseInVOs[0].getBody(i).getDbizdate().getYear()+"-"+excPurchaseInVOs[0].getBody(i).getDbizdate().getStrMonth()+"-01"), 1));
//								excPurchaseInVOs[0].getBody(i).setCcorrespondhid(excPurchaseInVOs[0].getBody(i).getCgeneralhid());
								excPurchaseInVOs[i].getBody(i).setCcorrespondhid(null);
								excPurchaseInVOs[i].getBody(i).setCcorrespondbid(null);
							}
							InvocationInfoProxy.getInstance().setBizDateTime(excPurchaseInVOs[0].getHead().getDbilldate().getMillis());
						}
						/**
						 * 修改关账判断逻辑  end
						 */
						MaterialOutVO  freplenishOutVO=(MaterialOutVO) materialOutVOs[0].clone();//复制一张正数的出库单

						freplenishOutVO.getHead().setCgeneralhid(null);

						freplenishOutVO.getHead().setVbillcode(null);

						freplenishOutVO.getHead().setTaudittime(null);

						freplenishOutVO.getHead().setApprover(null);

						freplenishOutVO.getHead().setFbillflag(2);

						freplenishOutVO.getHead().setDbilldate(AppContext.getInstance().getBusiDate());

						freplenishOutVO.getHead().setDmakedate(AppContext.getInstance().getBusiDate());

						freplenishOutVO.getHead().setStatus(VOStatus.NEW);
						//清空主键，重新复制，数量改成负数
						List<MaterialOutBodyVO> copyListOutBodyVOs=new ArrayList<MaterialOutBodyVO>();
						
						/**
						 * 退库单表体单据取入库单的无税单价  begin
						 */
						
						IAScaleUtil scale = IAScaleUtil.getScaleUtils();
						tool=new VOQuery(PurchaseInBodyVO.class);
						
						PurchaseInBodyVO[] inBodyVOs=(PurchaseInBodyVO[]) tool.query("  and  cgeneralhid='"+freplenishOutVO.getBody(0).getCsourcebillhid()+"'", (String)null);
						
						if(null!=inBodyVOs){
							for(int i=0;i<inBodyVOs.length;i++){
								mnyMap.put(inBodyVOs[i].getCgeneralbid(), inBodyVOs[i]);
								mnyMap.put(inBodyVOs[i].getVsourcerowno(), inBodyVOs[i]);
							}
						}
						
						MaterialOutBodyVO bodyVO=null;
						for(int i=0;i<excPurchaseInVOs[0].getBodys().length;i++){
							for(int k=0;k<freplenishOutVO.getBodys().length;k++){
								if(excPurchaseInVOs[0].getBody(i).getCmaterialoid().equals(freplenishOutVO.getBody(k).getCmaterialoid())&&excPurchaseInVOs[0].getBody(i).getVbatchcode().equals(freplenishOutVO.getBody(k).getVbatchcode())){
									bodyVO=(MaterialOutBodyVO) freplenishOutVO.getBody(k).clone();
									bodyVO.setCrowno(ValueUtils.getString((i+1)*10));
									bodyVO.setDbizdate(AppContext.getInstance().getBusiDate());
									bodyVO.setNcostprice(null);
									bodyVO.setNcostprice(mnyMap.get(bodyVO.getCsourcebillbid())==null?UFDouble.ZERO_DBL:mnyMap.get(bodyVO.getCsourcebillbid()).getNqtorigprice());

									bodyVO.setNassistnum(MathUtil.sub(UFDouble.ZERO_DBL, purchaseInVO.getBody(i).getNassistnum().abs()));
									bodyVO.setNnum(MathUtil.sub(UFDouble.ZERO_DBL, purchaseInVO.getBody(i).getNnum().abs())); 
									bodyVO.setNshouldassistnum(MathUtil.sub(UFDouble.ZERO_DBL, freplenishOutVO.getBody(k).getNshouldassistnum().abs())); 
									bodyVO.setNshouldnum(MathUtil.sub(UFDouble.ZERO_DBL, freplenishOutVO.getBody(k).getNshouldnum().abs()));
									UFDouble Ncostmny =scale.adjustMnyScale(bodyVO.getNcostprice().multiply(bodyVO.getNassistnum()),mnyMap.get(bodyVO.getCsourcebillbid())==null?bodyVO.getCcurrencyid():mnyMap.get(bodyVO.getCsourcebillbid()).getCcurrencyid());
									bodyVO.setNcostmny(Ncostmny);
//									bodyVO.setCcorrespondhid(bodyVO.getCgeneralhid());
//									bodyVO.setCcorrespondbid(bodyVO.getCgeneralbid());
									//新增加，因为freplenishOutVO直接clone导致对应来源单据信息都复制过来了
									bodyVO.setCcorrespondcode(null);
									bodyVO.setCcorrespondbid(null);
									bodyVO.setCcorrespondrowno(null);
									bodyVO.setCcorrespondtranstype(null);
									bodyVO.setCcorrespondtype(null);
									bodyVO.setCgeneralhid(null);
									bodyVO.setCgeneralbid(null);
									bodyVO.setCsourcebillbid(null);
									bodyVO.setCsourcebillhid(null);
									bodyVO.setCsourcetranstype(null);
									bodyVO.setCsourcetype(null);
									bodyVO.setTsourcebodyts(null);
									bodyVO.setTsourceheadts(null);
									bodyVO.setStatus(VOStatus.NEW);
									copyListOutBodyVOs.add(bodyVO);
									break;
								}
							}
						}
						/**
						 * add by 符耀铭 2020-1-15 退库单表体单据取入库单的无税单价  end
						 */
						freplenishOutVO.setChildrenVO(copyListOutBodyVOs.toArray(new MaterialOutBodyVO[0]));

						//校验退库数量是否超过入库数量
						//wby 20220307 调整代码，尝试解决数据异常仍能生成材料出库单
						if(checkArrNum(orderVOs[0]))  {
							busiService.generateMaterialOut_RequiresNew(freplenishOutVO);
						} else {
							ExceptionUtils.wrappBusinessException(nc.vo.ml.NCLangRes4VoTransl.getNCLangRes().getStrByID("4004030_0","04004030-0141")/*@res "存在订单累计退库主数量超出累计入库主数量的行，请检查！"*/);
						}
					}

					HashMap<String, ArrayList<String>> calcFormulaone = WyWGPTUtils.getFormulas("WY_45BODY_CALC", SapConstants.DIRECTION_SAP2NC);

					ArrayList<String> calcFormulaList = calcFormulaone.get(SapConstants.FORMULA_KEY);

					String[] calcyFormulas = calcFormulaList.toArray(new String[0]);

					ExtFormulaParser extFormulaParser = new ExtFormulaParser();
					
					//查询批次主键
//					String vbatchcode = excPurchaseInVOs[0].getBody(i).getVbatchcode();
//					String cmaterialvid = excPurchaseInVOs[0].getBody(i).getCmaterialvid();
//					String sqlcode = "select pk_batchcode from scm_batchcode where cmaterialvid='"+cmaterialvid+"' and vbatchcode '"+vbatchcode+"' and dr=0";
					String DNNum = excPurchaseInVOs[0].getHead().getVdef16();
					String PONum = excPurchaseInVOs[0].getHead().getVdef15();
					PurchaseInBodyVO[] ccinBodyVOs = null ;
					List<PurchaseInBodyVO> inBodyList = new ArrayList<PurchaseInBodyVO>();
					if(null != DNNum && null != PONum) {
					StringBuffer sqlstr=new StringBuffer("");
					sqlstr.append("select * from ic_purchasein_b").append("\r\n");
					sqlstr.append("where cgeneralhid = (select cgeneralhid from ic_purchasein_h where vdef16='"+DNNum+"' and vdef15='"+PONum+"' and dr ='0' and freplenishflag ='N') and dr=0"); 
					  inBodyList=  (List<PurchaseInBodyVO>) new BaseDAO().executeQuery(sqlstr.toString(), new BeanListProcessor(PurchaseInBodyVO.class));
					  ccinBodyVOs = inBodyList.toArray(new PurchaseInBodyVO[inBodyList.size()]);
					}
					
					if(null!=ccinBodyVOs){
						for(int i=0;i<ccinBodyVOs.length;i++){
							mnyMap.put(ccinBodyVOs[i].getCgeneralbid(), ccinBodyVOs[i]);
							mnyMap.put(ccinBodyVOs[i].getVsourcerowno(), ccinBodyVOs[i]);
						}
					}
					
					for(int i=0;i<excPurchaseInVOs[0].getBodys().length;i++){
						excPurchaseInVOs[0].getBody(i).setCcorrespondhid(null);
						excPurchaseInVOs[0].getBody(i).setCcorrespondbid(null);
						excPurchaseInVOs[0].getBody(i).setPk_batchcode(mnyMap.get(excPurchaseInVOs[0].getBody(i).getVsourcerowno()).getPk_batchcode());
					}
					extFormulaParser.execFormulas(calcyFormulas, excPurchaseInVOs[0], false);
					PurchaseInVO aggvo = excPurchaseInVOs[0];
					busiService.generateMaterialOut_RequiresNew(aggvo);
					//					Object[] saveObjects =(Object[]) SapUtils.getIPFBusiAction().processAction("WRITE", excPurchaseInVOs[0].getHead().getVtrantypecode(), null, excPurchaseInVOs[0], null, null);
					//					saveObjects=(Object[]) SapUtils.getIPFBusiAction().processAction("SIGN", excPurchaseInVOs[0].getHead().getVtrantypecode(), null, (PurchaseInVO) saveObjects[0], null, null);

					pk_bill = aggvo.getHead().getPrimaryKey();
					billno =  aggvo.getHead().getVbillcode();
					WuYeWgptUtil.createResultEsbVO(esb);
					esb.getEsbInfo().setReturnStatus(IReturnStatus.ESB_SUCCEED);
					esb.getEsbInfo().setReturnMsg("协同采购入库单退库成功");
					result.setCode(IReturnStatus.SUCCEED);
					esb.setResultInfo(result);

				}else {
					logVO.setItfname("【网购平台->NC】新增采购入库");
					String region="ic_purc_vdef16";
					CacheConfig config=new CacheConfig(region,true,3000,-1,CacheConfig.CacheType.MEMORY, CacheConfig.MemoryCacheLevel.SOFT);
					ICache cache =CacheManager.getInstance().getCache(config);
					Object cacheObject=cache.get("vdef16");
					if(dcrkd.equals(cacheObject)){
						ExceptionUtils.wrappBusinessException("发货单号:"+dcrkd+"在NC系统正在进行入库处理，请勿重复推送！");
					}
					cache.put("vdef16", dcrkd);
					String sql="select distinct ib.csourcebillhid,ib.cgeneralbid\n" +
							"  from ic_purchasein_h ih\n" + 
							" inner join ic_purchasein_b ib\n" + 
							"    on ih.cgeneralhid = ib.cgeneralhid\n" +
							" where ih.vdef16 = '"+dcrkd+"'\n" + 
							"   and nvl(ih.dr, 0) = 0\n" + 
							"   and nvl(ib.dr, 0) = 0 \n"+
							"  and nvl(ih.freplenishflag,'N') ='N'";
					Map map=(Map) baseDAO.executeQuery(sql, new MapProcessor());
					
					if(null==map||map.size()<1){
						Object wgptordercode=header.get("vdef18");
						if(null!=wgptordercode){
							sql = "select pk_order from  po_order where nvl(dr,0)=0 and vdef15='" + wgptordercode + "'";
							String pk_order = (String) baseDAO.executeQuery(sql, new ColumnProcessor());

							if(null!=pk_order){
								IOrderQuery orderQuery=NCLocator.getInstance().lookup(IOrderQuery.class);
								OrderVO[] orderVOs =orderQuery.queryOrderVOsByIds(new String[]{pk_order}, UFBoolean.FALSE);


								Map<String, OrderItemVO> orderitemMap=new HashMap<String, OrderItemVO>();
								List<OrderItemVO> orderItemVOs=new ArrayList<OrderItemVO>();
								for(int i=0;i<orderVOs[0].getBVO().length;i++){
									orderitemMap.put(orderVOs[0].getBVO()[i].getCrowno(), orderVOs[0].getBVO()[i]);
								}
								PurchaseInVO purchaseInVO=WyWGPTJsonTools.jsonToOrderVO(jsonobj, PurchaseInVO.class, PurchaseInHeadVO.class, PurchaseInBodyVO.class, null);
								
								/**
								 *  添加物业仓库的校验  begin
								 */
								PurchaseInHeadVO headVO =purchaseInVO.getHead();
								
								if(!"ZCC".equals(headVO.getCwarehouseid())){
									String countsql="select count(doc.pk_stordoc) from bd_stordoc doc left join org_orgs o on doc.pk_org = o.pk_org where doc.def3 = ?  and o.code = ?  and o.isbusinessunit = 'Y' and doc.dr=0";
									SQLParameter parameter=new SQLParameter();
									parameter.addParam(headVO.getVdef7());
									parameter.addParam(headVO.getPk_org());
									Object object =baseDAO.executeQuery(countsql, parameter, new ColumnProcessor());
									if(ValueUtils.getInt(object)>1){
										ExceptionUtils.wrappBusinessException("人力组织："+headVO.getVdef7()+"分配了多个仓库！");
									}
								}
								/**
								 *  添加物业仓库的校验  end
								 */
								
								// 转换后再进行非空校验、执行公式、翻译后各项非空校验
								WyWGPTUtils.notNullCheckAndExFormulaTwo("WY_45HEAD", "WY_45BODY", purchaseInVO);
								/**
								 * 修改映射字段  begin
								 */
								for(int j=0;j<purchaseInVO.getBodys().length;j++){
									
									OrderItemVO itemVO =(OrderItemVO) orderitemMap.get(purchaseInVO.getBodys()[j].getVsourcerowno()).clone();
									
									itemVO.setCproductorid(purchaseInVO.getBodys()[j].getCrowno());
									
									orderItemVOs.add(itemVO);
								}
								orderVOs[0].setBVO(orderItemVOs.toArray(new OrderItemVO[0]));
								PurchaseInVO[] excPurchaseInVOs=(PurchaseInVO[]) WuYeWgptUtil.getExchangeService().runChangeDataAry("21", "45", orderVOs, null);

								HashMap<String, ArrayList<String>> hFormulaone = WyWGPTUtils.getFormulas("WY_45HEAD", SapConstants.DIRECTION_SAP2NC);
								List<String> headKeys = hFormulaone.get(SapConstants.NC_FIELD_CODE);
								for (int j = 0; j < headKeys.size(); j++) {
									excPurchaseInVOs[0].getParentVO().setAttributeValue(headKeys.get(j), purchaseInVO.getParentVO().getAttributeValue(headKeys.get(j)));
								}
								HashMap<String, ArrayList<String>> bFormulaone = WyWGPTUtils.getFormulas("WY_45BODY", SapConstants.DIRECTION_SAP2NC);
								headKeys = bFormulaone.get(SapConstants.NC_FIELD_CODE);

								for(int a=0;a<excPurchaseInVOs[0].getBodys().length;a++){
									for(int b=0;b<purchaseInVO.getBodys().length;b++){
										if(excPurchaseInVOs[0].getBodys()[a].getVsourcerowno().equals(purchaseInVO.getBodys()[b].getVsourcerowno()) && excPurchaseInVOs[0].getBodys()[a].getCproductorid().equals(purchaseInVO.getBodys()[b].getCrowno())){
											excPurchaseInVOs[0].getBodys()[a].setCproductorid(null);
											for(int h=0;h<headKeys.size();h++){
												excPurchaseInVOs[0].getBodys()[a].setAttributeValue(headKeys.get(h), purchaseInVO.getBodys()[b].getAttributeValue(headKeys.get(h)));
											}
											break;
										}
									}
								}
								/**
								 * 修改映射字段  end
								 */
								HashMap<String, ArrayList<String>> calcFormulaone = WyWGPTUtils.getFormulas("WY_45BODY_CALC", SapConstants.DIRECTION_SAP2NC);

								ArrayList<String> calcFormulaList = calcFormulaone.get(SapConstants.FORMULA_KEY);
								String[] calcyFormulas = calcFormulaList.toArray(new String[0]);

								ExtFormulaParser extFormulaParser = new ExtFormulaParser();
								extFormulaParser.execFormulas(calcyFormulas, excPurchaseInVOs[0], false);
								//获取没关账的会计月
								/**
								 * 修改关账判断逻辑  begin
								 */
//								String period=excPurchaseInVOs[0].getHead().getDbilldate().getYear()+"-"+(Integer.valueOf(excPurchaseInVOs[0].getHead().getDbilldate().getMonth())>9?excPurchaseInVOs[0].getHead().getDbilldate().getMonth():"0"+excPurchaseInVOs[0].getHead().getDbilldate().getMonth());
								String period=excPurchaseInVOs[0].getHead().getDbilldate().getYear()+"-"+excPurchaseInVOs[0].getHead().getDbilldate().getStrMonth();
								Map<String, Boolean> perMap =closeAccQryPubServicer.isCloseByModuleIdAndPk_org("4008",excPurchaseInVOs[0].getHead().getPk_org(), new String[]{period});

								Map<String, Boolean> iaperMap =closeAccQryPubServicer.isCloseByModuleIdAndPk_org("2014",excPurchaseInVOs[0].getHead().getPk_org(), new String[]{period});
								if((perMap.get(period) || iaperMap.get(period))){
									excPurchaseInVOs[0].getHead().setDbilldate(DateUtil.getEndDateByMonth(new UFDate(excPurchaseInVOs[0].getHead().getDbilldate().getYear()+"-"+excPurchaseInVOs[0].getHead().getDbilldate().getStrMonth()+"-01"), 1));
									for(int i=0;i<excPurchaseInVOs[0].getBodys().length;i++){
										excPurchaseInVOs[0].getBody(i).setDbizdate(DateUtil.getEndDateByMonth(new UFDate(excPurchaseInVOs[0].getBody(i).getDbizdate().getYear()+"-"+excPurchaseInVOs[0].getBody(i).getDbizdate().getStrMonth()+"-01"), 1));
										excPurchaseInVOs[0].getBody(i).setCcorrespondhid(null);
										excPurchaseInVOs[0].getBody(i).setCcorrespondbid(null);
									}
									InvocationInfoProxy.getInstance().setBizDateTime(excPurchaseInVOs[0].getHead().getDbilldate().getMillis());
								}
								/**
								 * 修改关账判断逻辑  end
								 */
								for(int i=0;i<excPurchaseInVOs[0].getBodys().length;i++){
									excPurchaseInVOs[0].getBody(i).setCcorrespondhid(null);
									excPurchaseInVOs[0].getBody(i).setCcorrespondbid(null);
								}
								Object[] saveObjects =(Object[]) WyWGPTUtils.getIPFBusiAction().processAction("WRITE", excPurchaseInVOs[0].getHead().getVtrantypecode(), null, excPurchaseInVOs[0], null, null);
								pk_bill=((PurchaseInVO) saveObjects[0]).getPrimaryKey();
								billno = ((PurchaseInVO) saveObjects[0]).getHead().getVbillcode();
								saveObjects=(Object[]) WyWGPTUtils.getIPFBusiAction().processAction("SIGN", excPurchaseInVOs[0].getHead().getVtrantypecode(), null, (PurchaseInVO) saveObjects[0], null, null);
								nc.vo.pf.pub.BusitypeVO busiTypeVO = (BusitypeVO) baseDAO.retrieveByPK(BusitypeVO.class, excPurchaseInVOs[0].getHead().getCbiztype());
								if(!"Cxx-CG001".equals(busiTypeVO.getBusicode()) && !freplenishflag.booleanValue()){//业务流定义，固定资产采购
									MaterialOutVO[]  materialOutVOs =(MaterialOutVO[]) WuYeWgptUtil.getExchangeService().runChangeDataAry("45", "4D-01",  (AggregatedValueObject[]) saveObjects, null);
									if("Cxx-CG003".equalsIgnoreCase(busiTypeVO.getBusicode())){//业务流定义，费用类采购
										String sqlbm = "select pk_billtypeid from bd_billtype where pk_billtypecode ='4D-Cxx-01' and nvl(dr,0)=0";
										String billtypeid =(String) baseDAO.executeQuery(sqlbm, new ColumnProcessor());
										if(null !=billtypeid && billtypeid.length()>0){
										   materialOutVOs[0].getHead().setCtrantypeid(billtypeid);
										}
										materialOutVOs[0].getHead().setVtrantypecode("4D-Cxx-01");//4D-Cxx-01	部门领用
									}else {
										String sqlbm = "select pk_billtypeid from bd_billtype where pk_billtypecode ='4D-Cxx-02' and nvl(dr,0)=0";
										String billtypeid =(String) baseDAO.executeQuery(sqlbm, new ColumnProcessor());
										if(null !=billtypeid && billtypeid.length()>0){
											materialOutVOs[0].getHead().setCtrantypeid(billtypeid);//4D-Cxx-02	工程领用	
										}
//										materialOutVOs[0].getHead().setCtrantypeid("1001H21000000001JMJN");
										materialOutVOs[0].getHead().setVtrantypecode("4D-Cxx-02");
									}
									
									
									Object[]  objects=(Object[]) WyWGPTUtils.getIPFBusiAction().processAction("WRITE", materialOutVOs[0].getHead().getVtrantypecode(), null, materialOutVOs[0], null, null);
									WyWGPTUtils.getIPFBusiAction().processAction("SIGN", materialOutVOs[0].getHead().getVtrantypecode(), null, ((MaterialOutVO)objects[0]), null, null);
								}
							}else {
								ExceptionUtils.wrappBusinessException("采购订单号【"+wgptordercode+"】在NC系统不存在,请检查数据之后推送！");
							}
						}else {
							ExceptionUtils.wrappBusinessException("采购订单号【vdef18】不能为空！");
						}
					}else {
						ExceptionUtils.wrappBusinessException("发货单号:"+dcrkd+"在NC系统已存在,请勿重复推送！");
					}
					WuYeWgptUtil.createResultEsbVO(esb);
					esb.getEsbInfo().setReturnStatus(IReturnStatus.ESB_SUCCEED);
					esb.getEsbInfo().setReturnMsg("协同采购入库单成功");
					result.setCode(IReturnStatus.SUCCEED);
					esb.setResultInfo(result);
					
				}
			}
		}catch (Exception e) {
			result.setCode(IReturnStatus.ERROR);// 异常
			result.setError(WuYeWgptUtil.getExceptionDetail(e));
			result.setMessage(result.getError());
			WuYeWgptUtil.createResultEsbVO(esb);// 初始化响应对象
			esb.getEsbInfo().setReturnStatus(IReturnStatus.ESB_ERROR);
			esb.getEsbInfo().setReturnMsg("异常");
			esb.setResultInfo(result);// 设置响应内容
			ExceptionUtils.marsh(e);
			
			//wby 20220307 异常回滚事务
			new BaseDAO().executeUpdate("rollback");
		} finally {
			rsdata = com.alibaba.fastjson.JSONObject.toJSONString(esb);

			
			logVO.setNc_id(pk_bill);
			logVO.setOther_id(wgptbillcode + "");
			logVO.setBillno(billno);
			logVO.setTranstypecode("45");
			logVO.setItfcode("WGPT-NC-005");
			logVO.setBilldata(jsonobj == null ? "" : jsonobj.toString());
			logVO.setRsdata(rsdata);
			logVO.setMsg(result.getMessage());
			logVO.setIssuccess(IReturnStatus.SUCCEED.equals(result.getCode()) ? "Y" : "N");

			WuYeWgptUtil.getIWuYeWgptLogService().insertLog_RequiresNew(logVO);

		}
		return rsdata;
	}

	/**
	 * 获取一组VO的一列值,同时保证值不重复,排除null值 param CircularlyAccessibleValueObject[] vos,数据;
	 * param String field 获取字段的名称; return Object[] or null; 创建日期:2009-04-23
	 * 15:30:50
	 */
	public static Set<String> getVOsValueSet(
			CircularlyAccessibleValueObject[] vos, String field) {
		if (vos == null || vos.length <= 0) {
			return null;
		}
		Set<String> lvalue = new HashSet<String>();
		Object value = null;
		for (int i = 0; i < vos.length; i++) {
			value = vos[i].getAttributeValue(field);
			if (value == null) {
				continue;
			}
			lvalue.add(ValueUtils.getString(value));
		}
		if (lvalue.size() <= 0) {
			return null;
		}
		return lvalue;
	}

	/**
	 * 校验订单的退库数量是否超过入库数量
	 * @param view
	 */
	private boolean checkArrNum(OrderVO orderVO) {
		if (UFBoolean.TRUE.equals(orderVO.getHVO().getBrefwhenreturn())) {
			return true;
		}
		Map<String, Object[]> compareMap=new HashMap<String, Object[]>();

		for(int i=0;i<orderVO.getBVO().length;i++){
			UFDouble nnum = orderVO.getBVO()[i].getNnum();
			UFDouble naccumstorenum = orderVO.getBVO()[i].getNaccumstorenum();
			UFDouble nbackstorenum =ValueUtils.getUFDouble(orderVO.getBVO()[i].getNbackstorenum());
			UFDouble naccbacknum =MathTool.add(orderVO.getBVO()[i].getNbackarrvnum(), orderVO.getBVO()[i].getNbackstorenum());
			if(compareMap.containsKey(orderVO.getBVO()[i].getCrowno())){
				Object[] o =compareMap.get(orderVO.getBVO()[i].getCrowno());
				o[0]=MathTool.add(ValueUtils.getUFDouble(o[0]), nnum);
			}else{
				Object[] objects=new Object[]{MathTool.add(ValueUtils.getUFDouble(nnum), nbackstorenum),naccumstorenum};
				compareMap.put(orderVO.getBVO()[i].getCrowno(), objects);
			}

		}
		for (Entry<String, Object[]> entry : compareMap.entrySet()) {
			Object[] objects =entry.getValue();

			if (MathTool.compareTo(ValueUtils.getUFDouble(objects[0]), ValueUtils.getUFDouble(objects[1])) > 0) {
				return false;
			}
		}
		return true;
	}

}
