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

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.NodeComponent;

import cn.hutool.core.collection.CollUtil;
import com.zt.plat.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessSampleAssayResultDO;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessSampleEntrustDetailDO;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessSampleEntrustFileDO;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessSampleEntrustProjectDO;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessSampleEntrustRegistrationDO;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessSampleAssayResultMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessSampleEntrustDetailMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessSampleEntrustFileMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessSampleEntrustProjectMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessSampleEntrustRegistrationMapper;
import com.zt.plat.module.qms.business.bus.liteflow.slot.SampleEntrustContext;
import com.zt.plat.module.qms.business.config.controller.vo.MaterialAssayStandardDetailRespVO;
import com.zt.plat.module.qms.business.config.dal.dataobject.ConfigEntrustSourceDO;
import com.zt.plat.module.qms.enums.QmsCommonConstant;

import jakarta.annotation.Resource;

@LiteflowComponent(id = "sampleEntrustUpdateDataCmp", name = "样品委托更新委托数据" )
public class SampleEntrustUpdateDataCmp extends NodeComponent {
	
	@Resource
	private BusinessSampleEntrustRegistrationMapper businessSampleEntrustRegistrationMapper;
	
	@Resource
	private BusinessSampleEntrustDetailMapper businessSampleEntrustDetailMapper;
	
	@Resource
	private BusinessSampleEntrustFileMapper businessSampleEntrustFileMapper;
	
	@Resource
	private BusinessSampleEntrustProjectMapper businessSampleEntrustProjectMapper;
	
	@Resource
	private BusinessSampleAssayResultMapper businessSampleAssayResultMapper;

	@Override
	public void process() throws Exception {
		//获取样品委托上下文
		SampleEntrustContext sampleEntrustContext = this.getContextBean(SampleEntrustContext.class);
		//样品委托
		BusinessSampleEntrustRegistrationDO sampleEntrustRegistration = sampleEntrustContext.getSampleEntrustRegistration();
		BusinessSampleEntrustRegistrationDO oldSampleEntrustRegistration = businessSampleEntrustRegistrationMapper.selectById(sampleEntrustRegistration.getId());
		sampleEntrustRegistration.setEntrustNumber(oldSampleEntrustRegistration.getEntrustNumber());//重新赋值委托单号

		//扩展信息
		String externalInfomation = sampleEntrustRegistration.getExternalInfomation();
		JSONObject extJsonObject = null;
		if (StringUtils.isNotBlank(externalInfomation)) {
			extJsonObject = JSON.parseObject(externalInfomation);
		}
		
		//获取委托来源配置
		ConfigEntrustSourceDO configEntrustSource = sampleEntrustContext.getConfigEntrustSource();
		if (StringUtils.isNotBlank(configEntrustSource.getCodeField()) && extJsonObject != null) {//如果委托单号来源于字段，则重新获取更新下
			String entrustNumber = extJsonObject.getString(configEntrustSource.getCodeField());
			sampleEntrustRegistration.setEntrustNumber(entrustNumber);
		}

		//处理上传文件
		List<BusinessSampleEntrustFileDO> businessSampleEntrustFileDOList = new ArrayList<>();
		//删除旧的
		businessSampleEntrustFileMapper.physicalDeleteByBusinessSampleEntrustRegistrationId(sampleEntrustRegistration.getId());
		if (extJsonObject != null && extJsonObject.getJSONArray("uploadFile") != null) {
			JSONArray uploadFileJsonArray = extJsonObject.getJSONArray("uploadFile");
			if(!uploadFileJsonArray.isEmpty()){
	            for(int i = 0; i < uploadFileJsonArray.size(); i++){
	                JSONObject fieldExtension = uploadFileJsonArray.getJSONObject(i);
	                BusinessSampleEntrustFileDO businessSampleEntrustFileDO = new BusinessSampleEntrustFileDO();
	                businessSampleEntrustFileDO.setBusinessSampleEntrustRegistrationId(sampleEntrustRegistration.getId());
	                businessSampleEntrustFileDO.setFileId(fieldExtension.getLong("id"));
	                businessSampleEntrustFileDO.setFileName(fieldExtension.getString("name"));
	                businessSampleEntrustFileDO.setFileCategory(QmsCommonConstant.ENTRUST_ATTACHMENT_CATEGORY_REGISTRATION);
	                businessSampleEntrustFileDOList.add(businessSampleEntrustFileDO);
	            }
	        }
			
		}
		
		//先删除旧的
		List<BusinessSampleEntrustDetailDO> sampleEntrustDetailOldList = businessSampleEntrustDetailMapper.selectList(new LambdaQueryWrapperX<BusinessSampleEntrustDetailDO>().eq(BusinessSampleEntrustDetailDO::getBusinessSampleEntrustRegistrationId, sampleEntrustRegistration.getId()));
		if (CollUtil.isNotEmpty(sampleEntrustDetailOldList)) {
			List<Long> sampleEntrustDetailIdList = sampleEntrustDetailOldList.stream().map(m -> m.getId()).collect(Collectors.toList());
			List<BusinessSampleEntrustProjectDO> sampleEntrustProjectList = businessSampleEntrustProjectMapper.selectList(new LambdaQueryWrapperX<BusinessSampleEntrustProjectDO>().in(BusinessSampleEntrustProjectDO::getBusinessSampleEntrustDetailId, sampleEntrustDetailIdList));
			if (CollUtil.isNotEmpty(sampleEntrustProjectList)) {
				List<Long> sampleEntrustProjectIdList = sampleEntrustProjectList.stream().map(m -> m.getId()).collect(Collectors.toList());
				//删除样品对应的检验项目
				businessSampleEntrustProjectMapper.physicalDeleteByIds(sampleEntrustProjectIdList);
			}
			List<BusinessSampleAssayResultDO> sampleAssayResultList = businessSampleAssayResultMapper.selectList(new LambdaQueryWrapperX<BusinessSampleAssayResultDO>().in(BusinessSampleAssayResultDO::getBusinessSampleEntrustDetailId, sampleEntrustDetailIdList));
			if (CollUtil.isNotEmpty(sampleAssayResultList)) {
				List<Long> sampleAssayResultIdList = sampleAssayResultList.stream().map(m -> m.getId()).collect(Collectors.toList());
				//删除来样品位
				businessSampleAssayResultMapper.physicalDeleteByIds(sampleAssayResultIdList);
			}
			
			//删除委托登记明细
			businessSampleEntrustDetailMapper.physicalDeleteByIds(sampleEntrustDetailIdList);
		}
		
		//保存更新新的
		List<BusinessSampleAssayResultDO> sampleAssayResultList = new ArrayList<>();

		//提取委托单号
	    String year = null;
	    String number = null;
        Pattern pattern = Pattern.compile("\\((\\d+)\\)第(\\d+)号");
        //一般委托或仲裁委托才提取
        if ("xsqywtybwt".equals(configEntrustSource.getKey()) || "xsqywtzcwt".equals(configEntrustSource.getKey())) {
    	    Matcher matcher = pattern.matcher(sampleEntrustRegistration.getEntrustNumber());
    	    if (matcher.find()) {
    	        year = matcher.group(1); // "2026"
    	        number = matcher.group(2); // "0027"
    	    }
		}
		List<BusinessSampleEntrustDetailDO> sampleEntrustDetailList = sampleEntrustContext.getSampleEntrustDetailList();
		for (BusinessSampleEntrustDetailDO businessSampleEntrustDetail : sampleEntrustDetailList) {
			businessSampleEntrustDetail.setBusinessSampleEntrustRegistrationId(sampleEntrustRegistration.getId());

			if (StringUtils.isNotBlank(businessSampleEntrustDetail.getForecastResult())) {
				BusinessSampleAssayResultDO sampleAssayResult = new BusinessSampleAssayResultDO();
				sampleAssayResult.setBusinessSampleEntrustDetailId(businessSampleEntrustDetail.getId());
				sampleAssayResult.setData(businessSampleEntrustDetail.getForecastResult());
				sampleAssayResultList.add(sampleAssayResult);
			}
			
			//一般委托
			if ("xsqywtybwt".equals(configEntrustSource.getKey())) {
				String sampleCode = "W" + year + number + "-" + StringUtils.leftPad(businessSampleEntrustDetail.getSort().toString(), 2, "0");
				businessSampleEntrustDetail.setSampleCode(sampleCode);
			} else if ("xsqywtzcwt".equals(configEntrustSource.getKey())) {//仲裁委托
				String sampleCode = "ZW" + year + number + "-" + StringUtils.leftPad(businessSampleEntrustDetail.getSort().toString(), 2, "0");
				businessSampleEntrustDetail.setSampleCode(sampleCode);
			} else if ("ztgmwt".equals(configEntrustSource.getKey())) {//中铜国贸商检委托，来样编号与样品编号一致
				businessSampleEntrustDetail.setSampleCode(businessSampleEntrustDetail.getEntrustSampleCode());//样品编号与来样编号一致
			}
			
		}
		
		List<BusinessSampleEntrustProjectDO> sampleEntrustProjectList = sampleEntrustContext.getSampleEntrustProjectList();	
		for (BusinessSampleEntrustProjectDO businessSampleEntrustProject : sampleEntrustProjectList) {
			MaterialAssayStandardDetailRespVO materialAssayStandardDetail = sampleEntrustContext.getMaterialAssayStandardDetailById(businessSampleEntrustProject.getMaterialAssayStandardDetailId());
			businessSampleEntrustProject.setDictionaryProjectId(materialAssayStandardDetail.getDictionaryProjectId());
		}
		
		//保存样品委托登记
		businessSampleEntrustRegistrationMapper.updateById(sampleEntrustRegistration);
		
		//保存样品明细
		if (CollUtil.isNotEmpty(sampleEntrustDetailList)) {
			businessSampleEntrustDetailMapper.insertBatch(sampleEntrustDetailList);
		}

		//保存检测项目
		if (CollUtil.isNotEmpty(sampleEntrustProjectList)) {
			businessSampleEntrustProjectMapper.insertBatch(sampleEntrustProjectList);
		}
		
		//保存上传的附件
		if (CollUtil.isNotEmpty(businessSampleEntrustFileDOList)) {
			businessSampleEntrustFileMapper.insertBatch(businessSampleEntrustFileDOList);
		}
		
		//保存来样元素
		if (CollUtil.isNotEmpty(sampleAssayResultList)) {
			businessSampleAssayResultMapper.insertBatch(sampleAssayResultList);
		}

	}
	
}
