package nc.bs.cmp.settlement.listener;

import com.alibaba.fastjson.JSONObject;

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.logging.Logger;
import nc.cmp.utils.SettleUtils;
import nc.impl.pubapp.env.BSContext;
import nc.itf.pu.m21.IOrderClose;
import nc.itf.pu.m21.IOrderQuery;
import nc.util.mmf.framework.base.MMStringUtil;
import nc.util.mmf.framework.base.MMValueCheck;
import nc.util.uap.wgpt.WuYeWgptUtil;
import nc.vo.arap.pay.AggPayBillVO;
import nc.vo.cmp.settlement.SettlementAggVO;
import nc.vo.pu.m21.entity.OrderVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.pub.lang.UFDouble;
import nc.vo.pubapp.AppContext;
import nc.vo.pubapp.pattern.data.ValueUtils;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.tmpub.util.DateUtil;
import nc.vo.wgpt.log.WuYeWgptLogVO;
import ncc.pub.wywgpt.utils.WyWGPTUtils;

public class WYCGPaybillRedSettleWriteListener implements IBusinessListener {

	@Override
	public void doAction(IBusinessEvent event) throws BusinessException {
		WuYeWgptLogVO logVO = new WuYeWgptLogVO();
		logVO.setItfcode("NC-WGPT-PU-003");
		logVO.setTranstypecode("F3");
		logVO.setItfname("物业采购红冲付款单结算回写付款信息");
		StringBuilder sb=new StringBuilder();

		if(event instanceof BusinessEvent) {
			logVO.setIssuccess(UFBoolean.TRUE.toString());
			BusinessEvent updateEvent1 = (BusinessEvent)event;
			Object obj1 = updateEvent1.getObject();
			//zhoulpc B组织的红字付款单审批通过后同样需要关闭对应采购订单并回传信息通知碧彩商城
			if("CMPsettleAfter".equals(updateEvent1.getEventType()) || "1020".equals(updateEvent1.getEventType())){//事件类型编码
				if(obj1 instanceof SettlementAggVO[]) {
					String esbResultinfoStr = null;
					JSONObject requestInfo=new JSONObject();
					SettlementAggVO[] settlementAggVOs = (SettlementAggVO[])((SettlementAggVO[])updateEvent1.getObject());
					String billType =SettleUtils.getbilltype(MMStringUtil.toNotNullValue(ValueUtils.getString(settlementAggVOs[0].getParentVO().getAttributeValue("pk_tradetype"))), AppContext.getInstance().getPkGroup());

					if("F3".equals(billType)) {
						Object object =SettleUtils.getBuisAggVO(MMStringUtil.toNotNullValue(ValueUtils.getString(settlementAggVOs[0].getParentVO().getAttributeValue("pk_tradetype"))), MMStringUtil.toNotNullValue(ValueUtils.getString(settlementAggVOs[0].getParentVO().getAttributeValue("pk_busibill"))), AppContext.getInstance().getPkGroup());

						if(MMValueCheck.isNotEmpty(object)){
							AggPayBillVO aggPayBillVO= (AggPayBillVO) object;

							UFBoolean isRed =ValueUtils.getUFBoolean(aggPayBillVO.getHeadVO().getDef46());

							String wgptPoNo=aggPayBillVO.getHeadVO().getDef47();
							UFDouble money = aggPayBillVO.getHeadVO().getMoney();
							if(isRed.booleanValue() && (money == null || money.compareTo(UFDouble.ZERO_DBL) <= 0) && MMStringUtil.isNotEmpty(wgptPoNo) && "21".equals(aggPayBillVO.getBodyVOs()[0].getTop_billtype())) {
								
								IOrderClose closeService = NCLocator.getInstance().lookup(IOrderClose.class);
								IOrderQuery iOrderQuery=NCLocator.getInstance().lookup(IOrderQuery.class);
								
								OrderVO[] orderVOs =iOrderQuery.queryOrderVOsByIds(new String[] {aggPayBillVO.getBodyVOs()[0].getTop_billid()}, UFBoolean.FALSE);
								InvocationInfoProxy.getInstance().setProperty("isncredpay", UFBoolean.TRUE.toString());
								BSContext.getInstance().setSession("isncredpay", UFBoolean.TRUE.toString());
								
								closeService.close(orderVOs, 0, true);
								
								requestInfo.put("method", "sendRefundMsg");
								requestInfo.put("orderProviderNo", wgptPoNo);
								requestInfo.put("refundFormId", aggPayBillVO.getHeadVO().getDef48());
								requestInfo.put("refundState", Integer.parseInt(settlementAggVOs[0].getParentVO().getAttributeValue("settlestatus").toString())==5?"1":"0");
								requestInfo.put("refundMsg", "NC退款成功");

								String sendJsonData =WyWGPTUtils.getSendToEsbData("NC-WGPT-PU-003"+DateUtil.getCurrTime().getMillis(), requestInfo);
								logVO.setBilldata(requestInfo.toString());
								//发送请求
								try {
									aggPayBillVO.getHeadVO().setDef41(UFBoolean.TRUE.toString());
									JSONObject esbResultinfo = WyWGPTUtils.sendToESB(sendJsonData,"NC-WGPT-PU-003");
									if(esbResultinfo!=null){
										esbResultinfoStr = esbResultinfo.toString();
										sb.append("返回报文："+esbResultinfoStr);
										logVO.setRsdata(esbResultinfoStr);
										Logger.error("【红冲付款单结算回写付款信息接口】请求参数："+sendJsonData+"；\r\n返回参数："+esbResultinfoStr);
										JSONObject esbInfo = (JSONObject)esbResultinfo.get("esbInfo");
										if(esbInfo!=null){
											//接口返回状态：S（成功）/W（警告）/E（错误）
											String returnStatus = esbInfo.get("returnStatus")+"";
											returnStatus = "E".equals(returnStatus)?"否":"是";
											if("否".equals(returnStatus)){
												String returnMsg = esbInfo.get("returnMsg")+"";
												ExceptionUtils.wrappBusinessException("接口错误："+returnMsg);
											}
										}
										JSONObject resultInfo = esbResultinfo.getJSONObject("resultInfo");
										Object success = resultInfo.get("success");
										if(!ValueUtils.getUFBoolean(success).booleanValue()){
											Object result = resultInfo.get("result");
											ExceptionUtils.wrappBusinessException("碧彩商城提示:"+result);
										}
									}
								} catch (Exception e) {
									aggPayBillVO.getHeadVO().setDef41(UFBoolean.FALSE.toString());
									logVO.setIssuccess(UFBoolean.FALSE.toString());
									sb.append(WuYeWgptUtil.getExceptionDetail(e));
									ExceptionUtils.wrappBusinessException("异常：\n"+e.getMessage()+"\n请求报文：\n"+sendJsonData+"\n返回报文：\n"+esbResultinfoStr);
								}finally{
									BaseDAO baseDAO=new BaseDAO();
									baseDAO.updateVO(aggPayBillVO.getHeadVO(), new String[] {"def41"});
									logVO.setMsg(sb.toString());
									WuYeWgptUtil.getIWuYeWgptLogService().insertLog_RequiresNew(logVO);
								}
							}
						}
					}
				}
			}
		}
	}

}
