package nc.bs.cmp.wybcsc.task;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.NCLocator;
import nc.bs.logging.Logger;
import nc.bs.pub.pa.PreAlertObject;
import nc.bs.pub.pa.PreAlertReturnType;
import nc.bs.pub.taskcenter.BgWorkingContext;
import nc.bs.pub.taskcenter.IBackgroundWorkPlugin;
import nc.bs.resa.sql.SqlUtil;
import nc.itf.arap.pay.IArapPayBillQueryService;
import nc.itf.cmp.settlement.ISettlementQueryService;
import nc.jdbc.framework.processor.ColumnListProcessor;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.util.mmf.framework.base.MMArrayUtil;
import nc.util.mmf.framework.base.MMValueCheck;
import nc.util.uap.wgpt.WuYeWgptUtil;
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 符耀铭
 * @date 2020-9-22
 */
public class WYCGPaybillSettleWriteBackPlugin implements IBackgroundWorkPlugin {
//update by xuwb 代码优化
	@Override
	public PreAlertObject executeTask(BgWorkingContext context) throws BusinessException {
		String message ="";
		PreAlertObject msg = new PreAlertObject();
		msg.setReturnType(PreAlertReturnType.RETURNMESSAGE);
		StringBuilder sb=new StringBuilder();
		Map<String, Object> paraMap=context.getKeyMap();
		Object begindate=paraMap.get("begindate");
		Object billno=paraMap.get("billno");
		IArapPayBillQueryService queryService=NCLocator.getInstance().lookup(IArapPayBillQueryService.class);
		//wby 20210930 过滤交易类型为采购付款单pk_tradetype='F3-Cxx-D42'
		String conString="pk_tradetype='F3-Cxx-D42' and nvl(dr, 0) = 0  and (nvl(def41, '~') = '~' or nvl(def41,'N') ='N')  and  money >0 and substr(paydate, 0, 10) >'"+begindate+"' "+(MMValueCheck.isEmpty(billno)?" ":"  and "+SqlUtil.buildInSql("billno", billno.toString().split(","), true));
		AggPayBillVO[]  aggPayBillVOs= queryService.queryBillsByWhereSQL(conString);
		if(MMArrayUtil.isNotEmpty(aggPayBillVOs)) {
			int yftotal=0;//预付总数
			int fktotal=0;//付款总数
			BaseDAO baseDAO=new BaseDAO();
			WuYeWgptLogVO logVO = null;

			JSONObject requestInfo=null;
			
			String esbResultinfoStr = null;
			Set<String> successSet=new HashSet<String>();
			for(int i=0;i<aggPayBillVOs.length;i++) {
				JSONArray billList=new JSONArray();//付款接口请求报文		
				List orderPayReqList=new ArrayList();//预付请求报文集合
				
				sb=new StringBuilder();
				logVO = new WuYeWgptLogVO();
				logVO.setItfcode("NC-WGPT-PU-003");
				logVO.setTranstypecode("F3");
				logVO.setItfname("物业付款结算单 结算/取消结算后台任务回写付款信息_HD");
				AggPayBillVO aggPayBillVO=aggPayBillVOs[i];
				
				logVO.setNc_id(aggPayBillVO.getHeadVO().getPrimaryKey());
				logVO.setBillno(aggPayBillVO.getHeadVO().getBillno());
				
				aggPayBillVO.getHeadVO().setDef49(UFBoolean.FALSE.toString());
//				aggPayBillVO.getHeadVO().setDef41(UFBoolean.FALSE.toString());

				requestInfo=new JSONObject();
				sb.append("单据来源："+aggPayBillVO.getHeadVO().getSrc_syscode());
				if((aggPayBillVO.getHeadVO().getSrc_syscode()!=1 && aggPayBillVO.getHeadVO().getSrc_syscode()!=4)){
					continue;
				}
				String qrySql="select distinct bp.s_billid\n" +
						"  from arap_billmap bp\n" + 
						" where bp.t_billid = '"+aggPayBillVO.getHeadVO().getPk_paybill()+"'\n" + 
						"   and nvl(bp.dr, 0) = 0";


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

				JSONObject billdata=null;

				for(int j=0;j<list.size();j++){			
					Object P_billno="";
					int status=0;
					String sql=null;
					if(aggPayBillVO.getHeadVO().getSrc_syscode()==1){//来源系统：应付系统=1  调付款接口
						//vdef10	网购平台结算单号
						//vdef14	是否网购平台发送
						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(j)+"'))";
						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 {	    
						billdata=new JSONObject();
						billdata.put("payAmount", aggPayBillVO.getHeadVO().getMoney().doubleValue());
						billdata.put("invoiceType", aggPayBillVO.getHeadVO().getEffectstatus()==10?"1":"0");
						billdata.put("paymentTime", DateUtil.getCurrTime().toStdString());
					    billdata.put("billNo", P_billno.toString().split("@")[0]);	
					    billdata.put("status", status);	
					    billList.add(billdata);
						}
					}
					else if(aggPayBillVO.getHeadVO().getSrc_syscode()==4){//来源系统 ：采购系统=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;
						}else {
						//封装预付请求报文
						JSONObject orderPayRequestJson=new JSONObject();
						orderPayRequestJson.put("method", "sendOrderPaymentMsg");	
						orderPayRequestJson.put("orderProviderNo", P_billno.toString().split("@")[0]);
						orderPayRequestJson.put("paymentState", aggPayBillVO.getHeadVO().getEffectstatus()==10?"1":"0");
						orderPayRequestJson.put("paymentOrderNo", aggPayBillVO.getHeadVO().getBillno());
						orderPayRequestJson.put("paymentPrice", aggPayBillVO.getHeadVO().getMoney().toString());
						Object pk_account =aggPayBillVO.getBodyVOs()[0].getPayaccount();
						if(MMValueCheck.isEmpty(pk_account)){
							ISettlementQueryService qryService=NCLocator.getInstance().lookup(ISettlementQueryService.class);
							SettlementAggVO settlementAggVO=qryService.querySettlementAggByPk_busibill(aggPayBillVO.getHeadVO().getPk_paybill());
							if(MMValueCheck.isNotEmpty(settlementAggVO.getChildrenVO()[0].getAttributeValue("pk_account"))){
								pk_account=settlementAggVO.getChildrenVO()[0].getAttributeValue("pk_account");
							}
						}
						if(MMValueCheck.isEmpty(pk_account)){
							ExceptionUtils.wrappBusinessException("付款账户为空，单据号："+aggPayBillVO.getHeadVO().getBillno());
						}
						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());
						orderPayReqList.add(orderPayRequestJson);
						}
					}				
				}
				if(orderPayReqList.size()>0) {
					yftotal=orderPayReqList.size();
					WuYeWgptLogVO sendOrderPaymentMsgLogVO=null;
					for(int a=0;a<orderPayReqList.size();a++) {
						sendOrderPaymentMsgLogVO=new WuYeWgptLogVO();
						sendOrderPaymentMsgLogVO.setIssuccess(UFBoolean.TRUE.toString());
						sendOrderPaymentMsgLogVO.setItfcode("NC-WGPT-PU-003==sendOrderPaymentMsg");
						sendOrderPaymentMsgLogVO.setItfname("结算回写付款信息新增字段==_HD");
						String sendJsonData =WyWGPTUtils.getSendToEsbData("NC-WGPT-PU-003"+DateUtil.getCurrTime().getMillis(), orderPayReqList.get(a));
						//发送请求
						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().setDef49(UFBoolean.TRUE.toString());
								if(esbInfo!=null){
									//接口返回状态：S（成功）/W（警告）/E（错误）
									String returnStatus = esbInfo.get("returnStatus")+"";
									returnStatus = "E".equals(returnStatus)?"否":"是";
									if("否".equals(returnStatus)){
										aggPayBillVO.getHeadVO().setDef49(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().setDef49(UFBoolean.FALSE.toString());
									Object result = resultInfo.get("result");
									ExceptionUtils.wrappBusinessException("网购平台提示:"+result);
								}
							}
							successSet.add(aggPayBillVO.getHeadVO().getPk_paybill());
						} catch (Exception e) {
							aggPayBillVO.getHeadVO().setDef49(UFBoolean.FALSE.toString());
							sendOrderPaymentMsgLogVO.setIssuccess(UFBoolean.FALSE.toString());
							sendOrderPaymentMsgLogVO.setMsg(e.getMessage()+"##"+WuYeWgptUtil.getExceptionDetail(e));
//							ExceptionUtils.wrappBusinessException("异常：\n"+e.getMessage()+"\n请求报文：\n"+sendJsonData+"\n返回报文：\n"+esbResultinfoStr);//xug 注释
						}finally{
							WuYeWgptUtil.getIWuYeWgptLogService().insertLog_RequiresNew(sendOrderPaymentMsgLogVO);
						}
					}
				}

				if(billList.size()>0){
					fktotal=billList.size();
					requestInfo.put("method", "getPaymentMsg");
					requestInfo.put("billList", billList);
					String sendJsonData =WyWGPTUtils.getSendToEsbData("NC-WGPT-PU-003"+DateUtil.getCurrTime().getMillis(), requestInfo);
					sb.append("请求报文："+requestInfo);
					logVO.setBilldata(requestInfo.toString());
					//发送请求
					try {
						logVO.setIssuccess(UFBoolean.TRUE.toString());
						//xug 修改调用方式
						JSONObject esbResultinfo = WyWGPTUtils.sendToESB_GX(sendJsonData,"NC-WGPT-PU-003");
						aggPayBillVO.getHeadVO().setDef49(UFBoolean.TRUE.toString());
						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)){
									aggPayBillVO.getHeadVO().setDef49(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().setDef49(UFBoolean.FALSE.toString());
								Object result = resultInfo.get("result");
								ExceptionUtils.wrappBusinessException("网购平台提示:"+result);
							}
						}else {
							logVO.setIssuccess(UFBoolean.FALSE.toString());
							sb.append("接口返回esbInfo 为空！");
						}
						successSet.add(aggPayBillVO.getHeadVO().getPk_paybill());
					} catch (Exception e) {
						aggPayBillVO.getHeadVO().setDef49(UFBoolean.FALSE.toString());
						logVO.setIssuccess(UFBoolean.FALSE.toString());
						sb.append(e.getMessage()+"##"+WuYeWgptUtil.getExceptionDetail(e));
//						logVO.setMsg(e.getMessage()+"##"+WuYeWgptUtil.getExceptionDetail(e));
//						ExceptionUtils.wrappBusinessException("异常：\n"	+e.getMessage()+"\n请求报文：\n"+sendJsonData+"\n返回报文：\n"+esbResultinfoStr);//xug 注释
					}finally{
						logVO.setMsg(sb.toString());
						WuYeWgptUtil.getIWuYeWgptLogService().insertLog_RequiresNew(logVO);
					}
				}
				//xug  补传，传送成功，写入49
				if(UFBoolean.valueOf(aggPayBillVO.getHeadVO().getDef49()).booleanValue()) {
					WuYeWgptUtil.getIWuYeWgptLogService().updateSql_RequiresNew("update ap_paybill set def49='Y',def41='Y' where pk_paybill = '"+aggPayBillVO.getHeadVO().getPk_paybill()+"'");
				}
				if(orderPayReqList.size() == 0 && billList.size() == 0) {
					logVO.setIssuccess(UFBoolean.FALSE.toString());
					logVO.setMsg(sb.toString());
					WuYeWgptUtil.getIWuYeWgptLogService().insertLog_RequiresNew(logVO);
				}
			}
//			if(successSet.size()>0) {
//				baseDAO.executeUpdate("update  ap_paybill  set  def49='Y'  where "+SqlUtil.buildInSql("pk_paybill", successSet.toArray(new String[0]), true));
//			}
			int total=yftotal+fktotal;
			message="后台任务执行成功！总数量："+total+"，成功数量："+successSet.size()+"失败数量："+(total-successSet.size());
		}else {
			message="没有查出符合的数据！";
		}
		msg.setReturnObj(message);
		msg.setMsgTitle("【NC-碧彩商城】物业采购付款单回写碧彩商城");
		context.setLogStr(message);
		return msg;
	}

}
