package nc.bs.sap.fi;

import java.util.HashMap;
import java.util.UUID;

import com.alibaba.fastjson.JSONObject;

import nc.bs.dao.BaseDAO;
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.uap.pf.IplatFormEntry;
import nc.pub.sap.constant.SapConstants;
import nc.pubitf.arap.receivable.IArapReceivableBillPubQueryService;
import nc.util.mmf.framework.base.MMStringUtil;
import nc.util.mmf.framework.base.MMValueCheck;
import nc.util.mmf.framework.base.MMValueConvert;
import nc.util.uap.twxt.WYTwxtUtil;
import nc.vo.arap.receivable.AggReceivableBillVO;
import nc.vo.arap.receivable.ReceivableBillVO;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.pubapp.AppContext;
import nc.vo.pubapp.pflow.PfUserObject;
import nc.vo.sap.log.SapFinanceLogVO;
import nc.vo.sap.result.SAPResultVO;
/**
 * @Description: 内部交易应收协同确认  删除接口
 * @author 赵长剑 【碧桂园SAP专项】
 * @date 2018-06-01
 * @version with NC V6.3
 */
public class SapFiWriteSynergeticDelete {
	private String ITFTYPE = "SAP传递内部交易应收信息";
	//单据类型主键
	private  String PK_BILLTYPEID = "0000Z3000000000000F0";
	//单据类型
	private String PK_BILLTYPECODE = "F0";
	//交易类型主键
	private String PK_TRADETYPEID="";
	//交易类型编码
	private String PK_TRADETYPE = "";   
	//单据主键
	private String billid = "";
	//单据编码
	private String billno = "";
	//组织
	private String pk_org = "";
	//返回信息
	private String rsInfo = "";
	//UUID 生成标识
	private final String GUID = UUID.randomUUID().toString();   
	public String sapWriteSynergeticDelete(String key, String billdata) {
		Logger.error("业务类名：" + this.getClass().getName());
		Logger.error("业务类函数名：SapwriteSynergeticDelete");
		Logger.error("传入参数1 key：" + key);
		Logger.error("传入参数2 billdata：" + billdata);
		return doAtion(key,billdata);
	}

	private String doAtion(String key, String billdata) {
		    IplatFormEntry baService = NCLocator.getInstance().lookup(IplatFormEntry.class);
	     	ReceivableBillVO hvo = null;
	     	BaseDAO dao = new BaseDAO();
	  		//返回的json信息
			SAPResultVO sapResultVO = new SAPResultVO();
			//审批时默认参数
			HashMap<String, Object> customProperties = new HashMap<String, Object>();
			customProperties.put("notechecked", "notechecked");
			try {
				if (!SapConstants.CHECK_KEY.equals(key)) {
					throw new Exception("key验证失败 ！ ");
				}
				if (MMStringUtil.isEmpty(billdata)) {
					throw new Exception("内部交易应收信息不能为空 ！ ");
				}
				JSONObject jsonObj = JSONObject.parseObject(billdata);
				JSONObject data = (JSONObject) jsonObj.get("data");
				if (data.containsKey("pk_recbill") && MMValueCheck.isEmpty(data.get("pk_recbill"))) {
					sapResultVO.setMsg("操作异常：主键(pk_recbill)为空");
					return rsInfo =JSONObject.toJSONString(sapResultVO);
				}
				String pk_recbill = (String) data.get("pk_recbill");
				IArapReceivableBillPubQueryService queryService=NCLocator.getInstance().lookup(IArapReceivableBillPubQueryService.class);
				AggReceivableBillVO[] aggvos =queryService.findBillByPrimaryKey(new String[] {pk_recbill});
				if (MMValueCheck.isEmpty(aggvos)) {
						sapResultVO.setIssuccess(SapConstants.FAIL_TRANS);
						sapResultVO.setMsg("操作异常：NCC不存在您输入的主键");
						return rsInfo =JSONObject.toJSONString(sapResultVO);
				}
				AggReceivableBillVO aggvo=aggvos[0];
				if(new UFBoolean(aggvo.getHeadVO().getDef8()).booleanValue()){
					sapResultVO.setIssuccess(SapConstants.SU_TRANS);
					sapResultVO.setMsg("NC单据："+aggvo.getHeadVO().getPk_recbill()+"已协同，请不要重复操作！");
					return rsInfo =JSONObject.toJSONString(sapResultVO);
				}
				InvocationInfoProxy.getInstance().setProperty("issapconfirm", "Y");
				BSContext.getInstance().setSession("issapconfirm", "Y");
 			    if (data.containsKey("def37") && MMValueConvert.toUFBoolean(data.get("def37")).booleanValue() && (!data.getBooleanValue("def38") || !data.containsKey("def38"))) {
 			    	Logger.error("SAP内部交易应收协同确认");
			    	hvo= (ReceivableBillVO) aggvo.getParentVO();
			        billid = hvo.getPk_recbill();
				    pk_org = hvo.getPk_org();
				    PK_TRADETYPEID = hvo.getPk_tradetypeid();
				    PK_TRADETYPE = hvo.getPk_tradetype();
				    billno = hvo.getBillno();
			    	ITFTYPE="SAP内部交易应收协同确认";
			    	PK_BILLTYPECODE =hvo.getPk_tradetype();
			    	// 状态为Y时  自动审批
					PfUserObject PfUserObject=new PfUserObject();
					PfUserObject[] Pfs=new PfUserObject[]{PfUserObject};
			        String actionName = "APPROVE";
			        InvocationInfoProxy.getInstance().setUserId(hvo.getBillmaker());
			    	baService.processAction(actionName,PK_BILLTYPECODE,null, aggvo, Pfs, customProperties);
			    	dao.executeUpdate("update ar_recbill set def8='Y',approver='"+hvo.getBillmaker()+"' where pk_recbill='"+hvo.getPk_recbill()+"'");
				}
			    //SAP已作废 def38
			    if (data.containsKey("def38") && data.getBooleanValue("def38")) {
				    Logger.error("SAP内部交易应收作废确认");
				    hvo= (ReceivableBillVO) aggvo.getParentVO();
				    billid = hvo.getPk_recbill(); 
				    pk_org = hvo.getPk_org();
				    PK_TRADETYPEID = hvo.getPk_tradetypeid();
				    PK_TRADETYPE = hvo.getPk_tradetype();
				    //单据号
				    billno = hvo.getBillno();
				    ITFTYPE="SAP内部交易应收作废确认";
				    PK_BILLTYPEID =hvo.getPk_tradetypeid();
				    PK_BILLTYPECODE = hvo.getPk_tradetype();
			    	if (!MMValueConvert.toUFBoolean(hvo.getDef8()).booleanValue()) {
			    		if(hvo.getApprovestatus()==1) {//审批通过才进行取消审批
			    		//SAP已作废 为Y ，判断协同确认是否为N，为N时 修改 传输SAP为N,SAP已作废为Y  修改 SAP已作废 Y
			    		String actionName="UNAPPROVE";
			    		PfUserObject PfUserObject=new PfUserObject();
						PfUserObject[] Pfs=new PfUserObject[]{PfUserObject};
			    		baService.processAction(actionName,PK_BILLTYPECODE,null, aggvo, Pfs, customProperties);
			    		}
			    		dao.executeUpdate("update ar_recbill set def7='N' where pk_recbill='"+hvo.getPk_recbill()+"'");
					}else {
						//sap已作废 为Y.判断协同确认是否为Y，为Y时 修改 SAP已作废为Y 
						dao.executeUpdate("update ar_recbill set def9='Y' where pk_recbill='"+hvo.getPk_recbill()+"'");
					}
				}
				// 组装同步成功日志信息		
				sapResultVO.setBillid(billid);
				sapResultVO.setIssuccess(SapConstants.SU_TRANS);
				sapResultVO.setMsg("操作成功");
				rsInfo =JSONObject.toJSONString(sapResultVO);
			 } catch (Exception e) {
				// 组装异常日志信息
				Logger.debug("内部交易应收同步失败 : " + e.getMessage());
				sapResultVO.setBillid(billid);
				sapResultVO.setIssuccess(SapConstants.FAIL_TRANS);
				sapResultVO.setMsg("操作异常："+e.getMessage());
				rsInfo =JSONObject.toJSONString(sapResultVO);
			}finally {
				try {
					//构建日志VO
					SapFinanceLogVO logVO = new SapFinanceLogVO();
					logVO.setPk_group(AppContext.getInstance().getPkGroup());
					logVO.setPk_org(pk_org);
					logVO.setBillid(billid);
					logVO.setBillno(billno);
					logVO.setPk_billtypeid(PK_BILLTYPEID);
					logVO.setPk_billtypecode(PK_BILLTYPECODE);
					logVO.setPk_transtypecode(PK_TRADETYPE);
					logVO.setPk_transtypeid(PK_TRADETYPEID);
					logVO.setSend_data_sn(billdata);
					logVO.setResultdata_sn(rsInfo);
					logVO.setMsg_sn(sapResultVO.getMsg());
					logVO.setIssuccess_sn(sapResultVO.getIssuccess());
					logVO.setDef1(ITFTYPE);
					WYTwxtUtil.getIWuYeTwxtLogService().insertLog_RequiresNew(logVO);
				}catch (Exception e) {
					Logger.debug("插入日志失败 : " + e.getMessage());
				}
			}
		return rsInfo;
	}
}
