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.measdoc.IMeasdocService;
import nc.vo.bd.material.marbasclass.MarBasClassVO;
import nc.vo.bd.material.measdoc.MeasdocVO;
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 MeasdocPfxxPlugin extends nc.bs.pfxx.plugin.AbstractPfxxPlugin {

	private IMeasdocService service = null;

	private BaseDAO baseDAO = null;

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

	private MeasdocVO getUpdateVO(MeasdocVO measdocVO, String pk) throws BusinessException {
		MeasdocVO oldVO = (MeasdocVO) getBaseDAO().retrieveByPK(MeasdocVO.class, pk,
				new String[] { MeasdocVO.CREATOR, MeasdocVO.CREATIONTIME, MeasdocVO.OPPDIMEN, MeasdocVO.BASECODEFLAG });
		if (oldVO == null) {
			throw new BusinessException(nc.vo.ml.NCLangRes4VoTransl.getNCLangRes().getStrByID("bdpub", "0bdpub0057")
			/* @res "该数据已被删除" */);
		}
		measdocVO.setPrimaryKey(pk);
		measdocVO.setCreator(oldVO.getCreator());
		measdocVO.setCreationtime(oldVO.getCreationtime());
		measdocVO.setOppdimen(oldVO.getOppdimen());
		measdocVO.setBasecodeflag(oldVO.getBasecodeflag());
		measdocVO.setStatus(VOStatus.UPDATED);
		return measdocVO;
	}

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

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

}
