package nc.bs.pu.m21.wgpt.listener;

import com.alibaba.fastjson.JSONObject;

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.pubitf.arap.pay.IArapPayBillPubQueryService;
import nc.util.mmf.framework.base.MMValueCheck;
import nc.util.uap.wgpt.WuYeWgptUtil;
import nc.vo.arap.pay.AggPayBillVO;
import nc.vo.arap.utils.ArrayUtil;
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;
import ncc.pub.wywgpt.utils.WyWGPTUtils;
/**
 * @author 符耀铭
 * @date 2020年10月14日
 * @description 二开新建的类型，碧彩京东接口改造，采购订单整单关闭回写碧彩商城
 */
public class PuOrderClosingWriteWgptListener implements IBusinessListener {

	@Override
	public void doAction(IBusinessEvent event) throws BusinessException {
		WuYeWgptLogVO logVO = new WuYeWgptLogVO();
		logVO.setItfcode("NC-WGPT-PU-003");
		logVO.setTranstypecode("21");
		logVO.setItfname("NC采购订单整单关闭回写碧彩商城");
		StringBuilder sb=new StringBuilder();
		sb.append("EventType=="+event.getEventType()+"==");
		Object value=null;
		OrderVO[] bills = null;
		if(event instanceof BusinessEvent) {
			value = ((BusinessEvent)event).getObject();
		}
		if(null!=value) {
			UFBoolean iswgptsend=ValueUtils.getUFBoolean(InvocationInfoProxy.getInstance().getProperty("iswgptsend"));
			if(!iswgptsend.booleanValue()) {
				iswgptsend=ValueUtils.getUFBoolean(BSContext.getInstance().getSession("iswgptsend"));
			}
			sb.append("InvocationInfoProxy=="+iswgptsend+"==");
			if(!iswgptsend.booleanValue()) {
				if(value.getClass().isArray()) {
					Object[] objs = (Object[])((Object[])value);
					bills = objs instanceof OrderVO[]?(OrderVO[])((OrderVO[])objs):(OrderVO[])ArrayUtil.convertSupers2Subs((AggregatedValueObject[])((AggregatedValueObject[])objs), OrderVO.class);
				}else {
					bills = new OrderVO[]{(OrderVO)value};
				}
				
				if(null!=bills && ValueUtils.getUFBoolean(bills[0].getHVO().getVdef31()).booleanValue()) {
					String esbResultinfoStr = null;
					JSONObject requestInfo=new JSONObject();
					
					requestInfo.put("method","sendCancelMsg");
					requestInfo.put("orderProviderNo",bills[0].getHVO().getVdef15());
					requestInfo.put("cancelState","1");
					requestInfo.put("state", processWgptState(bills[0]));
					requestInfo.put("cancelMsg","NC采购订单整单关闭");
					
					String sendJsonData =WyWGPTUtils.getSendToEsbData("NC-WGPT-PU-003"+DateUtil.getCurrTime().getMillis(), requestInfo);
					sb.append("请求报文："+requestInfo);
					logVO.setBilldata(requestInfo.toString());
					//发送请求
					try {
						JSONObject esbResultinfo = WyWGPTUtils.sendToESB(sendJsonData,"NC-WGPT-PU-003");
						if(esbResultinfo!=null){
							esbResultinfoStr = esbResultinfo.toString();
							sb.append("返回报文："+esbResultinfoStr);
							logVO.setRsdata(esbResultinfoStr);
							Logger.error("【NC采购订单整单关闭回写碧彩商城】请求参数："+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(!"true".equals(success+"")){
								Object result = resultInfo.get("result");
								ExceptionUtils.wrappBusinessException("网购平台提示:"+result);
							}
						}
					} catch (Exception e) {
						logVO.setIssuccess(UFBoolean.FALSE.toString());
						sb.append(WuYeWgptUtil.getExceptionDetail(e));
						ExceptionUtils.wrappBusinessException("异常：\n"+e.getMessage()+"\n请求报文：\n"+sendJsonData+"\n返回报文：\n"+esbResultinfoStr);
					}finally{
						logVO.setMsg(sb.toString());
						WuYeWgptUtil.getIWuYeWgptLogService().insertLog_RequiresNew(logVO);
					}
				}
			}
		}

	}
	
	public String processWgptState(OrderVO orderVO) throws BusinessException {
		IArapPayBillPubQueryService payBillPubQueryService=NCLocator.getInstance().lookup(IArapPayBillPubQueryService.class);
		AggPayBillVO[] aggPayBillVOs=payBillPubQueryService.queryVOsByWhere("pk_paybill in (select pi.pk_paybill from ap_payitem pi where pi.top_billid ='"+orderVO.getHVO().getPk_order()+"' and  nvl(dr,0)=0)  and  nvl(dr,0)=0");
		if(MMValueCheck.isEmpty(aggPayBillVOs)) {
			return "3";
		}
		UFBoolean isncdel=ValueUtils.getUFBoolean(InvocationInfoProxy.getInstance().getProperty("isncdel"));
		if(!isncdel.booleanValue()) {
			isncdel=ValueUtils.getUFBoolean(BSContext.getInstance().getSession("isncdel"));
		}
		if(isncdel.booleanValue()) {
			return "5";
		}
		UFBoolean isncredpay=ValueUtils.getUFBoolean(InvocationInfoProxy.getInstance().getProperty("isncredpay"));
		if(!isncredpay.booleanValue()) {
			isncredpay=ValueUtils.getUFBoolean(BSContext.getInstance().getSession("isncredpay"));
		}
		
		if(isncredpay.booleanValue()) {
			return "6";
		}
		
		for(int i=0;i<aggPayBillVOs.length;i++) {
			if(aggPayBillVOs[i].getHeadVO().getMoney().doubleValue()<0 && aggPayBillVOs[i].getHeadVO().getEffectstatus()==10) {
				return "6";
			}
		}
		return "";
	}

}
