package nc.bs.arap.busireg;

import com.alibaba.fastjson.JSONObject;

import nc.bs.businessevent.BdUpdateEvent;
import nc.bs.businessevent.BusinessEvent;
import nc.bs.businessevent.IBusinessEvent;
import nc.bs.businessevent.IBusinessListener;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.logging.Logger;
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.twxt.WYTwxtUtil;
import nc.vo.arap.pay.PayBillVO;
import nc.vo.pu.m21.entity.OrderVO;
import nc.vo.pub.AggregatedValueObject;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFBoolean;
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;
/**
 * @author 符耀铭
 * @date 2020年10月14日
 * @description 碧彩京东接口改造接口，红字付款单删除回写
 */
public class WYBCSCPayBillRedDelWriteListener 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();
		AggregatedValueObject[] valueObjects=getAggVO(event);
		
		if (MMValueCheck.isNotEmpty(valueObjects)) {
			for (AggregatedValueObject bill : valueObjects) {
				PayBillVO headVo =  (PayBillVO) bill.getParentVO();
				UFBoolean isrefund =ValueUtils.getUFBoolean(headVo.getDef38());
				String wgptPoNo=headVo.getDef39();
				String bcuuid=headVo.getDef40();
				UFBoolean iswgpt=ValueUtils.getUFBoolean(headVo.getDef17());
				if(isrefund.booleanValue() && MMStringUtil.isNotEmpty(wgptPoNo) && MMStringUtil.isNotEmpty(bcuuid)) {
					String esbResultinfoStr = null;
					JSONObject requestInfo=new JSONObject();
					requestInfo.put("method", "sendRefundMsg");
					requestInfo.put("orderProviderNo", wgptPoNo);
					requestInfo.put("refundFormId",bcuuid);
					requestInfo.put("refundState", "2");
					requestInfo.put("refundMsg", "NC删除退款单");
					
					String sendJsonData =WYTwxtUtil.getSendToEsbData("NC-WGPT-PU-003"+DateUtil.getCurrTime().getMillis(), requestInfo);
					logVO.setBilldata(requestInfo.toString());
					//发送请求
					try {
						JSONObject esbResultinfo = WYTwxtUtil.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) {
						logVO.setIssuccess(UFBoolean.FALSE.toString());
						sb.append(WYTwxtUtil.getExceptionDetail(e));
						ExceptionUtils.wrappBusinessException("异常：\n"+e.getMessage()+"\n请求报文：\n"+sendJsonData+"\n返回报文：\n"+esbResultinfoStr);
					}finally{
						logVO.setMsg(sb.toString());
						WYTwxtUtil.getIWuYeTwxtLogService().insertLog_RequiresNew(logVO);
					}
				}else if (iswgpt.booleanValue() && "21".equals(bill.getChildrenVO()[0].getAttributeValue("top_billtype")) && headVo.getMoney().doubleValue()>0) {
					IOrderClose closeService = NCLocator.getInstance().lookup(IOrderClose.class);
					IOrderQuery iOrderQuery=NCLocator.getInstance().lookup(IOrderQuery.class);
					
					OrderVO[] orderVOs =iOrderQuery.queryOrderVOsByIds(new String[] {bill.getChildrenVO()[0].getAttributeValue("top_billid").toString()}, UFBoolean.FALSE);
					UFBoolean iswgptsend=ValueUtils.getUFBoolean(InvocationInfoProxy.getInstance().getProperty("iswgptsend"));
					if(!iswgptsend.booleanValue()) {
						iswgptsend=ValueUtils.getUFBoolean(BSContext.getInstance().getSession("iswgptsend"));
					}
					if(MMValueCheck.isNotEmpty(orderVOs) && ValueUtils.getBoolean(orderVOs[0].getHVO().getVdef31()) && !iswgptsend.booleanValue()) {
						BSContext.getInstance().setSession("isncdel",UFBoolean.TRUE.toString());
						InvocationInfoProxy.getInstance().setProperty("isncdel",UFBoolean.TRUE.toString());
						closeService.close(orderVOs, 0, true);
					}
				}
			}
		}
	}

	private AggregatedValueObject[] getAggVO(IBusinessEvent event){
		AggregatedValueObject[] billvos = null;
		Object obj = null;
		if (event instanceof BusinessEvent) {
			BusinessEvent business = (BusinessEvent) event;
			obj = (AggregatedValueObject[]) business.getObject();
		} else if (event instanceof BdUpdateEvent) {
			BdUpdateEvent business = (BdUpdateEvent) event;
			obj = (AggregatedValueObject[]) business.getNewObject();
		}
		if (obj != null) {
			if (obj.getClass().isArray()) {
				billvos = (AggregatedValueObject[]) obj;
			} else {
				billvos = new AggregatedValueObject[] { (AggregatedValueObject) obj };
			}
			if (billvos == null || billvos.length == 0)
				return null;
		}
		return billvos;
	}
}
