package nc.bs.cmp.settlement.listener;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
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.NCLocator;
import nc.bs.logging.Logger;
import nc.jdbc.framework.processor.ColumnListProcessor;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.pubitf.arap.pay.IArapPayBillPubQueryService;
import nc.util.uap.wgpt.WuYeWgptUtil;
import nc.vo.arap.basebill.BaseAggVO;
import nc.vo.arap.pay.AggPayBillVO;
import nc.vo.bd.bankaccount.BankAccSubVO;
import nc.vo.bd.bankdoc.BankdocVO;
import nc.vo.cmp.settlement.SettlementAggVO;
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 符耀铭
 * @time 2019-3-25
 */
public class WYCGPayBillSettleWriteWGPT 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("物业付款结算单 结算/取消结算回写付款信息_QD");
		StringBuilder sb=new StringBuilder();

		if(event instanceof BusinessEvent) {
			logVO.setIssuccess(UFBoolean.TRUE.toString());
			BusinessEvent updateEvent1 = (BusinessEvent)event;
			Object obj1 = updateEvent1.getObject();
			if("CMPsettleAfter".equals(updateEvent1.getEventType())||"CMPreverseSettleAfter".equals(updateEvent1.getEventType())){
				sb.append("进入日志记录物业付款单回写----"+updateEvent1.getEventType());
				if(obj1 instanceof SettlementAggVO[]) {
					
					String esbResultinfoStr = null;
					JSONObject requestInfo=new JSONObject();
					SettlementAggVO[] settlementAggVOs = (SettlementAggVO[])((SettlementAggVO[])updateEvent1.getObject());
//					String billType =SettleUtils.getbilltype(settlementAggVOs[0].getParentVO().getAttributeValue("pk_tradetype")==null?"":settlementAggVOs[0].getParentVO().getAttributeValue("pk_tradetype").toString(), AppContext.getInstance().getPkGroup());
					String billType = settlementAggVOs[0].getParentVO().getAttributeValue("pk_billtype")==null?"":settlementAggVOs[0].getParentVO().getAttributeValue("pk_billtype").toString();

					sb.append("单据类型："+billType);
					
					logVO.setNc_id(settlementAggVOs[0].getParentVO().getPrimaryKey());
					logVO.setBillno(settlementAggVOs[0].getParentVO().getAttributeValue("billcode")+"");
					
					//判断上游应付单是否发送网购平台 
					if("F3".equals(billType)) {
						JSONArray billList=new JSONArray();
						List orderPayReqList=new ArrayList();
						
//						Object object =SettleUtils.getBuisAggVO(settlementAggVOs[0].getParentVO().getAttributeValue("pk_tradetype").toString(), settlementAggVOs[0].getParentVO().getAttributeValue("pk_busibill").toString(), AppContext.getInstance().getPkGroup());
						BaseAggVO[] object = NCLocator.getInstance().lookup(IArapPayBillPubQueryService.class).findBillByPrimaryKey(new String[] { settlementAggVOs[0].getParentVO().getAttributeValue("pk_busibill").toString() });
						//并支付拆开不同的应付单传递 
						if(null!=object && object.length > 0 && object[0] instanceof AggPayBillVO){

							AggPayBillVO aggPayBillVO= (AggPayBillVO) object[0];
							
							logVO.setNc_id(aggPayBillVO.getHeadVO().getPrimaryKey());
							logVO.setBillno(aggPayBillVO.getHeadVO().getBillno());
							
							sb.append("单据来源："+aggPayBillVO.getHeadVO().getSrc_syscode());
							//只处理来源为应付系统和采购系统   
							if((aggPayBillVO.getHeadVO().getSrc_syscode()!=1 && aggPayBillVO.getHeadVO().getSrc_syscode()!=4)){
								return;
							}

							String qrySql="select bp.s_billid\n" +
									"  from arap_billmap bp\n" + 
									" where bp.t_billid = '"+aggPayBillVO.getHeadVO().getPk_paybill()+"'\n" + 
									"   and nvl(bp.dr, 0) = 0";

							BaseDAO baseDAO=new BaseDAO();

							List list=(List) baseDAO.executeQuery(qrySql, new ColumnListProcessor());
							sb.append("查询对照关系结果："+list.size()+"##"+list.toString());
							
								if(null==list || list.isEmpty()){
									list=new ArrayList();
									list.add(aggPayBillVO.getHeadVO().getPk_paybill());
								}

								requestInfo.put("method", "getPaymentMsg");
								
								JSONObject billdata=null;
								
								for(int i=0;i<list.size();i++){
									JSONObject orderPayRequestJson=new JSONObject();
									billdata=new JSONObject();
									orderPayRequestJson.put("method", "sendOrderPaymentMsg");
									billdata.put("invoiceType", Integer.parseInt(settlementAggVOs[0].getParentVO().getAttributeValue("settlestatus").toString())==5?"1":"0");

									billdata.put("payAmount", aggPayBillVO.getHeadVO().getMoney().doubleValue());

									Object P_billno="";
									int status=0;
									String sql=null;

									if(aggPayBillVO.getHeadVO().getSrc_syscode()==1){
										//考虑不是网购平台的单据
										//vdef10	网购平台结算单号
										//vdef8	是否网购平台发送  //xug??
										sql="select case  when  iv.vdef10 is null then 'none' else iv.vdef10  end ||'@'|| case when iv.vdef8 is null then  'N' else iv.vdef8 end wgpt \n" +
												"  from po_invoice iv\n" + 
												" where exists (select *\n" + 
												"          from ap_payableitem pii\n" + 
												"         where pii.top_billid = iv.pk_invoice\n" + 
												"           and pii.pk_payablebill in ('"+list.get(i)+"'))";
										P_billno =baseDAO.executeQuery(sql, new ColumnProcessor());
										sb.append("发票："+P_billno);
										if("".equals(P_billno) || null ==P_billno){
											continue;
										}
										String[] wgpts =P_billno.toString().split("@");
										UFBoolean iswgpt=ValueUtils.getUFBoolean(wgpts[1]);
										if(!iswgpt.booleanValue()){
											continue;
										}
									}else if(aggPayBillVO.getHeadVO().getSrc_syscode()==4){
										status=1;
										//考虑不是网购平台的单据
										sql="select case when vdef15 is null then 'none' else vdef15 end ||'@'|| case when vdef14 is null then 'N' else vdef14 end  wgpt \n" +
												"  from po_order od\n" + 
												" where exists (select *\n" + 
												"          from ap_payitem api\n" + 
												"         where od.pk_order = api.top_billid\n" + 
												"           and api.pk_paybill = '"+aggPayBillVO.getHeadVO().getPk_paybill()+"')";
										P_billno=baseDAO.executeQuery(sql,  new ColumnProcessor());
										sb.append("采购订单："+P_billno);
										if("".equals(P_billno) || null ==P_billno){
											continue;
										}
										String[] wgpts =P_billno.toString().split("@");
										UFBoolean iswgpt=ValueUtils.getUFBoolean(wgpts[1]);
										if(!iswgpt.booleanValue()){
											continue;
										}
									}
									
									billdata.put("billNo", P_billno.toString().split("@")[0]);
									
									billdata.put("status", status);

									billdata.put("paymentTime", DateUtil.getCurrTime().toStdString());
									orderPayRequestJson.put("orderProviderNo", P_billno.toString().split("@")[0]);
									orderPayRequestJson.put("paymentState", Integer.parseInt(settlementAggVOs[0].getParentVO().getAttributeValue("settlestatus").toString())==5?"1":"0");
									orderPayRequestJson.put("paymentOrderNo", aggPayBillVO.getHeadVO().getBillno());
									orderPayRequestJson.put("paymentPrice", aggPayBillVO.getHeadVO().getMoney().toString());
									Object pk_account =settlementAggVOs[0].getChildrenVO()[0].getAttributeValue("pk_account");
									orderPayRequestJson.put("paymentSubject", pk_account==null?"":((BankAccSubVO)baseDAO.retrieveByPK(BankAccSubVO.class, pk_account.toString(), new String[] {"accname"})).getAccname());
									BankdocVO[] bankdocVOs=(BankdocVO[]) baseDAO.retrieveByClause(BankdocVO.class, "pk_bankdoc in (select distinct bas.pk_bankdoc from bd_bankaccsub sub inner join bd_bankaccbas bas on sub.pk_bankaccbas = bas.pk_bankaccbas where sub.pk_bankaccsub ='"+pk_account+"')", new String[] {"name"}).toArray(new BankdocVO[0]);
									orderPayRequestJson.put("paymentBank",bankdocVOs[0].getName());
									orderPayRequestJson.put("bankPrice", aggPayBillVO.getHeadVO().getMoney().toString());
									orderPayRequestJson.put("payTime", ValueUtils.getUFDate(aggPayBillVO.getHeadVO().getPaydate())==null?"":aggPayBillVO.getHeadVO().getPaydate().toString());
									orderPayRequestJson.put("flagCode", aggPayBillVO.getBodyVOs()[0].getBankrelated_code());
									
									billList.add(billdata);
									orderPayReqList.add(orderPayRequestJson);
								}
								
								if(orderPayReqList.size()>0) {
									WuYeWgptLogVO sendOrderPaymentMsgLogVO=null;
									
									for(int i=0;i<orderPayReqList.size();i++) {
										sendOrderPaymentMsgLogVO=new WuYeWgptLogVO();
										sendOrderPaymentMsgLogVO.setIssuccess(UFBoolean.TRUE.toString());
										sendOrderPaymentMsgLogVO.setItfcode("NC-WGPT-PU-003==sendOrderPaymentMsg");
										sendOrderPaymentMsgLogVO.setItfname("结算回写付款信息新增字段==QD");
										String sendJsonData =WyWGPTUtils.getSendToEsbData("NC-WGPT-PU-003"+DateUtil.getCurrTime().getMillis(), orderPayReqList.get(i));
										//发送请求
										try {
											sendOrderPaymentMsgLogVO.setBilldata(sendJsonData);
											//xug 修改调用方式
											JSONObject esbResultinfo = WyWGPTUtils.sendToESB_GX(sendJsonData,"NC-WGPT-PU-003");
											if(esbResultinfo!=null){
												esbResultinfoStr = esbResultinfo.toString();
												sendOrderPaymentMsgLogVO.setRsdata(esbResultinfoStr);
												Logger.error("【付款单结算回写付款信息接口==sendOrderPaymentMsg】请求参数："+sendJsonData+"；\r\n返回参数："+esbResultinfoStr);
												JSONObject esbInfo = (JSONObject)esbResultinfo.get("esbInfo");
												aggPayBillVO.getHeadVO().setDef41(UFBoolean.TRUE.toString());
												if(esbInfo!=null){
													//接口返回状态：S（成功）/W（警告）/E（错误）
													String returnStatus = esbInfo.get("returnStatus")+"";
													returnStatus = "E".equals(returnStatus)?"否":"是";
													if("否".equals(returnStatus)){
														aggPayBillVO.getHeadVO().setDef41(UFBoolean.FALSE.toString());
														String returnMsg = esbInfo.get("returnMsg")+"";
														ExceptionUtils.wrappBusinessException("接口错误："+returnMsg);
													}
												}
												JSONObject resultInfo = esbResultinfo.getJSONObject("resultInfo");
												Object success = resultInfo.get("success");
												if(!"true".equals(success+"")){
													aggPayBillVO.getHeadVO().setDef41(UFBoolean.FALSE.toString());
													Object result = resultInfo.get("result");
													ExceptionUtils.wrappBusinessException("碧彩商城提示:"+result);
												}
											}
										} catch (Exception e) {
											aggPayBillVO.getHeadVO().setDef41(UFBoolean.FALSE.toString());
											sendOrderPaymentMsgLogVO.setIssuccess(UFBoolean.FALSE.toString());
											sendOrderPaymentMsgLogVO.setMsg(WuYeWgptUtil.getExceptionDetail(e));
											ExceptionUtils.wrappBusinessException("异常：\n"+e.getMessage()+"\n请求报文：\n"+sendJsonData+"\n返回报文：\n"+esbResultinfoStr);
										}finally{
											baseDAO.updateVO(aggPayBillVO.getHeadVO(),new String[] {"def41"});
											WuYeWgptUtil.getIWuYeWgptLogService().insertLog_RequiresNew(sendOrderPaymentMsgLogVO);
										}
									}
								}
								
								if(billList.size()>0){
									requestInfo.put("billList", billList);
									String sendJsonData =WyWGPTUtils.getSendToEsbData("NC-WGPT-PU-003"+DateUtil.getCurrTime().getMillis(), requestInfo);
									sb.append("请求报文："+requestInfo);
									logVO.setBilldata(requestInfo.toString());
									//发送请求
									try {
										//xug 修改调用方式
										JSONObject esbResultinfo = WyWGPTUtils.sendToESB_GX(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(!"true".equals(success+"")){
												Object result = resultInfo.get("result");
												ExceptionUtils.wrappBusinessException("碧彩商城提示:"+result);
											}
										}else {
											logVO.setIssuccess(UFBoolean.FALSE.toString());
											sb.append("接口返回esbInfo 为空！");
										}
									} 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);
									}
								}
						}else {
							sb.append("付款单无法查到："+settlementAggVOs[0].getParentVO().getAttributeValue("pk_busibill").toString());
						}
						
						if(orderPayReqList.size() == 0 && billList.size() == 0) {
							logVO.setIssuccess(UFBoolean.FALSE.toString());
							logVO.setMsg(sb.toString());
							WuYeWgptUtil.getIWuYeWgptLogService().insertLog_RequiresNew(logVO);
						}
					}
				}
			}
		}
	}

}
