package nc.bs.my.arap;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import nc.bs.arap.constant.PropertyFormularConstant;
import nc.bs.framework.common.NCLocator;
import nc.bs.logging.Logger;
import nc.bs.trade.business.HYPubBO;
import nc.itf.sap.log.IExtLogService;
import nc.itf.uap.pf.IPFBusiAction;
import nc.net.servlet.IReturnStatus;
import nc.pub.sap.constant.SapConstants;
import nc.vo.arap.payable.AggPayableBillVO;
import nc.vo.arap.payable.PayableBillItemVO;
import nc.vo.arap.payable.PayableBillVO;
import nc.vo.esb.EsbInfoVO;
import nc.vo.esb.QueryInfoVO;
import nc.vo.esb.ResultEsbVO;
import nc.vo.esb.ResultEsbVO_Arap;
import nc.vo.esb.ResultGuidVO;
import nc.vo.esb.ResultVO;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.sap.log.SapPurchaseLogVO;
import nc.vo.uap.busibean.exception.BusiBeanException;
import ncc.bs.arap.myutil.MYArapItfUtil;
import uap.json.JSONObject;
/**
 * @Description: My->NC F1-Cxx-W01
 * @author 徐刚【碧桂园my】
 * @date 2018-9-14
 * @version with NC V6.3
 */
public class MyArapWriteReceivablesBS {
	
	private String ITFTYPE = "NC-MY-PM-001";
//	//单据类型主键
//	private  String PK_BILLTYPEID = "0000Z3000000000000F0";  
//	//单据类型
//	private String PK_BILLTYPECODE = "F1";    
//	//交易类型主键
//	private String PK_TRADETYPEID = "1001H810000003BRY2YA";    
//	
//	//UUID 生成标识
//	private final String GUID = UUID.randomUUID().toString();   
	/**
	 * 交互时间精确到毫秒
	 */
	public static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
	public ResultEsbVO_Arap myArapWriteReceivablesBS(String key, String billdata,String postJson) {
		Logger.error("接口：nc.pubitf.sap.fi.ISapFi");
		Logger.error("业务类名：" + this.getClass().getName());
		Logger.error("业务类函数名：myarapinset");
		Logger.error("传入参数1 key：" + key);
		Logger.error("传入参数2 billdata：" + billdata);
		return doAction(key,billdata,postJson);
	}
	private ResultEsbVO_Arap doAction(String key, String billdata,String postJson) {
		//单据主键
		String billid = "";
		//组织
		String pk_org = "";
		//单据编码
		String billno="";
		//交易类型编码
		String pk_tradetype = "F1-Cxx-W01";
		
		// 返回json信息
		ResultEsbVO_Arap esbvo = new ResultEsbVO_Arap();
		ResultGuidVO sapResultVO = new ResultGuidVO();
		//wby 20211108 设置默认值 
		sapResultVO.setCode(IReturnStatus.ESB_SUCCEED_CODE);
		sapResultVO.setMessage("MY系统生成NC系统 应付成功");
		sapResultVO.setError("");
		AggPayableBillVO aggVO = null;
		try {
			Logger.info("应付单 校验传入的参数");
			if (!SapConstants.CHECK_KEY.equals(key)) {
				throw new Exception("key验证失败 ！");
			}
			if (billdata == null) {
				throw new Exception("应付单信息不能为空！");
			}
			// 参数非空校验 a.billdata不能为空校验【为空，则返回错误的json格式数据】
			JSONObject data = new JSONObject(billdata);
	
			aggVO = MYArapItfUtil.jsonToAggVO(data,AggPayableBillVO.class,PayableBillVO.class,PayableBillItemVO.class);
			sapResultVO.setGuid(aggVO.getHeadVO().getDef1());
			PayableBillItemVO[]  bvo = (PayableBillItemVO[]) aggVO.getChildrenVO();
			if ("02".equals(aggVO.getHeadVO().getDef39())) {
				for (int i = 0; i < bvo.length; i++) {
					bvo[i].setNotax_de(bvo[i].getMoney_de());
					bvo[i].setLocal_notax_de(bvo[i].getLocal_money_de()); 
				}
			}
			
			MYArapItfUtil.notNullCheckAndExFormula(PropertyFormularConstant.F1W01HEAD,PropertyFormularConstant.F1W01BODY, aggVO);
		    HYPubBO bo =new HYPubBO();
			String def1=(String) bo.findColValue("ap_payablebill", "def1", " nvl(dr,0)=0 and def1='"+aggVO.getHeadVO().getDef1()+"'");
			if (def1!=null && !"".equals(def1)) {
				throw new BusiBeanException("操作异常：MY-GUID重复-"+aggVO.getHeadVO().getDef1());
			}
			// 执行保存、提交、审批动作
			IPFBusiAction baService = NCLocator.getInstance().lookup(IPFBusiAction.class);
			
			pk_tradetype = aggVO.getHeadVO().getPk_tradetype();
			pk_org=aggVO.getHeadVO().getPk_org();
			if(pk_tradetype == null || "null".equals(pk_tradetype)) {
				ExceptionUtils.wrappBusinessException("pk_tradetype为空");
			}
			if(pk_org == null || "null".equals(pk_org)) {
				ExceptionUtils.wrappBusinessException("pk_org为空");
			}
			// 保存 creator
			baService.processAction("SAVE", pk_tradetype, null, aggVO, null,null);
			baService.processAction("COMMIT", pk_tradetype, null, aggVO, null,null);
			
			billid=aggVO.getHeadVO().getPk_payablebill();
			billno=aggVO.getHeadVO().getBillno();
			if(billid == null || "null".equals(billid)) {
				ExceptionUtils.wrappBusinessException("pk_tradetype为空");
			}
			if(billno == null || "null".equals(billno)) {
				ExceptionUtils.wrappBusinessException("billno为空");
			}
			//不需要核销
			//审批
			baService.processAction("APPROVE",pk_tradetype, null, aggVO, null, null);
//		    //核销---
//		    if(aggVO.getHeadVO().getDef71() != null && aggVO.getHeadVO().getDef71().length() > 0){
//				new ArapWsBillRegisterForBusiDataBO().doAction2(aggVO.getHeadVO(),aggVO.getHeadVO().getDef71());
//		    }
			
			//不需要核销
		    
			//构造新返回值
			esbvo.setPayablebillvo(aggVO.getHeadVO());
		} catch (Exception e) {
			// 组装异常日志信息
			Logger.debug("应付单同步失败 : " + e.getMessage());
			sapResultVO.setMessage("MY系统生成NC系统 应付失败");
			sapResultVO.setCode(IReturnStatus.ESB_FAILING_CODE);
			String message = e.getMessage() != null ? e.getMessage() : e.toString();
			sapResultVO.setError(message);
		} finally {
			// 插入日志
			try {
				//构建日志VO
				esbvo.setResultInfo(sapResultVO);
				createEsbVO(1, esbvo, new JSONObject(billdata), sapResultVO);// 创建响应对象 MDGToNcSupplierServelet.java  发送响应对象
				String issuccess_sn = "";
				if (IReturnStatus.ESB_SUCCEED_CODE.equals(sapResultVO.getCode())) {
					issuccess_sn = "Y";
				} else {
					issuccess_sn = "N";
				}
				List<SapPurchaseLogVO> logvo_list = new ArrayList<SapPurchaseLogVO>();
				SapPurchaseLogVO log = new SapPurchaseLogVO();
				log.setPk_org(ITFTYPE);
		    	log.setBillid(billid);
		    	log.setBillno(billno);
		    	log.setPk_billtypecode("F1");
		    	log.setPk_transtypecode(pk_tradetype);
		    	log.setSend_data_sn(postJson);
		    	//保存json构造
		    	ResultEsbVO rvo = new ResultEsbVO();
		    	rvo.setEsbInfo(esbvo.getEsbInfo());
		    	rvo.setQueryInfo(esbvo.getQueryInfo());
		    	rvo.setResultInfo(esbvo.getResultInfo());
		    	log.setResultdata_sn(com.alibaba.fastjson.JSONObject.toJSONString(rvo));
		    	// 保存json构造
		    	log.setMsg_sn(sapResultVO.getMessage()+sapResultVO.getError());
		    	log.setIssuccess_sn(issuccess_sn);
		    	log.setDef1(this.getClass().getName());
				IExtLogService logService=NCLocator.getInstance().lookup(IExtLogService.class);
				logService.insertLog_RequiresNew(log);
			} catch (Exception e) {
				Logger.debug("插入日志失败 : " + e.getMessage());
			}
		}
		return esbvo;
	}
	
	/**
	 * 创建ESB交互对象
	 * 
	 * @param newi
	 * @param esb
	 *            交互VO
	 * @return newi=0(请求对象)/newi=1(响应对象)
	 */
	@SuppressWarnings("rawtypes")
	public void createEsbVO(int newi,  ResultEsbVO_Arap esb,
			uap.json.JSONObject jsonobj, ResultVO resultvo) {
		uap.json.JSONObject esbinfo = jsonobj.getJSONObject("esbInfo");
		Date date = Calendar.getInstance().getTime();// 获取当前时间
		EsbInfoVO esbInfo = new EsbInfoVO();
		esbInfo.setReturnCode(resultvo.getCode());
		esbInfo.setInstId(esbinfo.getString("instId"));
		esbInfo.setReturnMsg(resultvo.getMessage());
		// 获取数据
		QueryInfoVO queryInfo = new QueryInfoVO();
		queryInfo.setTotalPage("");// 默认总页数为 1
		queryInfo.setCurrentPage("");// 默认当前页数为 1
		if (newi == 0) {// 设置请求时间
			esbInfo.setRequestTime(dateFormat.format(date));
		} else {// 设置响应时间
			esbInfo.setRequestTime(dateFormat.format(date));
			esbInfo.setResponseTime(dateFormat.format(date));
			if (IReturnStatus.ESB_SUCCEED_CODE.equals(resultvo.getCode())) {
				esbInfo.setReturnStatus(IReturnStatus.ESB_SUCCEED);// 响应成功
			} else if (IReturnStatus.ESB_ERROR_CODE.equals(resultvo.getCode())) {
				esbInfo.setReturnStatus(IReturnStatus.ESB_ERROR);// 响应异常
			} else {
				esbInfo.setReturnStatus(IReturnStatus.ESB_FAILING);// 响应失败
			}
		}
		esb.setEsbInfo(esbInfo);
		esb.setQueryInfo(queryInfo);
	}
}
