package nc.bs.arap.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import com.alibaba.fastjson.JSONObject;

import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.NCLocator;
import nc.bs.logging.Logger;
import nc.bs.uap.tools.formula.ExtFormulaParser;
import nc.itf.uap.IUAPQueryBS;
import nc.itf.ws.esb.IEsbDAO;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.pub.sap.constant.SapConstants;
import nc.pubitf.para.SysInitQuery;
import nc.util.mmf.framework.base.MMCollectionUtil;
import nc.util.mmf.framework.base.MMValueCheck;
import nc.util.uap.twxt.WYTwxtUtil;
import nc.vo.arap.receivable.AggReceivableBillVO;
import nc.vo.arap.receivable.ReceivableBillItemVO;
import nc.vo.baseapp.jsontool.JsonTransfVOUtil;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.pub.lang.UFDate;
import nc.vo.pubapp.AppContext;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.sap.log.SapFinanceLogVO;
import nc.vo.ws.esb.EsbinfoVO;

/**
 * 
 * @author 符耀铭
 * @date 2020年10月27日
 * @description 应收单传递SAP工具类
 */
public class ARRecbillSendTOSAPUtil {
	private static String PK_BILLTYPEID = "0000Z3000000000000F0";
	private static String PK_BILLTYPECODE = "F0";
	private static String PK_TRADETYPE = "";
	private static String PK_TRANSTYPEID ="";
	private	static String PK_ORG= "";
	private	static String BILLNO= "";
	private static String BILLID = "";
	private static String JSON =  "";
	private static String RETURNMSG = "";
	private static String RESULT="";
	private static String ISSUCCESS_NS="";

	//存放传递SAP的单据交易类型
	private static List<String> sendSapBilltype=Arrays.asList(new String[] {"F0-Cxx-D38","F0-Cxx-D39"});

	private static IUAPQueryBS queryBS=null;

	public static IUAPQueryBS getQueryBS() {
		if(null==queryBS) {
			queryBS=NCLocator.getInstance().lookup(IUAPQueryBS.class);
		}
		return queryBS;
	}

	public static void sendTOSAP(AggReceivableBillVO[] vos) throws BusinessException{
		if(MMValueCheck.isNotEmpty(vos)) {
			//以下交易类型才传SAP：F0-Cxx-D38、F0-Cxx-D39
			String s =SysInitQuery.getParaString("GLOBLE00000000000000","CALLSAP");
			if(MMValueCheck.isNotEmpty(s)) {
				MMCollectionUtil.addArrayToCollection(sendSapBilltype, s.split(","));
			}
			for(AggReceivableBillVO vo:vos) {
				boolean isSendSAP=isSendBS(vo);
				if(isSendSAP) {
					doAction(vo);
				}
			}
		}
	}

	private static boolean isSendBS(AggReceivableBillVO billVO) throws BusinessException {
		
		if(sendSapBilltype.contains(billVO.getHeadVO().getPk_tradetype())) {
			StringBuffer sbSql = new StringBuffer();
			sbSql.append("select nvl(o.def13,'NONE')||'#'||nvl(o.def14,'NONE') from  org_orgs o ");
			sbSql.append(" left join bd_customer r on r.pk_financeorg= o.pk_org ");
			sbSql.append(" where nvl(o.dr,0)=0 and nvl(o.def14,'~')!='~' ");
			sbSql.append(" and o.islastversion= 'Y 'and  r.custprop='1' ");
			sbSql.append(" and r.pk_customer= '"+billVO.getHeadVO().getCustomer()+"' ");
			Object object=getQueryBS().executeQuery(sbSql.toString(), new ColumnProcessor());
			if(MMValueCheck.isNotEmpty(object)) {
				String[] spStrings =object.toString().split("#");

				if(new UFBoolean(spStrings[0]).booleanValue()&&(billVO.getHeadVO().getBilldate().isSameDate(new UFDate(spStrings[1])) || billVO.getHeadVO().getBilldate().after(new UFDate(spStrings[1])))) {
					return true;
				}
			}
		}
		return false;
	}
	private static void doAction(AggReceivableBillVO aggVO) throws BusinessException{
		PK_ORG=aggVO.getHeadVO().getPk_org();
		BILLNO=aggVO.getHeadVO().getBillno();
		BILLID = aggVO.getHeadVO().getPk_recbill();
		PK_TRADETYPE = aggVO.getHeadVO().getPk_tradetype();
		PK_TRANSTYPEID= aggVO.getHeadVO().getPk_tradetypeid();

		HashMap<String,ArrayList<String>>	 hFormulaone = JsonTransfVOUtil.getFormulas("F0-Cxx-D38D39_head",SapConstants.DIRECTION_NC2SAP);
		HashMap<String,ArrayList<String>>	 bFormulaone = JsonTransfVOUtil.getFormulas("F0-Cxx-D38D39_body",SapConstants.DIRECTION_NC2SAP);
		if(hFormulaone==null){
			return;
		}
		try {
			JSONObject is_esbinfo= new JSONObject();
			JSONObject is_queryinfo= new JSONObject(); 
			JSONObject abroad= new JSONObject(); 
			JSONObject header= new JSONObject(); 

			List<JSONObject> items = new ArrayList<JSONObject>();
			JSONObject json= new JSONObject();
			//获取表头公式
			List<String> hformulas = hFormulaone.get(SapConstants.FORMULA_KEY);
			List<String> hnc_field_code = hFormulaone.get(SapConstants.NC_FIELD_CODE);
			List<String> hsap_field_code = hFormulaone.get(SapConstants.SAP_FIELD_CODE);

			//获取表体公式
			List<String> bformulas = bFormulaone.get(SapConstants.FORMULA_KEY);
			List<String> bnc_field_code = bFormulaone.get(SapConstants.NC_FIELD_CODE);
			List<String> bsap_field_code = bFormulaone.get(SapConstants.SAP_FIELD_CODE);
			//执行公式
			ExtFormulaParser extFormulaParser = new ExtFormulaParser();
			extFormulaParser.execFormulas(hformulas.toArray(new String[0]),bformulas.toArray(new String[0]),aggVO);
			String[] nodeKeys,vals;
			String nodeKey;
			Object val;
			//esbinfo
			nodeKeys = new String[]{"instId","requestTime","attr1","attr2","attr3"};
			vals = new String[]{"D01S003-SAPFIDOMESTIC-1804-001-"+System.currentTimeMillis(),AppContext.getInstance().getServerTime().toString(),"","",""};
			for (int i = 0; i < nodeKeys.length; i++) {
				is_esbinfo.put(nodeKeys[i], vals[i]);
			}
			//queryinfo
			nodeKeys = new String[]{"pageSize","currentPage"};
			vals = new String[]{"1","1"};
			for (int i = 0; i < nodeKeys.length; i++) {
				is_queryinfo.put(nodeKeys[i], vals[i]);
			}	
			//requestinfo Header
			nodeKeys = hsap_field_code.toArray(new String[0]);
			for (int i = 0; i < nodeKeys.length; i++) {
				String renodeKey = nodeKeys[i];
				nodeKey = hnc_field_code.get(i);
				val = aggVO.getHeadVO().getAttributeValue(nodeKey);
				val = val == null?"":val; 
				header.put(renodeKey, val); 
			}
			//requestinfo item

			nodeKeys = bsap_field_code.toArray(new String[0]);
			ReceivableBillItemVO[] bvo = (ReceivableBillItemVO[]) aggVO.getTableVO("recitem");
			for (int i = 0; i < bvo.length; i++) {
				JSONObject item= new JSONObject();;
				for (int j = 0; j < nodeKeys.length; j++) {
					String renodeKey = nodeKeys[j];
					nodeKey = bnc_field_code.get(j);
					val = aggVO.getTableVO("recjtem")[i].getAttributeValue(nodeKey);	
					val = val == null?"":val;
					item.put(renodeKey, val);
				}
				items.add(item);  
			}
			json.put("esbInfo", is_esbinfo);
			json.put("queryInfo", is_queryinfo);
			abroad.put("Item", items);
			abroad.put("Header", header);
			json.put("requestInfo", abroad);
			JSON=json.toString();
			IEsbDAO service = NCLocator.getInstance().lookup(IEsbDAO.class);
			EsbinfoVO[] esbinfos = (EsbinfoVO[]) service.findESB("code='NC-SAP-ARAP-001'");
			String url = esbinfos[0].getUrl();
			String code = esbinfos[0].getCode();
			Logger.error("==============开始打印请求对象 ==============");
			Logger.error(json);
			Logger.error("==============结束打印请求对象==============");
			JSONObject result=WYTwxtUtil.sendJsonPost(url,json.toString(),code);
			Logger.error("==============开始打印响应对象==============");
			Logger.error(result);
			Logger.error("==============结束打印响应对象 ==============");
			if(result==null){
				ExceptionUtils.wrappBusinessException("SAP ERROR:"+"返回响应信息为空");
			}
			JSONObject objs = result.getJSONObject("esbInfo");
			RESULT=result.toString();
			ISSUCCESS_NS="是";
			RETURNMSG = objs.get("returnMsg").toString();
			if (!objs.get("returnStatus").toString().equals("S")) {
				ISSUCCESS_NS="否";
				ExceptionUtils.wrappBusinessException("SAP错误信息："+objs.get("returnMsg").toString());
			}
		} catch (Exception e) {
			RESULT="应收单传递SAP出错："+e.getMessage();
			ISSUCCESS_NS="否";
			ExceptionUtils.wrappBusinessException("应收单传递SAP出错："+e.getMessage());
		}finally {
			String ITFTYPE = "NC传递SAP费用协同";
			String GUID = UUID.randomUUID().toString();
			try {
				if("是".equals(ISSUCCESS_NS)){
					BaseDAO dao =new BaseDAO();
					dao.executeUpdate("update ar_recbill set def7='Y', def8='N',def9='N' where pk_recbill='"+aggVO.getHeadVO().getPk_recbill()+"'");
				}
				SapFinanceLogVO logVO = new SapFinanceLogVO();
				logVO.setPk_group(SapConstants.GROUPID);
				logVO.setPk_org(PK_ORG);
				logVO.setBillid(BILLID);
				logVO.setBillno(BILLNO);
				logVO.setPk_billtypeid(PK_BILLTYPEID);
				logVO.setPk_billtypecode(PK_BILLTYPECODE);
				logVO.setPk_transtypeid(PK_TRANSTYPEID);
				logVO.setPk_transtypecode(PK_TRADETYPE);
				logVO.setSend_data_ns(JSON);
				logVO.setSend_data_sn(null);
				logVO.setResultdata_ns(RESULT);
				logVO.setMsg_ns(RETURNMSG);
				logVO.setResultdata_sn(null);
				logVO.setMsg_sn(null);
				logVO.setIssuccess_ns(ISSUCCESS_NS);
				logVO.setIssuccess_sn(null);
				logVO.setDef1(ITFTYPE);
				logVO.setDef2(GUID);
				WYTwxtUtil.getIWuYeTwxtLogService().insertLog_RequiresNew(logVO);
			} catch (Exception e) {
				Logger.debug("插入日志失败 : " + e.getMessage());
			}
		}
	}
}
