package nc.bs.bd.pfxx.plugin;

import nccloud.commons.lang.StringUtils;

import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.NCLocator;
import nc.bs.pfxx.ISwapContext;
import nc.itf.bd.material.marbasclass.IMaterialBasClassService;
import nc.vo.bd.material.marbasclass.MarBasClassVO;
import nc.vo.pfxx.auxiliary.AggxsysregisterVO;
import nc.vo.pfxx.util.PfxxPluginUtils;
import nc.vo.pub.BusinessException;
import nc.vo.pub.VOStatus;
import java.util.Collection;
/**
 * 物料基本分类的外部交换平台导入插件
 * 
 * @author jiangjuna
 * @since NC6.0
 * 
 */
public class MarBasClassPfxxPlugin extends nc.bs.pfxx.plugin.AbstractPfxxPlugin {

	private IMaterialBasClassService service = null;

	private BaseDAO baseDAO = null;

	@Override
	protected Object processBill(Object vo, ISwapContext swapContext, AggxsysregisterVO aggxsysvo)
			throws BusinessException {
		MarBasClassVO classVO = (MarBasClassVO) vo;
		String pk = PfxxPluginUtils.queryBillPKBeforeSaveOrUpdate(swapContext.getBilltype(), swapContext.getDocID());
		//合并start
		if (swapContext.getSender().equals("BIP_NC")) {
	          String whereSql = MarBasClassVO.CODE + "='" + classVO.getCode() + "'";
	          Collection<MarBasClassVO> cols = new BaseDAO().retrieveByClause(MarBasClassVO.class, whereSql);
	          if (cols != null && !cols.isEmpty()) {
	              MarBasClassVO[] vos = cols.toArray(new MarBasClassVO[0]);
	              pk = vos[0].getPk_marbasclass();
	          }
	     }
		//合并end
		if (StringUtils.isBlank(pk)) {
			classVO.setStatus(VOStatus.NEW);
			classVO = getService().insertMaterialBasClass(classVO);
			PfxxPluginUtils.addDocIDVsPKContrast(swapContext.getBilltype(), swapContext.getDocID(),
					classVO.getPrimaryKey());
		} else {
			classVO = getService().updateMaterialBasClass(getUpdateVO(classVO, pk));
		}
		return classVO.getPrimaryKey();
	}

	private MarBasClassVO getUpdateVO(MarBasClassVO classVO, String pk) throws BusinessException {
		MarBasClassVO oldVO = (MarBasClassVO) getBaseDAO().retrieveByPK(MarBasClassVO.class, pk,
				new String[] { MarBasClassVO.CREATOR, MarBasClassVO.CREATIONTIME, MarBasClassVO.INNERCODE,
						MarBasClassVO.ENABLESTATE });
		if (oldVO == null) {
			throw new BusinessException(nc.vo.ml.NCLangRes4VoTransl.getNCLangRes().getStrByID("bdpub", "0bdpub0057")
			/* @res "该数据已被删除" */);
		}
		classVO.setPrimaryKey(pk);
		classVO.setInnercode(oldVO.getInnercode());
		classVO.setCreator(oldVO.getCreator());
		classVO.setCreationtime(oldVO.getCreationtime());
		classVO.setEnablestate(oldVO.getEnablestate());
		classVO.setStatus(VOStatus.UPDATED);
		return classVO;
	}

	private BaseDAO getBaseDAO() {
		if (baseDAO == null) {
			baseDAO = new BaseDAO();
		}
		return baseDAO;
	}

	private IMaterialBasClassService getService() {
		if (service == null) {
			service = NCLocator.getInstance().lookup(IMaterialBasClassService.class);
		}
		return service;
	}

}
