package com.zt.plat.module.qms.business.bus.liteflow.sample.flow;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.qlexpress4.Express4Runner;
import com.alibaba.qlexpress4.QLOptions;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.NodeComponent;
import com.zt.plat.framework.common.exception.ServiceException;
import com.zt.plat.framework.security.core.LoginUser;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessAssayTaskDataDO;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessHandoverRecordSubDO;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessSubSampleAnalysisGroupDO;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessSubSampleDO;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessHandoverRecordSubMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessSubSampleAnalysisGroupMapper;
import com.zt.plat.module.qms.business.bus.liteflow.slot.SampleFlowContext;
import com.zt.plat.module.qms.business.config.dal.dataobject.ConfigRuleDO;
import com.zt.plat.module.qms.business.config.dal.dataobject.ConfigSampleFlowDO;
import com.zt.plat.module.qms.business.config.dal.dataobject.ConfigSubSampleDO;
import com.zt.plat.module.qms.business.config.dal.mapper.ConfigRuleMapper;
import com.zt.plat.module.qms.business.config.service.ConfigSampleFlowService;
//import com.zt.plat.module.qms.business.config.service.ConfigSubSampleService;
import com.zt.plat.module.qms.core.sampleflow.SampleFlowDefinition;
import com.zt.plat.module.qms.core.sampleflow.SampleFlowNode;
import com.zt.plat.module.qms.enums.QmsCommonConstant;

import cn.hutool.core.collection.CollUtil;
import jakarta.annotation.Resource;

@LiteflowComponent(id = "sampleSubProcessUpdateCmp", name = "子样流程节点更新")
public class SampleSubProcessUpdateCmp extends NodeComponent {
	
//	@Resource
//	private ConfigSubSampleService configSubSampleService;
	
	@Resource
	private Express4Runner express4Runner;
	
	@Resource
	private ConfigRuleMapper configRuleMapper;
	
	@Resource
	private ConfigSampleFlowService configSampleFlowService;
	
	@Resource
	private BusinessHandoverRecordSubMapper businessHandoverRecordSubMapper;
	
	@Resource
	private BusinessSubSampleAnalysisGroupMapper businessSubSampleAnalysisGroupMapper;

	@Override
	public void process() throws Exception {
		SampleFlowContext sampleFlowContext = this.getContextBean(SampleFlowContext.class);
		String currentSampleFlowKey = sampleFlowContext.getCurrentSampleFlowKey();
		LoginUser loginUser = sampleFlowContext.getLoginUser();
		String loginRealname = sampleFlowContext.getLoginRealname();
		LocalDateTime currentDateTime = sampleFlowContext.getCurrentDateTime();
		List<Long> sampleIdList = sampleFlowContext.getSampleIdList();
		List<BusinessSubSampleDO> busSubCsampleList = sampleFlowContext.getBusinessSubSampleList();
		List<BusinessAssayTaskDataDO> businessAssayTaskDataList = sampleFlowContext.getBusinessAssayTaskDataList();
		//查询历史交接记录
		List<BusinessHandoverRecordSubDO> businessHandoverRecordSubDOList = businessHandoverRecordSubMapper.selectByBusinessSubSampleIds(sampleIdList);
		//查询子样分析班组
		List<BusinessSubSampleAnalysisGroupDO> businessSubSampleAnalysisGroupDOList = businessSubSampleAnalysisGroupMapper.selectByBusinessSubSampleIds(sampleIdList);
		
		for (BusinessSubSampleDO businessSubSample : busSubCsampleList) {
			ConfigSampleFlowDO configSampleFlow = configSampleFlowService.getConfigSampleFlow(businessSubSample.getConfigSampleFlowId());
			String configSampleFlowContent = configSampleFlow.getContent();
			//样品流程定义
			SampleFlowDefinition sampleFlowDefinition = JSON.parseObject(configSampleFlowContent, SampleFlowDefinition.class);
			//获取流程列表
			List<SampleFlowNode> flowNodeList = sampleFlowDefinition.getFlowNodeList();
			//查询当前流程节点
			SampleFlowNode currFlowNode = flowNodeList.stream().filter(f -> f.getNodeKey().equals(currentSampleFlowKey)).findFirst().orElse(null);
			//获取下一个流程节点列表
			List<SampleFlowNode> nextFlowNodeList = currFlowNode.getNextFlowNodeList();
			//查询默认节点
			SampleFlowNode nextFlowNode = nextFlowNodeList.stream().filter(f -> f.getIsDefault() != null && f.getIsDefault()).findFirst().orElse(null);
			//未找到默认节点
			if (nextFlowNode == null) {
				//循环下一个流程节点列表，根据条件判断
				for (SampleFlowNode flowNode : nextFlowNodeList) {
					ConfigRuleDO conditionRule = configRuleMapper.selectLatestConfigRuleByCode(flowNode.getCondition());
					Boolean isMeetCondition = false;
			        Map<String, Object> context = new HashMap<>();
			        ConfigSubSampleDO configSubSample = sampleFlowContext.getConfigSubSampleById(businessSubSample.getConfigSubSampleId());
			        Boolean hasSubSimpleCodeRule = configSubSample != null && StringUtils.isNotBlank(configSubSample.getSimpleCodeRule());
			        Boolean hasSubSampleEncrypt = businessHandoverRecordSubDOList.stream().filter(f -> f.getBusinessSubSampleId().equals(businessSubSample.getId())).anyMatch(m -> QmsCommonConstant.FlOW_NODE_SAMPLE_ENCRYPT.equals(m.getSampleFlowNodeKey()));
			        
			        if (CollUtil.isNotEmpty(businessSubSampleAnalysisGroupDOList)) {
			        	List<BusinessSubSampleAnalysisGroupDO> curSubSampleAnalysisGroupDOList = businessSubSampleAnalysisGroupDOList.stream().filter(f -> f.getBusinessSubSampleId().equals(businessSubSample.getId())).collect(Collectors.toList());
						Boolean hasAllDeptAnalyzed = curSubSampleAnalysisGroupDOList.stream().allMatch(m -> ( "已完成".equals(m.getSampleStatus()) || "已收样".equals(m.getSampleStatus()) ) );
						Boolean hasCurDeptAnalyzed = curSubSampleAnalysisGroupDOList.stream().filter(f -> f.getAssayDepartmentId().equals(loginUser.getVisitDeptId())).allMatch(m -> ( "已完成".equals(m.getSampleStatus()) || "已收样".equals(m.getSampleStatus()) ) );
				        context.put("hasAllDeptAnalyzed", hasAllDeptAnalyzed);
						context.put("hasCurDeptAnalyzed", hasCurDeptAnalyzed);
					}
			        
			        context.put("hasSubSimpleCodeRule", hasSubSimpleCodeRule);
			        context.put("hasSubSampleEncrypt", hasSubSampleEncrypt);
					try {
//						isMeetCondition = (Boolean) express4Runner.execute(conditionRule.getExpression(), context, null, false, false);
						isMeetCondition = (Boolean) express4Runner.execute(conditionRule.getExpression(), context, QLOptions.DEFAULT_OPTIONS).getResult();
					} catch (Exception e) {
						e.printStackTrace();
						throw new ServiceException(1_032_100_000, e.getMessage());
					}
					//满足条件，赋值下一个流程节点，跳出循环
					if (isMeetCondition) {
						nextFlowNode = flowNode;
						break;
					}
					
				}
			}
			businessSubSample.setNextSampleFlowNode(nextFlowNode.getNextFlowNodeName());
			businessSubSample.setSampleFlowNodeKey(nextFlowNode.getNodeKey());
			businessSubSample.setSampleFlowNodeTime(currentDateTime);
			
			List<BusinessAssayTaskDataDO> subSampleAssayTaskDataList = businessAssayTaskDataList.stream().filter(f -> f.getBusinessSubSampleId().equals(businessSubSample.getId())).collect(Collectors.toList());
			for (BusinessAssayTaskDataDO businessAssayTaskDataDO : subSampleAssayTaskDataList) {
				businessAssayTaskDataDO.setSampleFlowNodeKey(QmsCommonConstant.FLOW_NODE_ANALYSIS);//样品分析
				businessAssayTaskDataDO.setSampleFlowNodeTime(currentDateTime);

			}
		}

		//如果是班组收样，需要更新分析班组表
		if (QmsCommonConstant.FLOW_NODE_TEAM_RECEIVE.equals(currentSampleFlowKey)) {
			List<BusinessSubSampleAnalysisGroupDO> curDeptSubSampleAnalysisGroupDOList = businessSubSampleAnalysisGroupDOList.stream().filter(f -> f.getAssayDepartmentId().equals(loginUser.getVisitDeptId())).collect(Collectors.toList());
			for (BusinessSubSampleAnalysisGroupDO businessSubSampleAnalysisGroupDO : curDeptSubSampleAnalysisGroupDOList) {
				businessSubSampleAnalysisGroupDO.setSampleReceiveTime(currentDateTime);
				businessSubSampleAnalysisGroupDO.setSampleReceiver(loginRealname);
				businessSubSampleAnalysisGroupDO.setSampleStatus("已收样");
			}
			sampleFlowContext.setBusinessSubSampleAnalysisGroupList(curDeptSubSampleAnalysisGroupDOList);
		}
		
		//如果是班组送样，需要更新分析班组表
		if (QmsCommonConstant.FLOW_NODE_TEAM_SEND.equals(currentSampleFlowKey)) {
			List<BusinessSubSampleAnalysisGroupDO> curDeptSubSampleAnalysisGroupDOList = businessSubSampleAnalysisGroupDOList.stream().filter(f -> f.getAssayDepartmentId().equals(loginUser.getVisitDeptId())).collect(Collectors.toList());
			for (BusinessSubSampleAnalysisGroupDO businessSubSampleAnalysisGroupDO : curDeptSubSampleAnalysisGroupDOList) {
				businessSubSampleAnalysisGroupDO.setIsSend(QmsCommonConstant.YES);
			}
			sampleFlowContext.setBusinessSubSampleAnalysisGroupList(curDeptSubSampleAnalysisGroupDOList);
			
		}
	}

}
