package nc.bs.arap.busireg;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import nc.bs.businessevent.BdUpdateEvent;
import nc.bs.businessevent.BusinessEvent;
import nc.bs.businessevent.IBusinessEvent;
import nc.bs.businessevent.IBusinessListener;
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.env.BSContext;
import nc.itf.uap.pf.IPfExchangeService;
import nc.jdbc.framework.processor.ColumnListProcessor;
import nc.pub.sap.constant.SapConstants;
import nc.util.mmf.framework.base.MMValueCheck;
import nc.util.mmf.framework.base.MMValueConvert;
import nc.util.uap.twxt.WYTwxtUtil;
import nc.vo.arap.payable.PayableBillItemVO;
import nc.vo.arap.payable.PayableBillVO;
import nc.vo.arap.receivable.AggReceivableBillVO;
import nc.vo.baseapp.jsontool.JsonTransfVOUtil;
import nc.vo.pub.AggregatedValueObject;
import nc.vo.pub.BusinessException;
import nc.vo.pub.JavaType;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.pubapp.AppContext;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;

public class RecbillApproveSendToNCListener implements IBusinessListener {

	@Override
	public void doAction(IBusinessEvent event) throws BusinessException {
		try {
			AggregatedValueObject[] billVo=getAggVO(event);
			UFBoolean isfromnc =MMValueConvert.toUFBoolean(InvocationInfoProxy.getInstance().getProperty("ISFROMNC"));
			if(!isfromnc.booleanValue()) {
				isfromnc=MMValueConvert.toUFBoolean(BSContext.getInstance().getSession("ISFROMNC"));
			}
			if(MMValueCheck.isNotEmpty(billVo) && !isfromnc.booleanValue()) {
				BaseDAO baseDAO =new BaseDAO();
				for(int i=0;i<billVo.length;i++) {
					AggReceivableBillVO vo =((AggReceivableBillVO) billVo[i]).clone();
					String  pk_tradetype=vo.getHeadVO().getPk_tradetype();
					if("F0-Cxx-D38".equals(pk_tradetype)){
						String sql="select cust.pk_customer from bd_customer cust inner join org_orgs o on cust.code=o.code where decode(UPPER(nvl(o.def1,'N')),'TRUE','Y',UPPER(nvl(o.def1,'N')))<>'Y' and o.isbusinessunit='Y'  and decode(UPPER(nvl(o.def13,'N')),'TRUE','Y',UPPER(nvl(o.def13,'N')))<>'Y'   and cust.pk_customer ='"+vo.getHeadVO().getCustomer()+"'";
						List<String> toncList=(List<String>) baseDAO.executeQuery(sql, new ColumnListProcessor());
						if(MMValueCheck.isNotEmpty(toncList) && toncList.contains(vo.getHeadVO().getCustomer())) {
							IPfExchangeService service =NCLocator.getInstance().lookup(IPfExchangeService.class);
							
							AggregatedValueObject changeValueObject =service.runChangeData("F0-Cxx-D38","F1", vo, null);
							HashMap<String,ArrayList<String>>	 hConfig = JsonTransfVOUtil.getFormulas("TWF1_HEAD",SapConstants.DIRECTION_NC2SAP);
							HashMap<String,ArrayList<String>>	 bConfig = JsonTransfVOUtil.getFormulas("TWF1_BODY",SapConstants.DIRECTION_NC2SAP);
							
							//获取表头公式
							List<String> hformulas = hConfig.get(SapConstants.FORMULA_KEY);
							List<String> hnc_field_code = hConfig.get(SapConstants.NC_FIELD_CODE);
							List<String> hsap_field_code = hConfig.get(SapConstants.SAP_FIELD_CODE);
							
							//获取表体公式
							List<String> bformulas = bConfig.get(SapConstants.FORMULA_KEY);
							List<String> bnc_field_code = bConfig.get(SapConstants.NC_FIELD_CODE);
							List<String> bsap_field_code = bConfig.get(SapConstants.SAP_FIELD_CODE);
							
							ExtFormulaParser extFormulaParser = new ExtFormulaParser();
							extFormulaParser.execFormulas(hformulas.toArray(new String[hformulas.size()]), bformulas.toArray(new String[bformulas.size()]), changeValueObject);
							
							HashMap<String, String> hTransMap=JsonTransfVOUtil.getTranNCcodes("TWF1_HEAD", SapConstants.DIRECTION_SAP2NC);//获取天问传NCC方向的配置
							HashMap<String, String> bTransMap=JsonTransfVOUtil.getTranNCcodes("TWF1_BODY", SapConstants.DIRECTION_SAP2NC);//获取天问传NCC方向的配置
							
							JSONObject reqJsonObject=new JSONObject();
							JSONObject header=new JSONObject();
							JSONArray bodyJsonArray=new JSONArray();
					        JSONObject bodyJson=null;
							PayableBillVO headvo=(PayableBillVO) changeValueObject.getParentVO();
							PayableBillItemVO[] items=(PayableBillItemVO[]) changeValueObject.getChildrenVO();
							Iterator<Entry<String, String>> it = hTransMap.entrySet().iterator();
					        while (it.hasNext()) {
					        	Entry<String, String> entry=it.next();
					        	header.put(entry.getKey(),MMValueConvert.toType(headvo.getAttributeValue(entry.getValue()), JavaType.String));
					        }
							
					        for(int b=0;b<items.length;b++) {
					        	bodyJson=new JSONObject();
					        	it = bTransMap.entrySet().iterator();
					        	while (it.hasNext()) {
						        	Entry<String, String> entry=it.next();
						        	bodyJson.put(entry.getKey(),MMValueConvert.toType(items[b].getAttributeValue(entry.getValue()), JavaType.String));
						        }
					        	bodyJsonArray.add(bodyJson);
					        }
					        reqJsonObject.put("Header", header);
					        reqJsonObject.put("Items", bodyJsonArray);
					        
					        String  reqData=WYTwxtUtil.getSendToEsbData(AppContext.getInstance().getServerTime().getMillis()+"", reqJsonObject);
							
							com.alibaba.fastjson.JSONObject ncresJsonObject=WYTwxtUtil.sendToESB(reqData,"TW-NC-FI-001_NCYF");

							com.alibaba.fastjson.JSONObject esbInfoJsonObject =ncresJsonObject.getJSONObject("esbInfo");
							com.alibaba.fastjson.JSONObject resultInfoJsonObject=ncresJsonObject.getJSONObject("resultInfo");

							Object returnStatus =esbInfoJsonObject.get("returnStatus");
							if(!"S".equals(returnStatus)) {
								ExceptionUtils.wrappBusinessException(resultInfoJsonObject.get("error").toString());
							}
						}
					}
				}
			}
		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException("内部交易应收单传递NC生成应付单报错:"+e.getMessage());
		}
	}
	private AggregatedValueObject[] getAggVO(IBusinessEvent event){
		AggregatedValueObject[] billvos = null;
		Object obj = null;
		if (event instanceof BusinessEvent) {
			BusinessEvent business = (BusinessEvent) event;
			obj = (AggregatedValueObject[]) business.getObject();
		} else if (event instanceof BdUpdateEvent) {
			BdUpdateEvent business = (BdUpdateEvent) event;
			obj = (AggregatedValueObject[]) business.getNewObject();
		}
		if (obj != null) {
			if (obj.getClass().isArray()) {
				billvos = (AggregatedValueObject[]) obj;
			} else {
				billvos = new AggregatedValueObject[] { (AggregatedValueObject) obj };
			}
			if (billvos == null || billvos.length == 0)
				return null;
		}
		return billvos;
	}
}
