package nc.bs.mmpac.pmo.pac0002.bp.rule;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import nc.bs.dao.DAOException;
import nc.bs.framework.common.NCLocator;
import nc.bs.trade.business.HYSuperDMO;
import nc.impl.pubapp.pattern.rule.IRule;
import nc.itf.uap.IUAPQueryBS;
import nc.itf.uif.pub.IUifService;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.jdbc.framework.processor.MapProcessor;
import nc.vo.bd.defdoc.DefdocVO;
import nc.vo.ic.m4c.entity.SaleOutHeadVO;
import nc.vo.mmpac.pmo.pac0002.entity.PMOAggVO;
import nc.vo.mmpac.pmo.pac0002.entity.PMOHeadVO;
import nc.vo.mmpac.pmo.pac0002.entity.PMOItemVO;
import nc.vo.pub.BusinessException;
import nc.vo.so.m30.entity.SaleOrderBVO;
//import nc.bs.rbac.bizlistener.BaseDocDataPermChangeEventListener;
//import nc.impl.mmpac.pmo.pac0002.PMOTransTypeQueryServiceImpl;
//import nc.impl.mmpac.bcrule.predata.BarCodeDataInitListener;
//import nc.ui.mmpub.setanalysis.action.SaAnalysisAction.actionPerformed;//流程生产订单齐套分析-分析

//import nc.impl.mmpub.setanalysis.SetAnalysisServiceImpl;
import nc.bs.mmpac.pmo.pac0002.bp.PMORowPutBP;
import nccloud.web.mmpac.pmo.action.PmoCardPutAction;

public class putBeforeCheckRule implements IRule<PMOAggVO> {

	private static IUifService service = (IUifService) NCLocator.getInstance().lookup(IUifService.class.getName());

	@Override
	public void process(PMOAggVO[] vos) {
		try {
			// TODO Auto-generated method stub
			List<SaleOrderBVO> list = new ArrayList<SaleOrderBVO>();
			for (PMOAggVO vo : vos) {
				// 判断是否是需要控制的业务单元
				PMOHeadVO pmoHeadVO = vo.getParentVO();
				String pkstockorgStr = getPk_stockorg(pmoHeadVO.getPk_org());
				if (pkstockorgStr == null || pkstockorgStr.equals("")) {
					return;
				}
				PMOItemVO[] iSuperVOs = vo.getChildrenVO();
				for (int i = 0; i < iSuperVOs.length; i++) {
					PMOItemVO itemvo = iSuperVOs[i];
					// 判断是否类型是否为30
					if (itemvo.getVsrctype() == null || !itemvo.getVsrctype().equals("30")) {
						return;
					}
					Map<String, Object> valMap = getVbdef6(itemvo.getVsrcbid());
					// 销售发票表头pk_billtypecode=30-Cxx-12
					if (valMap.get("pk_billtypecode").equals("30-Cxx-12")
							|| valMap.get("pk_billtypecode").equals("30-Cxx-02")
							|| valMap.get("pk_billtypecode").equals("30-Cxx-08")
							|| valMap.get("pk_billtypecode").equals("30-Cxx-13")
							|| valMap.get("pk_billtypecode").equals("30-Cxx-16")) {
						return;
					}

					String code = valMap.get("code").toString();
					LocalDateTime dbilldate = LocalDateTime.parse(valMap.get("dbilldate").toString(),
							DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
					LocalDateTime targetDate1 = LocalDateTime.parse("2025-06-27 00:00:00",
							DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
					List<String> defMap = checkOrgCtrl1();
					if (!valMap.isEmpty()&& defMap.contains(code) && dbilldate.isBefore(targetDate1)) {
						return;
					}
					// 历史数据不考虑
					String storedDateStr = (String) valMap.get("creationtime");
					String targetDateStr = "2024-12-31 00:00:00";
					DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
					LocalDateTime storedDate = LocalDateTime.parse(storedDateStr, formatter);
					LocalDateTime targetDate = LocalDateTime.parse(targetDateStr, formatter);
					if (storedDate.isBefore(targetDate)) {
						return;
					}
					String vdef4Str = itemvo.getVdef4();// 齐套率
					String vdef4 = (vdef4Str != null) ? vdef4Str.toString() : "";
					double vdef4qty = (vdef4.isEmpty()) ? 0 : Double.parseDouble(vdef4);// 齐套率
					String vdef10Str = itemvo.getVdef10();// 齐套率标准
					String vdef10 = (vdef10Str != null) ? vdef10Str.toString() : "";
					double vdef10qty = (vdef10.isEmpty()) ? 0 : Double.parseDouble(vdef10);// 齐套率标准
					if (vdef4qty < vdef10qty) {
						throw new BusinessException("齐套率" + vdef4qty + "小于齐套率标准'" + vdef10qty + "'，无法保存！");
					}

				}
			}
		} catch (BusinessException e) {
			throw new RuntimeException(e);
		}
	}

	private Map<String, Object> getVbdef6(String vsrcbidStr) throws BusinessException {
		IUAPQueryBS queryBS = NCLocator.getInstance().lookup(IUAPQueryBS.class);
		String sql = " SELECT org_salesorg.CODE ,s.dbilldate, bt.pk_billtypecode,s.creationtime,b.vbdef12,d.nastnum FROM so_saleorder_b b\n"
				+ "INNER JOIN so_saleorder s ON s.csaleorderid = b.csaleorderid\n"
				+ " LEFT JOIN org_salesorg ON org_salesorg.PK_SALESORG = s.PK_ORG "
				+ "left join (select mm_mo.Vsrcbid,sum(nastnum) as nastnum \n" + "from mm_mo\n" + "where mm_mo.dr=0\n"
				+ "group by mm_mo.Vsrcbid) d on b.csaleorderbid=d.Vsrcbid\n"
				+ "INNER JOIN bd_billtype bt on bt.pk_billtypeid=s.ctrantypeid\n" + "where b.csaleorderbid='"
				+ vsrcbidStr + "' ";
		Map<String, Object> valList = (Map<String, Object>) queryBS.executeQuery(sql, new MapProcessor());
		return valList;
	}

	private String getPk_stockorg(String pk_stockorg) throws BusinessException {
		String sql = " select pk_stockorg from org_stockorg where code in ('C018','C029','C033','C039','C020','C019') and pk_stockorg='"
				+ pk_stockorg + "' ";
		String saleorderPK = (String) getQueryService().executeQuery(sql, new ColumnProcessor());
		return saleorderPK;
	}

	public IUAPQueryBS getQueryService() {
		return NCLocator.getInstance().lookup(IUAPQueryBS.class);
	}
	private List<String> checkOrgCtrl1() {
		List<String> list = new ArrayList<>();
		String strWhere = " pk_defdoclist in (select pk_defdoclist from bd_defdoclist where code='org-ctrl' and dr=0 )  and dr=0";
		try {
			DefdocVO[] defdocVOs = (DefdocVO[]) new HYSuperDMO().queryByWhereClause(DefdocVO.class, strWhere);
			if (defdocVOs != null && defdocVOs.length > 0) {
				for (DefdocVO defdocVO : defdocVOs) {
					if(defdocVO.getCode().equals("pmol")){
						list= Arrays.stream(defdocVO.getMemo().split(",")).map(String::trim).collect(Collectors.toList());
					}
				}
			}
		} catch (DAOException e) {
			e.printStackTrace();
		}
		return list;
	}
}
