package nccloud.web.pu.poorder.action;

import java.util.Objects;
import nc.vo.pu.m21.entity.OrderVO;
import nc.vo.pub.BusinessException;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.pubapp.pflow.PfUserObject;
import nc.vo.scmpub.res.billtype.POBillType;
import nccloud.dto.pu.poorder.entity.QueryInfo;
import nccloud.dto.scmpub.script.entity.SCMScriptResultDTO;
import nccloud.framework.core.json.IJson;
import nccloud.framework.core.util.GridCompareUtils;
import nccloud.framework.service.ServiceLocator;
import nccloud.framework.web.container.IRequest;
import nccloud.framework.web.json.JsonFactory;
import nccloud.framework.web.ui.pattern.extbillcard.ExtBillCard;
import nccloud.framework.web.ui.pattern.extbillcard.ExtBillCardOperator;
import nccloud.pubitf.riart.pflow.CloudPFlowContext;
import nccloud.pubitf.scmpub.commit.service.IBatchRunScriptService;
import nc.itf.pu.invoke.*;

public class OrderSaveAction extends AbstractOrderSaveAction {

	// 继承父类的方法在以前动作脚本执行之前自动分配物料 add by 郭晋贤
	@SuppressWarnings({ "unused" })
	@Override
	public Object doAction(IRequest request) {
		nc.bs.logging.Logger.error("*****************开始进行物料分配**************");
		
		ExtBillCardOperator operator = getExtBillCardOperator(request);
		OrderVO vo = getWebOrder(request, operator);
		
		((IMatrilFpService)ServiceLocator.find(IMatrilFpService.class)).matrialFp(vo.getBVO());
		
		nc.bs.logging.Logger.error("*****************物料分配完成**************");
		
		return super.doAction(request);
	}

	

	protected SCMScriptResultDTO doScriptRemoteCall(OrderVO[] vos, PfUserObject pfUserObject,
			ExtBillCardOperator operator) throws BusinessException {
		CloudPFlowContext cloudContext = getCloudPFlowContext(vos, pfUserObject);
		SCMScriptResultDTO scriptResult = ((IBatchRunScriptService) ServiceLocator.find(IBatchRunScriptService.class))
				.runBacth(cloudContext, OrderVO.class);
		return scriptResult;
	}

	private CloudPFlowContext getCloudPFlowContext(OrderVO[] vos, PfUserObject pfUserObject) {
		CloudPFlowContext context = new CloudPFlowContext();
		context.setActionName("SAVEBASE");
		context.setBillType(POBillType.Order.getCode());
		context.setBillVos(vos);
		context.setUserObj(new PfUserObject[] { pfUserObject });
		return context;
	}

	protected ExtBillCard doAfterCompare(ExtBillCard serverCard, ExtBillCard clientCard) {
		serverCard = GridCompareUtils.compareExtBillCardGrid(clientCard, serverCard);
		return serverCard;
	}

	private ExtBillCardOperator getExtBillCardOperator(IRequest request) {
		try {
			IJson json = JsonFactory.create();
			QueryInfo info = (QueryInfo) json.fromJson(request.read(), QueryInfo.class);
			return new ExtBillCardOperator(info.getPageid());
		} catch (Exception e) {
			ExceptionUtils.wrappException(e);
		}
		return null;
	}

	private OrderVO getWebOrder(IRequest request, ExtBillCardOperator operator) {
		if (Objects.isNull(operator)) {
			return null;
		}
		return (OrderVO) operator.toBill(request);
	}



}
