package nc.bs.my.arap;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import nc.bs.arap.constant.PropertyFormularConstant;
import nc.bs.arap.util.BillSetDefaultValueUtil;
import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.logging.Logger;
import nc.bs.pf.pub.PfDataCache;
import nc.bs.trade.business.HYPubBO;
import nc.itf.sap.log.IExtLogService;
import nc.itf.uap.pf.IPFBusiAction;
import nc.itf.uap.pf.IWorkflowDefine;
import nc.itf.uap.pf.IWorkflowMachine;
import nc.itf.uap.pf.IplatFormEntry;
import nc.itf.uap.pf.metadata.IFlowBizItf;
import nc.jdbc.framework.processor.BeanListProcessor;
import nc.net.servlet.IReturnStatus;
import nc.uap.pf.metadata.PfMetadataTools;
import nc.vo.arap.pay.AggPayBillVO;
import nc.vo.arap.pay.PayBillItemVO;
import nc.vo.arap.pay.PayBillVO;
import nc.vo.esb.EsbInfoVO;
import nc.vo.esb.QueryInfoVO;
import nc.vo.esb.ResultEsbVO;
import nc.vo.esb.ResultVO;
import nc.vo.pub.AggregatedValueObject;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.pub.workflownote.WorkflownoteVO;
import nc.vo.sap.log.SapPurchaseLogVO;
import nc.vo.uap.busibean.exception.BusiBeanException;
import nc.vo.uap.pf.PFRuntimeException;
import nc.vo.wfengine.core.workflow.WorkflowProcess;
import nc.vo.wfengine.definition.WorkflowTypeEnum;
import ncc.bs.wy.tools.WyWGPTJsonTools;
import ncc.pub.wywgpt.utils.WyWGPTUtils;
import nccloud.vo.pf.flowinstance.NCCFlowInstanceVO;
import uap.json.JSONObject;
/**
 * @Description: My->NC F1-Cxx-W01
 * @author 徐刚【碧桂园my】
 * @date 2018-9-14
 * @version with NC V6.3
 */
public class MyArapWritePaybillBS {
	
	private String ITFTYPE = "NC-MY-PM-003";
	//单据类型
	private String PK_BILLTYPECODE = "F3";    
	
	//UUID 生成标识
	private final String GUID = UUID.randomUUID().toString();   
	/**
	 * 交互时间精确到毫秒
	 */
	public static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
	
	public ResultEsbVO myArapWritePaybillBS(String key, String billdata) {
		Logger.error("接口：nc.impl.bgy.ws.my2nc.write.PaybillWsFromMy");
		Logger.error("业务类名：" + this.getClass().getName());
		Logger.error("业务类函数名：execFunction");
		Logger.error("传入参数1 key：" + key);
		Logger.error("传入参数2 billdata：" + billdata);
		return doAction(key,billdata);
	}
	
	private ResultEsbVO doAction(String key, String billdata) {
		//单据主键
		String billid = "";
		//组织
		String pk_org = "";
		//单据编码
		String billno="";
		//交易类型编码
		String pk_tradetype = "F3-Cxx-W01";
		
		// 返回json信息
		ResultEsbVO esbvo = new ResultEsbVO();
		ResultVO sapResultVO = new ResultVO();
		AggPayBillVO aggVO = null;
		try {
			Logger.info("付款单 校验传入的参数");

			// 参数非空校验 a.billdata不能为空校验【为空，则返回错误的json格式数据】
			JSONObject jsonObj = new JSONObject(billdata);
			JSONObject data = (JSONObject) jsonObj.get("requestInfo");
			if (data == null){
				throw new Exception("付款单信息不能为空！");
			}
			aggVO = WyWGPTJsonTools.jsonToAggVO(data,AggPayBillVO.class,PayBillVO.class,PayBillItemVO.class);
			BillSetDefaultValueUtil.setPaybillVODefaultValue(aggVO);
			
			//add by 陈志威 2019年10月8日 添加部门和收支项目转换 begin
			PayBillItemVO[] tempitemVOs = aggVO.getBodyVOs();
			String[] deptcodes = new String[tempitemVOs.length];
			for(int i = 0; i < tempitemVOs.length; i++) {
				deptcodes[i] = tempitemVOs[i].getPk_deptid();
			}
			//add by 陈志威 2019年10月8日 添加部门和收支项目转换 end
			
			WyWGPTUtils.notNullCheckAndExFormula(PropertyFormularConstant.F3W01HEAD,PropertyFormularConstant.F3W01BODY, aggVO);
			HYPubBO bo =new HYPubBO();
			String def1=(String) bo.findColValue("ap_paybill", "def1", " nvl(dr,0)=0 and def1 ='"+aggVO.getHeadVO().getDef1()+"'");
			if (def1!=null && !"".equals(def1)) {
				throw new BusiBeanException("操作异常：MY-GUID重复-"+aggVO.getHeadVO().getDef1());
			}
			//add 2021-05-30 增加起初标识判断
//			if((aggVO.getHeadVO().getIsinit() !=null && aggVO.getHeadVO().getIsinit().booleanValue())
//					|| "WYQC001".equals(aggVO.getHeadVO().getBillmaker())) {
//				aggVO.getHeadVO().setIsinit(UFBoolean.TRUE);
//			}
			// 环境变量初始化 
			InvocationInfoProxy.getInstance().setGroupId(aggVO.getHeadVO().getPk_group());
			InvocationInfoProxy.getInstance().setUserId(aggVO.getHeadVO().getCreator());
			// 执行保存、提交、审批动作
			IPFBusiAction baService = NCLocator.getInstance().lookup(IPFBusiAction.class);
			
			pk_tradetype = aggVO.getHeadVO().getPk_tradetype();
			pk_org=aggVO.getHeadVO().getPk_org();
			
			if(aggVO.getHeadVO().getDef21()!=null && "NC63".equals(aggVO.getHeadVO().getDef21())){
				baService.processAction("SAVE", pk_tradetype, null, aggVO, null,null);	
				//baService.processAction("COMMIT", pk_tradetype, null, aggVO, null,null);	
				baService.processAction("APPROVE", pk_tradetype, null, aggVO, null,null);	
			}else {
				// 保存 creator
				baService.processAction("SAVE", pk_tradetype, null, aggVO, null,null);	
			}
			
			billid=aggVO.getHeadVO().getPk_paybill();
			billno=aggVO.getHeadVO().getBillno();
			
			//add by 陈志威 2019年10月8日 添加部门和收支项目转换 begin
//			BaseDAO dao = new BaseDAO();
//			String def76 = aggVO.getHeadVO().getDef76();
//			String def77 = aggVO.getHeadVO().getDef77();
//			ArrayList<PayBillItemVO> itemVOs = (ArrayList<PayBillItemVO>) dao.executeQuery("select * from ap_payitem where pk_paybill = '"+billid+"'", new BeanListProcessor(PayBillItemVO.class));
//			ArrayList<PayBillItemVO> updateVOs = new ArrayList<PayBillItemVO>();
//			if(def76.equals("Y")){
//				for(int i = 0; i < itemVOs.size(); i++) {
//					PayBillItemVO itemVO = itemVOs.get(i);
//					String deptid = (String) bo.findColValue("org_dept", "pk_dept", " code = '"+deptcodes[i]+"' and pk_org = '"+def77+"'");
//					itemVO.setPk_deptid(deptid);
//					itemVO.setPk_subjcode("1001H210000000025T8K");
//					itemVO.setBankrollprojet("1001H210000000Y4SHRT");
//					itemVO.setCashitem("1001H210000000025W8C");
//					dao.updateVO(itemVO);
//				}
//			}
//			else {
//				for(int i = 0; i < itemVOs.size(); i++) {
//					PayBillItemVO itemVO = itemVOs.get(i);
//					String deptid = (String) bo.findColValue("org_dept", "pk_dept", " code = '"+deptcodes[i]+"' and pk_org = '"+itemVO.getPk_org()+"'");
//					itemVO.setPk_deptid(deptid);
//					dao.updateVO(itemVO);
//				}
//			}
			/**BaseDAO dao = new BaseDAO();
			ArrayList<PayBillItemVO> itemVOs = (ArrayList<PayBillItemVO>) dao.executeQuery("select * from ap_payitem where pk_paybill = '"+billid+"'", new BeanListProcessor(PayBillItemVO.class));
			ArrayList<PayBillItemVO> updateVOs = new ArrayList<PayBillItemVO>();
			for(int i = 0; i < itemVOs.size(); i++) {
				PayBillItemVO itemVO = itemVOs.get(i);
				String deptid = (String) bo.findColValue("org_dept", "pk_dept", " code = '"+deptcodes[i]+"' and pk_org = '"+itemVO.getPk_org()+"'");
				itemVO.setPk_deptid(deptid);
				dao.updateVO(itemVO);
			}*/
			//add by 陈志威 2019年10月8日 添加部门和收支项目转换 end
			
			sapResultVO.setCode(IReturnStatus.ESB_SUCCEED_CODE);
			sapResultVO.setMessage("MY系统生成NC系统 付款单成功");
			sapResultVO.setError("");	
		} catch (Exception e) {
			// 组装异常日志信息
			Logger.debug("应付单同步失败 : " + e.getMessage());
			sapResultVO.setMessage("MY系统生成NC系统 付款单失败");
			sapResultVO.setCode(IReturnStatus.ESB_FAILING_CODE);
			sapResultVO.setError(e.getMessage());
		}finally {
			// 插入日志
			try {
				//构建日志VO
				esbvo.setResultInfo(sapResultVO);
				createEsbVO(1, esbvo, new JSONObject(billdata), sapResultVO);// 创建响应对象 MDGToNcSupplierServelet.java  发送响应对象
				String issuccess_sn = "";
				if (sapResultVO.getCode().equals(IReturnStatus.ESB_SUCCEED_CODE)) {
					issuccess_sn = "Y";
				} else {
					issuccess_sn = "N";
				}
				List<SapPurchaseLogVO> logvo_list = new ArrayList<SapPurchaseLogVO>();
				SapPurchaseLogVO log = new SapPurchaseLogVO();
				log.setPk_org(ITFTYPE);
		    	log.setBillid(billid);
		    	log.setBillno(billno);
		    	log.setPk_billtypecode("F3");
		    	log.setPk_transtypecode(pk_tradetype);
		    	log.setSend_data_sn(billdata);
		    	log.setResultdata_sn(com.alibaba.fastjson.JSONObject.toJSONString(esbvo));
		    	log.setMsg_sn(sapResultVO.getMessage()+sapResultVO.getError());
		    	log.setIssuccess_sn(issuccess_sn);
		    	log.setDef1(this.getClass().getName());
				//logvo_list.add(log);
				//PubUtils.getSaplog().insertPurchaseLog_RequiresNew(logvo_list);
				
				IExtLogService logService=NCLocator.getInstance().lookup(IExtLogService.class);
				logService.insertLog_RequiresNew(log);
				
			} catch (Exception e) {
				Logger.debug("插入日志失败 : " + e.getMessage());
			}
		}
		return esbvo;
	}
		
	
	/**
	 * 创建ESB交互对象
	 * 
	 * @param newi
	 * @param esb
	 *            交互VO
	 * @return newi=0(请求对象)/newi=1(响应对象)
	 */
	@SuppressWarnings("rawtypes")
	public void createEsbVO(int newi, final ResultEsbVO esb,
			uap.json.JSONObject jsonobj, ResultVO resultvo) {
		uap.json.JSONObject esbinfo = jsonobj.getJSONObject("esbInfo");
		Date date = Calendar.getInstance().getTime();// 获取当前时间
		EsbInfoVO esbInfo = new EsbInfoVO();
		esbInfo.setReturnCode(resultvo.getCode());
		esbInfo.setInstId(esbinfo.getString("instId"));
		esbInfo.setReturnMsg(resultvo.getMessage());
		// 获取数据
		QueryInfoVO queryInfo = new QueryInfoVO();
		queryInfo.setTotalPage("");// 默认总页数为 1
		queryInfo.setCurrentPage("");// 默认当前页数为 1
		if (newi == 0) {// 设置请求时间
			esbInfo.setRequestTime(dateFormat.format(date));
		} else {// 设置响应时间
			esbInfo.setRequestTime(dateFormat.format(date));
			esbInfo.setResponseTime(dateFormat.format(date));
			if (resultvo.getCode().equals(IReturnStatus.ESB_SUCCEED_CODE)) {
				esbInfo.setReturnStatus(IReturnStatus.ESB_SUCCEED);// 响应成功
			} else if (resultvo.getCode().equals(IReturnStatus.ESB_ERROR_CODE)) {
				esbInfo.setReturnStatus(IReturnStatus.ESB_ERROR);// 响应异常
			} else {
				esbInfo.setReturnStatus(IReturnStatus.ESB_FAILING);// 响应失败
			}
		}
		esb.setEsbInfo(esbInfo);
		esb.setQueryInfo(queryInfo);
	}
}
