/*
 * 
 */
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.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.fa.common.constant.FARuleConst;
import nc.itf.fa.byzlog.IbyzLogRcord;
import nc.pubitf.para.ISysInitDAO;
import nc.uif.pub.exception.UifException;
import nc.util.fa.httputil.BeanUtils;
import nc.util.fa.httputil.BillHttpRequestUtil;
import nc.util.fa.httputil.MD5Utils;
import nc.vo.bd.psn.PsndocVO;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.fa.asset.AssetVO;
import nc.vo.fa.assetcombin.AssetCombinBodyVO;
import nc.vo.fa.assetcombin.AssetCombinHeadVO;
import nc.vo.fa.assetcombin.AssetCombinVO;
import nc.vo.fa.billsendVO.AssetsBodyVo;
import nc.vo.fa.billsendVO.AssetsHeadVo;
import nc.vo.fa.byzLogVO.ByzLogRcordVO;
import nc.vo.fa.category.CategoryVO;
import nc.vo.fa.depmethod.DepmethodVO;
import nc.vo.fa.usingstatus.UsingStatusVO;
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;

/**
 * 资产合并单 ： 审批后同步--->碧优资 2021年12月27日
 * 
 * @author CCY
 *
 */
public class AfterAssetCombinedApprove implements IRule<AssetCombinVO> {

	@Override
	public void process(ActionContext<AssetCombinVO> context, AssetCombinVO... aggVos) throws BusinessException {
		for (AssetCombinVO aggVO : aggVos) {		
			JSONObject resultjson = new JSONObject();
			String response = null;
			String req = null;
			AssetCombinVO cloneVO = ((Map<String, AssetCombinVO>) context
					.getImutableUserObj(FARuleConst.ASSETCOMBINE_COMBINED_ASSET)).get(aggVO.getPrimaryKey());
			if(BillInfoQueryUtil.isARC((String)cloneVO.getParentVO().getAttributeValue("pk_org"))) {
				try {
					
					String arcip = getSysinittempValue("assettobyz");
					String appid = getSysinittempValue("appid");
					String appkey = getSysinittempValue("appkey");
					long time = System.currentTimeMillis();
					String token = MD5Utils.MD5Upper(appid + appkey + time);
					AssetCombinHeadVO headVo = (AssetCombinHeadVO) cloneVO.getParent();
					AssetsHeadVo assetsHeadVo = assetsHead(headVo);
					AssetCombinBodyVO[] bodyVo = (AssetCombinBodyVO[]) cloneVO.getChildrenVO();
					List<String> assetsBodyLists = assetsBodyLists(bodyVo);
					Map<String, Object> sendMap = new HashMap<String, Object>();
					sendMap.put("appid", appid);
					sendMap.put("time", time);
					sendMap.put("token", token);
					JSONObject data = new JSONObject();
					data.put("head", assetsHeadVo);
					data.put("bodys", assetsBodyLists);
//					String encodeData = Base64Util.encode(data.toString());
					sendMap.put("data", data);
					JSONObject json = new JSONObject(sendMap);
					req = json.toString();
					response = BillHttpRequestUtil.sendPost(arcip, req);
					JSONObject responseJson = new JSONObject(response);
					String msg = (String)responseJson.getString("msg");
					if(responseJson.getInt("code")!=200) {
						 ExceptionUtils.wrappBusinessException(msg);
					}				
					BillInfoQueryUtil.updateStatus("HO", new String[] {headVo.getPk_assetcombin()});
				} catch (Exception e) {
					Logger.error(e.getMessage(), e);
					throw new RuntimeException(e.getMessage(), e);
				} finally {
					IbyzLogRcord ibyzLogRcord = (IbyzLogRcord) NCLocator.getInstance().lookup(IbyzLogRcord.class);
					ByzLogRcordVO byzLogRcordVO = new ByzLogRcordVO();
					byzLogRcordVO.setItf_type("资产合并发送碧优资");
					byzLogRcordVO.setItfclass("nc.impl.fa.assetcombin.rule.AfterAssetCombinedApprove");

					byzLogRcordVO.setByztonccresult(response);
					String resjson = SendUtil.unicodeToString(req);
					byzLogRcordVO.setNcctobyzparam(resjson);
					try {
						ibyzLogRcord.RcordLogBYZ__RequiresNew(byzLogRcordVO);
					} catch (BusinessException e) {
						Logger.error(e.getMessage(), e);
						Logger.error("日志生成失败！！nc.itf.fa.byzlog.IbyzLogRcord");

					}

				}
			}
			
		}

	}

	private List<String> assetsBodyLists(AssetCombinBodyVO[] bodyVo) throws UifException {
		List<String> assetsBodyList = new ArrayList<String>();
		for (AssetCombinBodyVO item : bodyVo) {
			AssetVO cardVo = BillInfoQueryUtil.selectCard(item.getPk_card());
			AssetsBodyVo assetsBodyVo = (AssetsBodyVo) BeanUtils.copy(cardVo, AssetsBodyVo.class);
			// AssetsBodyVo assetsBodyVo = new AssetsBodyVo();
			assetsBodyVo.setPk_card (cardVo.getPk_card());
			assetsBodyVo.setCard_code(cardVo.getCard_code());
			assetsBodyVo.setPk_addreducestyle("拆分&合并");
			assetsBodyVo.setAsset_code(cardVo.getAsset_code());
			assetsBodyVo.setAsset_name(cardVo.getAsset_name());
			
			String currency = (String) getHYPubBO().findColValue("bd_currtype", "name",
					"pk_currtype = '" + cardVo.getPk_category() + "' and dr = 0");
			if (currency != null) {
				assetsBodyVo.setPk_category(currency);
			}
			// assetsBodyVo.setPk_usedept(cardVo.getUsedept());
			DeptVO mandept = BillInfoQueryUtil.selectDept(cardVo.getPk_mandept());
			if (mandept != null) {
				assetsBodyVo.setPk_mandept(mandept.getPk_dept());
				assetsBodyVo.setMandept_name(mandept.getName());
				assetsBodyVo.setMandept_code(mandept.getCode());
			}
			//// 折旧承担部门
			DeptVO paydept_flag = BillInfoQueryUtil.selectDept(cardVo.getPaydept_flag());
			if (paydept_flag != null) {
				assetsBodyVo.setPaydept_flag(paydept_flag.getPk_dept());
				assetsBodyVo.setPaydept_flag_name(paydept_flag.getName());
				assetsBodyVo.setPaydept_flag_code(paydept_flag.getCode());
			}
			UsingStatusVO  usingStatusVO  =BillInfoQueryUtil.selectUsingstatus(cardVo.getPk_usingstatus());
			if(usingStatusVO!=null) {
				assetsBodyVo.setPk_usingstatus(usingStatusVO.getStatus_name());
			}
			
			DepmethodVO depmethodVO = BillInfoQueryUtil.selectDepmethod(cardVo.getPk_depmethod());
			if(depmethodVO!=null) {
				assetsBodyVo.setPk_depmethod(depmethodVO.getDepmethod_name());

			}
			assetsBodyVo.setNaturemonth(cardVo.getNaturemonth());
			assetsBodyVo.setAccuworkloan(cardVo.getAccuworkloan());
			assetsBodyVo.setUsedmonth(cardVo.getUsedmonth());
			assetsBodyList.add(assetsBodyVo.toString());
		}
		return assetsBodyList;
	}

	private AssetsHeadVo assetsHead(AssetCombinHeadVO headVo) throws BusinessException {
		try {
//			AssetsHeadVo assetsHeadVo = (AssetsHeadVo) BeanUtils.copy(headVo, AssetsHeadVo.class);
			AssetsHeadVo assetsHeadVo = new AssetsHeadVo();
			assetsHeadVo.setPk_card(headVo.getPk_card());

			FinanceOrgVO org = BillInfoQueryUtil.selectOrg(headVo.getPk_org());
			if (org != null) {
				assetsHeadVo.setPk_org(org.getPk_org());
				assetsHeadVo.setOrg_orgs_code(org.getCode());
				assetsHeadVo.setOrg_orgs_name(org.getName());
			}
			assetsHeadVo.setBill_code(headVo.getBill_code());
			assetsHeadVo.setDef13(headVo.getDef13());
			assetsHeadVo.setCard_code(headVo.getCard_code());
			assetsHeadVo.setAsset_code(headVo.getAsset_code());
			assetsHeadVo.setAsset_name(headVo.getAsset_name());
			CategoryVO category = BillInfoQueryUtil.selectCategory(headVo.getPk_category());
			if (category != null) {
				assetsHeadVo.setPk_category(category.getCate_code());

			}
			assetsHeadVo.setPk_transitype("资产合并");

			assetsHeadVo.setPk_addreducesty("拆分与合并");
			ProjectHeadVO project = BillInfoQueryUtil.selectProject(headVo.getPk_jobmngfil());
			if (project != null) {
				assetsHeadVo.setPk_jobmngfil(project.getPk_project());
				assetsHeadVo.setBd_Project_code(project.getProject_code());
				assetsHeadVo.setBd_Project_Name(project.getProject_name());
				assetsHeadVo.setBd_Project_erpcode(project.getDef6());
			}

			assetsHeadVo.setBegin_date(headVo.getBegin_date());
			assetsHeadVo.setBusiness_date(headVo.getBusiness_date());
			AssetVO cardVo = BillInfoQueryUtil.selectCard(headVo.getPk_card());
			if (cardVo != null) {
				// 月工作量？？
				assetsHeadVo.setMonthworkloan(cardVo.getMonthworkloan());
				//// 月折旧率(%)				
				assetsHeadVo.setDeprate(cardVo.getDeprate());
				assetsHeadVo.setDep_start_date(headVo.getDep_start_date());
				assetsHeadVo.setDep_end_date(cardVo.getDep_end_date());// 折旧截止日期
				assetsHeadVo.setProvider(cardVo.getProvider());// 供应商
			}

			String currency = (String) getHYPubBO().findColValue("bd_currtype", "name",
					"pk_currtype = '" + headVo.getPk_currency() + "' and dr = 0");
			if (currency != null) {
				assetsHeadVo.setPk_currency(currency);
			}

			PsndocVO assetuser = BillInfoQueryUtil.selectPsndoc(headVo.getPk_assetuser());
			if (assetuser != null) {
				assetsHeadVo.setPk_assetuser(assetuser.getPk_psndoc());
				assetsHeadVo.setAssetuser_name(assetuser.getName());
				assetsHeadVo.setAssetuser_code(assetuser.getCode());
			}
			// 责任人？？？
			PsndocVO pk_user = BillInfoQueryUtil.selectPsndoc(headVo.getPk_assetuser());
			if (pk_user != null) {
				assetsHeadVo.setPk_user(assetuser.getPk_psndoc());
				assetsHeadVo.setUser_name(assetuser.getName());
				assetsHeadVo.setUser_code(assetuser.getCode());
			}

			// 使用部门
			DeptVO usedept = BillInfoQueryUtil.selectDept(headVo.getUsedept());
			if (usedept != null) {
				assetsHeadVo.setPk_usedept(usedept.getPk_dept());
				assetsHeadVo.setUsedept_name(usedept.getName());
				assetsHeadVo.setUsedept_code(usedept.getCode());
			}

			// 管理部门// 管理部门
			DeptVO mandept = BillInfoQueryUtil.selectDept(headVo.getPk_mandept());
			if (mandept != null) {
				assetsHeadVo.setPk_mandept(mandept.getPk_dept());
				assetsHeadVo.setMandept_name(mandept.getName());
				assetsHeadVo.setMandept_code(mandept.getCode());
			}
			//// 折旧承担部门
			DeptVO paydept_flag = BillInfoQueryUtil.selectDept(headVo.getPaydept_flag());
			if (paydept_flag != null) {
				assetsHeadVo.setPaydept_flag(paydept_flag.getPk_dept());
				assetsHeadVo.setPaydept_flag_name(paydept_flag.getName());
				assetsHeadVo.setPaydept_flag_code(paydept_flag.getCode());
			}

			// fa_usingstatus 使用情况nc.vo.fa.usingstatus.UsingStatusVO
			assetsHeadVo.setPk_usingstatus(headVo.getPk_usingstatus());

			String depmethodCode = (String) getHYPubBO().findColValue("fa_depmethod", "depmethod_code",
					" pk_depmethod  = '" + headVo.getPk_depmethod() + "' and dr = 0");
			if (depmethodCode != null) {
				assetsHeadVo.setPk_depmethod(depmethodCode);
			}
			assetsHeadVo.setNaturemonth(headVo.getNaturemonth());
			assetsHeadVo.setAccuworkloan(headVo.getAccuworkloan());

			assetsHeadVo.setUsedmonth(headVo.getUsedmonth());

			assetsHeadVo.setCard_num(headVo.getCard_num());
			assetsHeadVo.setDef7(headVo.getDef7());
			assetsHeadVo.setSalvage(headVo.getSalvage());
			assetsHeadVo.setNetvalue(headVo.getNetvalue());
			assetsHeadVo.setNetrating(headVo.getNetrating());
			assetsHeadVo.setOriginvalue(headVo.getOriginvalue());
			assetsHeadVo.setLocaloriginvalue(headVo.getLocaloriginvalue());
			UserVO billmaker = BillInfoQueryUtil.selectUser(headVo.getBillmaker());
			if (billmaker != null) {
				assetsHeadVo.setBillmaker(billmaker.getUser_name());
			}
			assetsHeadVo.setBillmaketime(headVo.getBillmaketime());
			UserVO getCreator = BillInfoQueryUtil.selectUser(headVo.getCreator());
			if (getCreator != null) {
				assetsHeadVo.setCreator(getCreator.getUser_name());
			}
			UserVO getModifier = BillInfoQueryUtil.selectUser(headVo.getModifier());
			if (getModifier != null) {
				assetsHeadVo.setModifier(getModifier.getModifier());
			}
			assetsHeadVo.setCreationtime(headVo.getCreationtime());
			assetsHeadVo.setModifiedtime(headVo.getModifiedtime());
			return assetsHeadVo;
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}

	}

	private ISysInitDAO iSysInitDAO;

	public ISysInitDAO getISysInitDAO() {
		if (iSysInitDAO == null) {
			iSysInitDAO = NCLocator.getInstance().lookup(ISysInitDAO.class);
		}
		return iSysInitDAO;
	}

	private HYPubBO hYPubBO;

	public HYPubBO getHYPubBO() {
		if (hYPubBO == null) {
			hYPubBO = new HYPubBO();
		}
		return hYPubBO;
	}

	public String getSysinittempValue(String initcode) throws BusinessException {
		SysinittempVO sysinittempVO = getISysInitDAO().getSysInitTempVO(initcode);
		if (sysinittempVO != null) {
			return sysinittempVO.getDefaultvalue();
		}

		return null;
	}
}