package nc.bs.uap.twxt.process;

import com.alibaba.fastjson.JSONObject;

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.boss.process.BossWriteRecBIllInfo;
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.pubitf.para.SysInitQuery;
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;

/**
 * 中台,boss系统应收单写入实现
 * 
 * @author xuy
 * @date 2022-04-15
 * 
 */
public class BossWriteRecBillInfoProcess implements BossWriteRecBIllInfo {

	/**
	 * 
	 * Boss系统实现
	 */
	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 bossid = 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");
				bossid = headerJsonObject.get("bossid");

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

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

				if (ValueUtils.getInt(count) > 0) {
					result.setCode(IReturnStatus.SUCCEED);// 成功
					com.alibaba.fastjson.JSONObject resJsonObject = new com.alibaba.fastjson.JSONObject();
					resJsonObject.put("billno", null);
					result.setResult(resJsonObject);
					result.setMessage("Boss系统同步NCC应收单成功");
					WYTwxtUtil.createResultEsbVO(esb);
					esb.setResultInfo(result);
					rsdata = com.alibaba.fastjson.JSONObject.toJSONString(esb);
					return rsdata;
				}

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

				AggReceivableBillVO receivableBillVO = JsonTransfVOUtil.json2AggVO(paramVO);
				// 转换前非空校验、执行公式、翻译后各项非空校验
				JsonTransfVOUtil.notNullCheckAndExFormula("bossF0_HEAD", "bossF0_BODY", receivableBillVO);
				pk_tradetype = receivableBillVO.getHeadVO().getPk_tradetype();
				receivableBillVO.getHeadVO().setDef1(null == bossid ? null : bossid.toString());// 设置ztid到def1
				String actionName = "SAVE";
				sql = "select o.def13 from bd_customer cust inner join org_orgs o on cust.code=o.code where o.isbusinessunit='Y' and  "
						+ SqlUtil.buildInSql("cust.pk_customer",
								MMVOUtil.getStrValue(receivableBillVO.getBodyVOs(), "customer"), true);
				Object isonlinesap = baseDAO.executeQuery(sql, new ColumnProcessor());
				if ("F0-Cxx-D38".equals(pk_tradetype) && MMValueConvert.toUFBoolean(isonlinesap).booleanValue()) {
					BSContext.getInstance().setSession("issapconfirm", "Y");
					InvocationInfoProxy.getInstance().setProperty("issapconfirm", "Y");
				}
				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());
				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("Boss系统同步NCC应收单成功");
				WYTwxtUtil.createResultEsbVO(esb);
				esb.setResultInfo(result);
			}
		} catch (Exception e) {
			result.setCode(IReturnStatus.ERROR);// 异常
			result.setError(WYTwxtUtil.getExceptionDetail(e));
			result.setMessage(null == bossid ? null : bossid.toString()+":"+e.getMessage());
			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(bossid + "");
			logVO.setBillno("");
			logVO.setTranstypecode(pk_tradetype);
			logVO.setItfcode("BO-NC-FI-001");
			logVO.setItfname("【物业Boss接口】新增应收计提/应收单");
			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;
	}

	/**
	 * 
	 * 中台系统实现
	 */
	public String writeRecBillInfo2(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 ztid = null;
		String def28=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 = jsonobj.getJSONObject("requestInfo");
				if (requestInfo == null) {
					throw new Exception("应收单信息不能为空！");
				}
				InvocationInfoProxy.getInstance().setGroupId(SysInitQuery.getParaString("GLOBLE00000000000000", "GROUP"));
				InvocationInfoProxy.getInstance().setUserId(SysInitQuery.getParaString("GLOBLE00000000000000", "ITFZTUSER"));
				JSONObject headerJsonObject = requestInfo.getJSONObject("Header");
				ztid = headerJsonObject.get("ztId");
				def28=headerJsonObject.getString("def28");
				String sql = "select count(def1) from ar_recbill where def1 = '" + ztid + "' and nvl(dr, 0) = 0";

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

				if (ValueUtils.getInt(count) > 0) {
					result.setCode(IReturnStatus.SUCCEED);// 成功
					com.alibaba.fastjson.JSONObject resJsonObject = new com.alibaba.fastjson.JSONObject();
					resJsonObject.put("billno", null);
					result.setResult(resJsonObject);
					result.setMessage("中台系统同步NCC应收单成功");
					WYTwxtUtil.createResultEsbVO(esb);
					esb.setResultInfo(result);
					rsdata = com.alibaba.fastjson.JSONObject.toJSONString(esb);
					return rsdata;
				}

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

				AggReceivableBillVO receivableBillVO = JsonTransfVOUtil.json2AggVO(paramVO);
				// 转换前非空校验、执行公式、翻译后各项非空校验
				JsonTransfVOUtil.notNullCheckAndExFormula("ZTF0_HEAD", "ZTF0_BODY", receivableBillVO);
				pk_tradetype = receivableBillVO.getHeadVO().getPk_tradetype();
				receivableBillVO.getHeadVO().setDef1(null == ztid ? null : ztid.toString());// 设置ztid到def1
				String actionName = "SAVE";
				sql = "select o.def13 from bd_customer cust inner join org_orgs o on cust.code=o.code where o.isbusinessunit='Y' and  "
						+ SqlUtil.buildInSql("cust.pk_customer",
								MMVOUtil.getStrValue(receivableBillVO.getBodyVOs(), "customer"), true);
				Object isonlinesap = baseDAO.executeQuery(sql, new ColumnProcessor());
				if ("F0-Cxx-D38".equals(pk_tradetype) && MMValueConvert.toUFBoolean(isonlinesap).booleanValue()) {
					BSContext.getInstance().setSession("issapconfirm", "Y");
					InvocationInfoProxy.getInstance().setProperty("issapconfirm", "Y");
				}
				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());
				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(WYTwxtUtil.getExceptionDetail(e));
			result.setMessage(null == def28 ? null : def28.toString()+":"+e.getMessage());
			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(ztid + "");
			logVO.setBillno("");
			logVO.setTranstypecode(pk_tradetype);
			logVO.setItfcode("ZT-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;
	}

}
