package nc.bs.uap.twxt.process;

import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.resa.sql.SqlUtil;
import nc.bs.uap.lock.PKLock;
import nc.impl.pubapp.env.BSContext;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.net.servlet.IReturnStatus;
import nc.pubitf.arap.receivable.IArapReceivableBillPubQueryService;
import nc.util.mmf.framework.base.MMVOUtil;
import nc.util.mmf.framework.base.MMValueConvert;
import nc.util.uap.twxt.WYTwxtUtil;
import nc.vo.arap.receivable.AggReceivableBillVO;
import nc.vo.arap.receivable.ReceivableBillItemVO;
import nc.vo.arap.receivable.ReceivableBillVO;
import nc.vo.baseapp.jsontool.JsonTransfVOUtil;
import nc.vo.baseapp.jsontool.ParamVO;
import nc.vo.esb.ResultEsbVO;
import nc.vo.esb.ResultVO;
import nc.vo.pub.BusinessException;
import nc.vo.pubapp.pattern.data.ValueUtils;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.twxt.log.WYTwxtLogVO;
import uap.json.JSONObject;

/**
 * @Description: 【天文系统->NC】天问应收单同步到NC
 * 
 * @author 周蓝萍 【碧桂园-物业板块-天问系统接口】
 * @date 2019-04-12
 * @version with NC V6.3
 */
public class WriteRecBillInfoProcess {

	public String writeRecBillInfo(JSONObject jsonobj) throws BusinessException {
		String rsdata = null;
		ResultVO result = new ResultVO();
		//		result.setResult("");
		ResultEsbVO<ResultVO> esb = new ResultEsbVO<ResultVO>();
		esb.setResultInfo(result);
		Object pk_bill = null;//唯一标识
		AggReceivableBillVO aggVO = null;
		String pk_tradetype = null;
		Object twid=null;
		try {
			if (jsonobj == null || "".equals(jsonobj.toString())) {// 无Post提交值
				result.setCode(IReturnStatus.FAILING);// 失败
				result.setMessage("Post所提交请求Json格式错误或者无值!");
				WYTwxtUtil.createResultEsbVO(esb);
				esb.getEsbInfo().setReturnStatus(IReturnStatus.ESB_FAILING);
				esb.getEsbInfo().setReturnMsg("失败");
				esb.setResultInfo(result);
			} else {
				jsonobj.toString().getBytes("utf-8");
				JSONObject requestInfo = (JSONObject) jsonobj.get("requestInfo");
				if (requestInfo == null){
					throw new Exception("应收单信息不能为空！");
				}
				JSONObject headerJsonObject =requestInfo.getJSONObject("Header");
				twid =headerJsonObject.get("def41");

				String sql="select count(def1) from ar_recbill where def1 = '"+twid+"' and nvl(dr, 0) = 0";

				BaseDAO baseDAO=new BaseDAO();
				Object count=baseDAO.executeQuery(sql, new ColumnProcessor());

				if(ValueUtils.getInt(count)>0){
					ExceptionUtils.wrappBusinessException("NC系统已存在天问系统单据ID:"+twid+"的单据,请勿重复传递！");
				}

				ParamVO paramVO=new ParamVO();
				paramVO.setAggVOClass(AggReceivableBillVO.class);
				paramVO.setHeadVOClass(ReceivableBillVO.class);
				paramVO.setBodyVOClass(ReceivableBillItemVO.class);
				paramVO.setBilldata(requestInfo.toString());
				paramVO.sethCfgCode("TWF0_HEAD");
				paramVO.setBfgCode("TWF0_BODY");

				AggReceivableBillVO receivableBillVO=JsonTransfVOUtil.json2AggVO(paramVO);
				// 转换前非空校验、执行公式、翻译后各项非空校验
				JsonTransfVOUtil.notNullCheckAndExFormula("TWF0_HEAD", "TWF0_BODY", receivableBillVO);
				pk_tradetype=receivableBillVO.getHeadVO().getPk_tradetype();
				String actionName="SAVE";
				sql="select nvl(sup.def10,'NONE') from  bd_customer r left join bd_supplier sup on r.pk_supplier=sup.pk_supplier where nvl(r.dr,0)=0  and  "+SqlUtil.buildInSql("r.pk_customer", MMVOUtil.getStrValue(receivableBillVO.getBodyVOs(), "customer"), true);
				Object  isonlinesap= baseDAO.executeQuery(sql, new ColumnProcessor());
				sql="SELECT oo.DEF1 FROM BD_CUSTOMER bc LEFT JOIN ORG_ORGS oo ON bc.code = oo.code WHERE oo.ISBUSINESSUNIT='Y' and  nvl(bc.DR,0)=0 AND nvl(oo.DR,0)=0 and "+SqlUtil.buildInSql("bc.pk_customer", MMVOUtil.getStrValue(receivableBillVO.getBodyVOs(), "customer"), true);
				Object isonlinencc=baseDAO.executeQuery(sql, new ColumnProcessor());
				if("F0-Cxx-D38".equals(pk_tradetype)) {
					if(MMValueConvert.toUFBoolean(isonlinesap).booleanValue()) {
						BSContext.getInstance().setSession("issapconfirm", "Y");
						InvocationInfoProxy.getInstance().setProperty("issapconfirm", "Y");
						actionName="SAVETEMP";
					}
					if(!MMValueConvert.toUFBoolean(isonlinencc).booleanValue()) {
						actionName="SAVETEMP";
					}
				}
				
				WYTwxtUtil.getIPFBusiAction().processAction(actionName, receivableBillVO.getHeadVO().getPk_tradetype(), null, receivableBillVO, null, null);
				pk_bill=receivableBillVO.getPrimaryKey();
				PKLock.getInstance().releaseDynamicLocks();
				PKLock.getInstance().releaseLock(pk_bill.toString(), InvocationInfoProxy.getInstance().getUserId(), InvocationInfoProxy.getInstance().getUserDataSource());

				if("F0-Cxx-D38".equals(pk_tradetype) && (MMValueConvert.toUFBoolean(isonlinesap).booleanValue()||!MMValueConvert.toUFBoolean(isonlinencc).booleanValue())){
						result.setCode(IReturnStatus.SUCCEED);// 成功
						com.alibaba.fastjson.JSONObject resJsonObject=new com.alibaba.fastjson.JSONObject();
						resJsonObject.put("billno", receivableBillVO.getHeadVO().getBillno());
						result.setResult(resJsonObject);
						result.setMessage("天问系统同步NCC内部交易应收单成功");
						WYTwxtUtil.createResultEsbVO(esb);
						esb.setResultInfo(result);
						rsdata =com.alibaba.fastjson.JSONObject.toJSONString(esb);
						return rsdata;
				}
				IArapReceivableBillPubQueryService service=NCLocator.getInstance().lookup(IArapReceivableBillPubQueryService.class);
				receivableBillVO=service.findBillByPrimaryKey(new String[]{pk_bill.toString()})[0];
				PKLock.getInstance().releaseLock(pk_bill.toString(), InvocationInfoProxy.getInstance().getUserId(), InvocationInfoProxy.getInstance().getUserDataSource());
				receivableBillVO.getHeadVO().setApprovedated(receivableBillVO.getHeadVO().getBilldate());
				InvocationInfoProxy.getInstance().setBizDateTime(receivableBillVO.getHeadVO().getBilldate().getMillis());
				WYTwxtUtil.getIPFBusiAction().processAction("APPROVE", receivableBillVO.getHeadVO().getPk_tradetype(), null,receivableBillVO, null, null);

				result.setCode(IReturnStatus.SUCCEED);// 成功
				com.alibaba.fastjson.JSONObject resJsonObject=new com.alibaba.fastjson.JSONObject();
				resJsonObject.put("billno", receivableBillVO.getHeadVO().getBillno());
				result.setResult(resJsonObject);
				result.setMessage("天问系统同步NCC应收单成功");
				WYTwxtUtil.createResultEsbVO(esb);
				esb.setResultInfo(result);
			}
		} catch (Exception e) {
			result.setCode(IReturnStatus.ERROR);// 异常
			result.setError(e.getMessage());
			result.setMessage(WYTwxtUtil.getExceptionDetail(e));
			WYTwxtUtil.createResultEsbVO(esb);// 初始化响应对象
			esb.getEsbInfo().setReturnStatus(IReturnStatus.ESB_ERROR);
			esb.getEsbInfo().setReturnMsg("异常");
			esb.setResultInfo(result);// 设置响应内容
//			ExceptionUtils.marsh(e);
		} finally {
			rsdata = com.alibaba.fastjson.JSONObject.toJSONString(esb);
			WYTwxtLogVO logVO=new WYTwxtLogVO();

			logVO.setNc_id(pk_bill+"");
			logVO.setOther_id(twid + "");
			logVO.setBillno("");
			logVO.setTranstypecode(pk_tradetype);
			logVO.setItfcode("TW-NC-FI-001");
			logVO.setItfname("【物业天问接口】新增应收计提/应收单");
			logVO.setBilldata(jsonobj == null ? "" : jsonobj.toString());
			logVO.setRsdata(rsdata);
			logVO.setMsg(null);
			logVO.setIssuccess(IReturnStatus.SUCCEED.equals(result.getCode()) ? "Y" : "N");
			WYTwxtUtil.getIWuYeTwxtLogService().insertLog_RequiresNew(logVO);
		}
		return rsdata;
	}
}
