package nc.impl.fa.assetcombin.rule;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import nc.bs.am.framework.action.ActionContext;
import nc.bs.am.framework.action.IRule;
import nc.bs.dao.BaseDAO;
import nc.bs.dao.DAOException;
import nc.bs.framework.common.NCLocator;
import nc.bs.hz.utils.BillInfoQueryUtil;
import nc.bs.hz.utils.SendUtil;
import nc.bs.logging.Logger;
import nc.bs.trade.business.HYPubBO;
import nc.impl.am.db.processor.ListMapProcessor;
import nc.itf.fa.byzlog.IbyzLogRcord;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.jdbc.framework.processor.MapListProcessor;
import nc.pubitf.para.ISysInitDAO;
import nc.util.fa.httputil.Base64Util;
import nc.util.fa.httputil.BillHttpRequestUtil;
import nc.util.fa.httputil.MD5Utils;
import nc.vo.bd.defdoc.DefdocVO;
import nc.vo.bd.psn.PsndocVO;
import nc.vo.bd.supplier.SupplierVO;
import nc.vo.fa.asset.AssetVO;
import nc.vo.fa.assetsplit.AssetSplitBodyVO;
import nc.vo.fa.assetsplit.AssetSplitHeadVO;
import nc.vo.fa.assetsplit.AssetSplitVO;
import nc.vo.fa.billsendVO.AssetsBodyVo;
import nc.vo.fa.billsendVO.AssetsHeadVo;
import nc.vo.fa.byzLogVO.ByzLogRcordVO;
import nc.vo.org.DeptVO;
import nc.vo.org.FinanceOrgVO;
import nc.vo.pmpub.project.ProjectHeadVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.paratemp.SysinittempVO;
import nc.vo.sm.UserVO;
import uap.json.JSONObject;


/**
 * 资产拆分单 ： 审批后同步--->碧优资 2022年01月19日
 * 
 * @author SSY
 *
 */

public class ARMSplitAssetsApproveAfterRule implements IRule<AssetSplitVO> {
	private BaseDAO baseDao;
	private ISysInitDAO iSysInitDAO;
	public ISysInitDAO getISysInitDAO() {
		if (iSysInitDAO == null) {
			iSysInitDAO = NCLocator.getInstance().lookup(ISysInitDAO.class);
		}
		return iSysInitDAO;
	}	
	public String getSysinittempValue(String initcode) throws BusinessException {
		SysinittempVO sysinittempVO = getISysInitDAO().getSysInitTempVO(initcode);
		if (sysinittempVO != null) {
			return sysinittempVO.getDefaultvalue();
		}
		
		return null; 
	}
	String pk_org;
	@Override
	public void process(ActionContext<AssetSplitVO> var1, AssetSplitVO... var2) throws BusinessException {
		String bill_code = null;
		String json = null;
		String resjson = null;
		String arcip = null;
		try {
			for (AssetSplitVO var : var2) {
				ISysInitDAO InitDAO=NCLocator.getInstance().lookup(ISysInitDAO.class);
				arcip = InitDAO.getSysInitTempVO("splittobyz").getDefaultvalue();
				String appid = getSysinittempValue("appid");
				String appkey = getSysinittempValue("appkey");
				long time = System.currentTimeMillis();
				String token =MD5Utils.MD5Upper(appid + appkey + time);
				AssetSplitBodyVO[]body = (AssetSplitBodyVO[])var.getChildrenVO();
				JSONObject headJson = null;
				List<JSONObject> bodyJson = null;
				JSONObject data =new JSONObject();
				
				headJson = setHeadVO((AssetSplitHeadVO)var.getParent(),body[0]);//!!
				data.put("head",headJson);
					for(int i=0; i<body.length; i++) {
						bodyJson = setBodyVO(body,(AssetSplitHeadVO)var.getParent());
						data.put("bodys", bodyJson);
					}
				String unicodeByDate =SendUtil.unicodeToString(data.toString());
				JSONObject sendMap = new JSONObject();
				sendMap.put("appid", appid);
				sendMap.put("time", String.valueOf(time));
				sendMap.put("token", token);		
				if(!BillInfoQueryUtil.isARC(pk_org)) return;//不是ARC,则不推送
				AssetSplitHeadVO hvo = (AssetSplitHeadVO)var.getParent();
				bill_code = hvo.getBill_code();
				String encodeData = Base64Util.encode(unicodeByDate);
//				sendMap.put("data", encodeData);
				sendMap.put("data", data);
				json =SendUtil.unicodeToString(sendMap.toString());
				resjson = BillHttpRequestUtil.sendPost(arcip, json);
				BillInfoQueryUtil.updateStatus("HM", new String[] {hvo.getPk_assetsplit()});
			}
		} catch (Exception e) {
			e.printStackTrace();
			resjson = e.toString();
		}finally {
			IbyzLogRcord ibyzLogRcord = (IbyzLogRcord) NCLocator.getInstance().lookup(IbyzLogRcord.class);
			ByzLogRcordVO byzLogRcordVO = new ByzLogRcordVO();
			byzLogRcordVO.setVbillcode(bill_code);
			byzLogRcordVO.setItf_type("资产拆分");
			byzLogRcordVO.setItfclass("nc.itf.fa.servlet.ARMSplitAssetsApproveAfterRule");
			byzLogRcordVO.setItfaddress(arcip);
			byzLogRcordVO.setByztonccparam(resjson);
			String  reqJson= SendUtil.unicodeToString(json);
			byzLogRcordVO.setNcctobyzresult(reqJson);
			try {
				ibyzLogRcord.RcordLogBYZ__RequiresNew(byzLogRcordVO);
			} catch (BusinessException e) {
				Logger.error(e.getMessage(), e);	
				Logger.error("日志生成失败！！nc.itf.fa.byzlog.IbyzLogRcord");	

			}
			
		}		
	}
	
	private JSONObject setHeadVO(AssetSplitHeadVO ahvo,AssetSplitBodyVO abvo) throws Exception {
		nc.vo.fa.billsendVO.AssetsHeadVo hvo = (AssetsHeadVo) nc.util.fa.httputil.BeanUtils.copy(ahvo, nc.vo.fa.billsendVO.AssetsHeadVo.class);
		nc.vo.fa.billsendVO.AssetsBodyVo bvo = (AssetsBodyVo) nc.util.fa.httputil.BeanUtils.copy(abvo, nc.vo.fa.billsendVO.AssetsBodyVo.class);
		JSONObject json = new JSONObject();
		pk_org = ahvo.getPk_org();
		
		AssetVO avo = BillInfoQueryUtil.selectCard(ahvo.getPk_card());//资产卡片
		List<Map<String, String>> mapDate = selectOrgsByPK(ahvo.getPk_org());
//		FinanceOrgVO org = BillInfoQueryUtil.selectOrg(ahvo.getPk_org());//财务组织
		if(mapDate != null) {
			json.put("pk_org", ahvo.getPk_org());
			json.put("Org_orgs_code",mapDate.get(0).get("code"));
			json.put("Org_orgs_name",mapDate.get(0).get("name"));
		}
		
		

		json.put("org_orgs_code", getOrgCodeByPK(pk_org));	
		json.put("org_orgs_name", getOrgNameByPK(pk_org));
		
		
		ProjectHeadVO pvo = BillInfoQueryUtil.selectProject(abvo.getPk_jobmngfil());//项目档案
		if(pvo!=null) {
		json.put("pk_jobmngfil", pvo.getPk_project());
		json.put("Bd_Project_code", pvo.getProject_code());
		json.put("Bd_Project_name", pvo.getProject_name());
		json.put("Bd_Project_erpcode", pvo.getDef6());
		}
		
		DefdocVO dfVO = BillInfoQueryUtil.selectDefVO(hvo.getDef13());////!!!!
		if(dfVO!=null) {
		json.put("def13", dfVO.getPk_defdoc());
		json.put("def13_name", dfVO.getName());
		json.put("def13_code", dfVO.getCode());
		}
		
		json.put("pk_card",ahvo.getPk_card());
		json.put("card_code", avo.getCard_code());
		json.put("asset_code", avo.getAsset_code());
		json.put("asset_name", avo.getAsset_name());
		json.put("pk_category", avo.getPk_category());
		json.put("pk_transitype", "资产合并");//交易类型，固定为资产合并
		json.put("pk_addreducestyle", "拆分与合并");//减少方式


		json.put("begin_date", toString(avo.getBegin_date()));
		json.put("business_date", toString(avo.getBusiness_date()));
		json.put("dep_start_date", toString(avo.getDep_start_date()));
		json.put("dep_end_date", toString(avo.getDep_end_date()));
		json.put("pk_currency", BillInfoQueryUtil.getBdcurrtypename(avo.getPk_currency())); //币种
		
		PsndocVO assetuser = BillInfoQueryUtil.selectPsndoc(avo.getPk_assetuser());//使用人
		if(assetuser != null) {
			json.put("pk_assetuser", assetuser.getPk_psndoc());
			json.put("assetuser_name", assetuser.getName());
			json.put("assetuser_code", assetuser.getCode());
		}
		PsndocVO pdvo = BillInfoQueryUtil.selectPsndoc(avo.getPk_user());//责任人
		if(pdvo!=null) {
			json.put("pk_user", avo.getPk_user()); 
			json.put("user_name", pdvo.getName());
			json.put("user_code", pdvo.getCode());
			json.put("vtrantypecode", dfVO.getCode());
		}
		SupplierVO svo = BillInfoQueryUtil.selectSupplier(avo.getProvider());//供应商
		if(svo!=null) {
		json.put("provider", avo.getProvider());
		json.put("provider_name", svo.getName());
		json.put("provider_code", svo.getCode());
		}
		
		DeptVO dvo = BillInfoQueryUtil.selectDept(avo.getPk_equip_usedept());//使用部门
		if(dvo!= null) {
			json.put("pk_usedept", dvo.getPk_dept());
			json.put("usedept_name", dvo.getName());
			json.put("usedept_code", dvo.getCode());
		}		
		
		
		DeptVO mandept = BillInfoQueryUtil.selectDept(bvo.getPk_mandept());//管理部门
		if (mandept != null) {
			json.put("pk_mandept", mandept.getPk_dept());
			json.put("mandept_name", mandept.getName());
			json.put("mandept_code", mandept.getCode());
		}
		
		
		DeptVO paydept_flag = BillInfoQueryUtil.selectDept(bvo.getPaydept_flag());//折旧承担部门
		if (paydept_flag != null) {
			json.put("paydept_flag",paydept_flag.getPk_dept());
			json.put("paydept_flag_name",paydept_flag.getName());
			json.put("paydept_flag_code",paydept_flag.getCode());
		}
		
		json.put("pk_usingstatus", bvo.getPk_usingstatus());
		String depmethodCode = (String) getHYPubBO().findColValue("fa_depmethod", "depmethod_code",
				" pk_depmethod  = '" + bvo.getPk_depmethod() + "' and dr = 0");
		if (depmethodCode != null) {
			json.put("pk_depmethod", depmethodCode);
		}
		
		json.put("naturemonth", avo.getNaturemonth());
		json.put("accuworkloan", avo.getAccuworkloan());
		json.put("usedmonth", avo.getUsedmonth());
		json.put("monthworkloan", avo.getMonthworkloan());
		json.put("deprate", avo.getDeprate());
		json.put("salvagerate", avo.getSalvagerate());
		json.put("card_num", avo.getCard_num());
		json.put("def7", avo.getDef7());
		json.put("netvalue", bvo.getNetvalue());
		json.put("netrating", avo.getNetrating());
		json.put("originvalue", avo.getOriginvalue());
		json.put("localoriginvalue", avo.getLocaloriginvalue());
		json.put("curryeardep", bvo.getCurryeardep());
		json.put("salvage", bvo.getSalvage());
		json.put("billmaker", hvo.getBillmaker());
		UserVO billmaker = BillInfoQueryUtil.selectUser(hvo.getBillmaker());//制单人
		if (billmaker != null) {
			json.put("billmaker", billmaker.getUser_name());
		}
		json.put("billmaketime", toString(hvo.getBillmaketime()));
		
		UserVO getCreator = BillInfoQueryUtil.selectUser(hvo.getCreator());//创建人
		if (getCreator != null) {
			json.put("creator",getCreator.getUser_name() );
		}
		
		json.put("creationtime", toString(hvo.getCreationtime()));
		json.put("modifier", hvo.getModifier());
		UserVO getModifier = BillInfoQueryUtil.selectUser(hvo.getModifier());
		if (getModifier != null) {
			json.put("modifier",getModifier.getModifier());
		}
		json.put("modifiedtime", toString(hvo.getModifiedtime()));
		
		

		return json;
	}
	private List<JSONObject> setBodyVO(AssetSplitBodyVO []arrBvo,AssetSplitHeadVO hvo) {
		List<JSONObject> assetsBodyList = new ArrayList<JSONObject>();
		for(AssetSplitBodyVO bvo:arrBvo) {
		JSONObject json = new JSONObject();
		AssetVO cardVo = BillInfoQueryUtil.selectCard(bvo.getPk_card());
		json.put("card_code", cardVo.getCard_code());
		json.put("asset_code", cardVo.getAsset_code());
		json.put("pk_addreducestyle", "拆分与合并");
		json.put("asset_name", cardVo.getAsset_name());
		json.put("pk_category", cardVo.getPk_category());
		
		DeptVO dvo = BillInfoQueryUtil.selectDept(cardVo.getPk_equip_usedept());//使用部门
		if(dvo!= null) {
			json.put("pk_usedept", dvo.getPk_dept());
			json.put("usedept_name", dvo.getName());
			json.put("usedept_code", dvo.getCode());
		}	
		DeptVO mandept = BillInfoQueryUtil.selectDept(cardVo.getPk_mandept());//管理部门
		if (mandept != null) {
			json.put("pk_mandept", mandept.getPk_dept());
			json.put("mandept_name", mandept.getName());
			json.put("mandept_code", mandept.getCode());
		}
		DeptVO paydept_flag = BillInfoQueryUtil.selectDept(cardVo.getPaydept_flag());//折旧承担部门
		if (paydept_flag != null) {
			json.put("paydept_flag",paydept_flag.getPk_dept());
			json.put("paydept_flag_name",paydept_flag.getName());
			json.put("paydept_flag_code",paydept_flag.getCode());
		}
		json.put("pk_usingstatus", cardVo.getPk_usingstatus());
		json.put("pk_depmethod", cardVo.getPk_depmethod());
		json.put("naturemonth", cardVo.getNaturemonth());
		json.put("accuworkloan", cardVo.getAccuworkloan());
		json.put("usedmonth", cardVo.getUsedmonth());
		json.put("begin_date", toString(cardVo.getBegin_date()));
		json.put("business_date", toString(cardVo.getBusiness_date()));
		json.put("card_num", cardVo.getCard_num());
		json.put("originvalue", cardVo.getOriginvalue());
		json.put("localoriginvalue", cardVo.getLocaloriginvalue());
		json.put("accudep", cardVo.getAccudep());
		json.put("curryeardep", cardVo.getCurryeardep());
		json.put("salvage", cardVo.getSalvage());
		json.put("netvalue", cardVo.getNetvalue());
		json.put("pk_jobmngfil", cardVo.getPk_jobmngfil());
		DefdocVO dfVO = BillInfoQueryUtil.selectDefVO(hvo.getDef13());
		if(dfVO!=null) {
		json.put("def13", dfVO.getPk_defdoc());
		json.put("def13_name", dfVO.getName());
		json.put("def13_code", dfVO.getCode());
		}
		json.put("pk_card",cardVo.getPk_card());
		assetsBodyList.add(json);
		}
		return assetsBodyList;
	}
	private String getOrgNameByPK(String pk) {
		return executeQuery("select name from org_orgs where pk_org = '"+pk+"'");
	}
	private String getOrgCodeByPK(String pk) {
		return executeQuery("select code from org_orgs where pk_org = '"+pk+"'");
	}

	private String executeQuery(String sql) {
		try {
			Object resultData= getDao().executeQuery(sql+" and nvl(dr,0)=0", new ColumnProcessor());
			if(resultData == null)
				return null;
			return resultData.toString();
		} catch (DAOException e) {
			e.printStackTrace();
		}
		return null;
	}
	private BaseDAO getDao() {
		if(baseDao == null) {
			baseDao = new BaseDAO();
		}
		return baseDao;
	}
	private HYPubBO hYPubBO;
	public HYPubBO getHYPubBO() {
		if (hYPubBO == null) {
			hYPubBO = new HYPubBO();
		}
		return hYPubBO;
	}
	private String toString(Object data) {
		String str="";
		if(data != null) {
			str =data.toString();
		}
		return str;
	}
	private List<Map<String,String>> selectOrgsByPK(String pk_org){
		
		try {
			 return (List<Map<String, String>>) getDao().executeQuery("select  code , name  from org_orgs where pk_org = '"+pk_org+"'", new MapListProcessor());
		} catch (DAOException e) {

			e.printStackTrace();
		}
		return null;
	}
	
}
