package com.zt.plat.module.qms.business.bus.service;

import cn.hutool.core.collection.CollUtil;
import com.zt.plat.module.qms.business.bus.controller.vo.*;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;

import org.springframework.validation.annotation.Validated;

import java.util.*;
import java.util.stream.Collectors;

import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessAssayTaskDataDO;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessAssayParameterDataMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessAssayProjectDataMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessAssayTaskDataMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessAssayTaskParameterDataMapper;
import com.zt.plat.module.qms.business.config.controller.vo.ConfigSubSampleMethodConfInfo;
import com.zt.plat.module.qms.business.config.controller.vo.ConfigSubSampleMethodConfItem;
import com.zt.plat.module.qms.business.config.controller.vo.ConfigSubSampleMethodConfPoint;
import com.zt.plat.module.qms.business.config.controller.vo.ConfigSubSampleMethodExtendRespVO;
import com.zt.plat.module.qms.business.config.dal.mapper.ConfigSubSampleMethodMapper;
import com.zt.plat.framework.common.pojo.PageResult;
import com.alibaba.fastjson2.JSON;
import com.zt.plat.framework.common.util.object.BeanUtils;
import static com.zt.plat.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.zt.plat.module.qms.enums.ErrorCodeConstants.*;

/**
 * 子样检测任务业务 Service 实现类
 *
 * @author 后台管理
 */
@Service
@Validated
public class BusinessAssayTaskDataServiceImpl implements BusinessAssayTaskDataService {

    @Resource
    private BusinessAssayTaskDataMapper businessAssayTaskDataMapper;
    
    @Resource
    private BusinessAssayTaskParameterDataMapper businessAssayTaskParameterDataMapper;
    
    @Resource
    private BusinessAssayProjectDataMapper businessAssayProjectDataMapper;
    
    @Resource
    private BusinessAssayParameterDataMapper businessAssayParameterDataMapper;
    
    @Resource
    private ConfigSubSampleMethodMapper configSubSampleMethodMapper;

    @Override
    public BusinessAssayTaskDataRespVO createBusinessAssayTaskData(BusinessAssayTaskDataSaveReqVO createReqVO) {
        // 插入
        BusinessAssayTaskDataDO businessAssayTaskData = BeanUtils.toBean(createReqVO, BusinessAssayTaskDataDO.class);
        businessAssayTaskDataMapper.insert(businessAssayTaskData);
        // 返回
        return BeanUtils.toBean(businessAssayTaskData, BusinessAssayTaskDataRespVO.class);
    }

    @Override
    public void updateBusinessAssayTaskData(BusinessAssayTaskDataSaveReqVO updateReqVO) {
        // 校验存在
        validateBusinessAssayTaskDataExists(updateReqVO.getId());
        // 更新
        BusinessAssayTaskDataDO updateObj = BeanUtils.toBean(updateReqVO, BusinessAssayTaskDataDO.class);
        businessAssayTaskDataMapper.updateById(updateObj);
    }

    @Override
    public void deleteBusinessAssayTaskData(Long id) {
        // 校验存在
        validateBusinessAssayTaskDataExists(id);
        // 删除
        businessAssayTaskDataMapper.deleteById(id);
    }

    @Override
        public void deleteBusinessAssayTaskDataListByIds(List<Long> ids) {
        // 校验存在
        validateBusinessAssayTaskDataExists(ids);
        // 删除
        businessAssayTaskDataMapper.deleteByIds(ids);
        }

    private void validateBusinessAssayTaskDataExists(List<Long> ids) {
        List<BusinessAssayTaskDataDO> list = businessAssayTaskDataMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(BUSINESS_ASSAY_TASK_DATA_NOT_EXISTS);
        }
    }

    private void validateBusinessAssayTaskDataExists(Long id) {
        if (businessAssayTaskDataMapper.selectById(id) == null) {
            throw exception(BUSINESS_ASSAY_TASK_DATA_NOT_EXISTS);
        }
    }

    @Override
    public BusinessAssayTaskDataDO getBusinessAssayTaskData(Long id) {
        return businessAssayTaskDataMapper.selectById(id);
    }

	@Override
	public List<BusinessAssayTaskDataGroupRespVO> getUnAssayTaskGroupList(BusinessAssayTaskDataReqVO reqVO) {
//		System.out.println("查询时租户id：" + TenantContextHolder.getTenantId());
		return businessAssayTaskDataMapper.selectUnAssayTaskGroupList(reqVO);
	}

	@Override
	public List<BusinessAssayTaskDataGroupRespVO> getUnAssayTaskGroupTypeList(BusinessAssayTaskDataReqVO reqVO) {
		return businessAssayTaskDataMapper.selectUnAssayTaskGroupTypeList(reqVO);
	}

	@Override
	public List<BusinessAssayTaskDataGroupRespVO> getUnAuditTaskGroupList(BusinessAssayTaskDataReqVO reqVO) {
		return businessAssayTaskDataMapper.selectUnAuditTaskGroupList(reqVO);
	}

	@Override
	public List<BusinessAssayTaskDataExtendRespVO> getBusinessAssayTaskDataList(BusinessAssayTaskDataReqVO reqVO) {
		List<BusinessAssayTaskDataExtendRespVO> list = businessAssayTaskDataMapper.selectList(reqVO);
		if (CollUtil.isEmpty(list)) {
			return list;
		}
		List<Long> configSubSampleIdList = list.stream().map(m -> m.getConfigSubSampleId()).collect(Collectors.toList());

		List<ConfigSubSampleMethodExtendRespVO> configSubSampleMethodList = new ArrayList<>();
		if (reqVO.getConfigAssayMethodId() != null) {
			configSubSampleMethodList = configSubSampleMethodMapper.selectByConfigSubSampleIdsAndConfigAssayMethodId(configSubSampleIdList, reqVO.getConfigAssayMethodId());
		} else if (reqVO.getConfigAssayMethodDictionaryBusinessId() != null) {
			configSubSampleMethodList = configSubSampleMethodMapper.selectByConfigSubSampleIdsAndConfigAssayMethodDictionaryBusinessId(configSubSampleIdList, reqVO.getConfigAssayMethodDictionaryBusinessId());
		} else if (StringUtils.isNotBlank(reqVO.getConfigAssayMethodDictionaryBusinessKey())) {
			configSubSampleMethodList = configSubSampleMethodMapper.selectByConfigSubSampleIdsAndConfigAssayMethodDictionaryBusinessKey(configSubSampleIdList, reqVO.getConfigAssayMethodDictionaryBusinessKey());
		}
		
		List<Long> businessAssayTaskDataIdList = list.stream().map(m -> m.getId()).collect(Collectors.toList());
		//查询检测项目
		List<BusinessAssayProjectDataExtendRespVO> businessAssayProjectDataList = businessAssayProjectDataMapper.selectByBusinessAssayTaskDataIds(businessAssayTaskDataIdList);
		List<Long> businessAssayProjectDataIdList = businessAssayProjectDataList.stream().map(m -> m.getId()).collect(Collectors.toList());
		//查询检测项目参数
		List<BusinessAssayParameterDataExtendRespVO> businessAssayParameterDataList = businessAssayParameterDataMapper.selectExtendByBusinessAssayProjectDataIds(businessAssayProjectDataIdList);
		//查询分析任务属性
		List<BusinessAssayTaskParameterDataExtendRespVO> businessAssayTaskParameterDataList = businessAssayTaskParameterDataMapper.selectExtendByBusinessAssayTaskDataIds(businessAssayTaskDataIdList);
		
		
    	for (BusinessAssayTaskDataExtendRespVO businessAssayTaskData : list) {
    		ConfigSubSampleMethodExtendRespVO configSubSampleMethod = configSubSampleMethodList.stream().filter(f -> f.getConfigSubSampleId().equals(businessAssayTaskData.getConfigSubSampleId()) && f.getConfigAssayMethodId().equals(businessAssayTaskData.getConfigAssayMethodId())).findFirst().orElse(null);
    		String configInfomation = configSubSampleMethod.getConfigInfomation();
			if (StringUtils.isNotBlank(configInfomation)) {
				ConfigSubSampleMethodConfInfo configSubSampleMethodConfInfo = JSON.parseObject(configInfomation, ConfigSubSampleMethodConfInfo.class);
				List<ConfigSubSampleMethodConfItem> getParamList = configSubSampleMethodConfInfo.getGetParam();
				StringBuilder ingredientInfoBuilder = new StringBuilder();
				for (ConfigSubSampleMethodConfItem configSubSampleMethodConfItem : getParamList) {
					ConfigSubSampleMethodConfPoint target = configSubSampleMethodConfItem.getTarget();
					if (StringUtils.isNotBlank(target.getProject())) {//来自检测项目参数
						List<String> projectList = Arrays.asList(target.getProject().split(","));//来源可以有多个
						for (String project : projectList) {
							String parameter = target.getParameter();
							BusinessAssayProjectDataExtendRespVO currentBusinessAssayProjectData = businessAssayProjectDataList.stream().filter(f -> f.getBusinessAssayTaskDataId().equals(businessAssayTaskData.getId()) && project.equals(f.getSimpleName())).findFirst().orElse(null);
							if (currentBusinessAssayProjectData == null) {//如果检测项目为空，则跳出当前循环
								continue;
							}
							BusinessAssayParameterDataExtendRespVO currentBusinessAssayParameterData = businessAssayParameterDataList.stream().filter(f -> f.getBusinessAssayProjectDataId().equals(currentBusinessAssayProjectData.getId()) && parameter.equals(f.getParameterKey())).findFirst().orElse(null);
							if (currentBusinessAssayParameterData != null && StringUtils.isNotBlank(currentBusinessAssayParameterData.getValue())) {
								ingredientInfoBuilder.append(currentBusinessAssayParameterData.getParameterName()).append("：").append(currentBusinessAssayParameterData.getValue()).append("、");
								break;
							}
						}
						
					} else if (StringUtils.isNotBlank(target.getAttribute())) {//来自分析任务属性
						BusinessAssayTaskParameterDataExtendRespVO currentBusinessAssayTaskParameterData = businessAssayTaskParameterDataList.stream().filter(f -> f.getBusinessAssayTaskDataId().equals(businessAssayTaskData.getId()) && target.getAttribute().endsWith(f.getKey())).findFirst().orElse(null);
						if (currentBusinessAssayTaskParameterData != null && StringUtils.isNotBlank(currentBusinessAssayTaskParameterData.getValue())) {
							ingredientInfoBuilder.append(currentBusinessAssayTaskParameterData.getParameterName()).append("：").append(currentBusinessAssayTaskParameterData.getValue()).append("、");
						}
					}
					
				}
				if (ingredientInfoBuilder.length() > 0) {
					ingredientInfoBuilder.delete(ingredientInfoBuilder.length() - 1, ingredientInfoBuilder.length());
				}
				businessAssayTaskData.setIngredientInfo(ingredientInfoBuilder.toString());
			}
		}
    	
		return list;
	}

    @Override
    public PageResult<BusinessAssayTaskDataExtendRespVO> getBusinessAssayTaskDataPage(BusinessAssayTaskDataPageReqVO pageReqVO) {
    	PageResult<BusinessAssayTaskDataExtendRespVO> page = businessAssayTaskDataMapper.selectPage(pageReqVO);
    	List<BusinessAssayTaskDataExtendRespVO> list = page.getList();
		if (CollUtil.isEmpty(list)) {
			return page;
		}
		List<Long> configSubSampleIdList = list.stream().map(m -> m.getConfigSubSampleId()).collect(Collectors.toList());
		List<ConfigSubSampleMethodExtendRespVO> configSubSampleMethodList = new ArrayList<>();
		if (pageReqVO.getConfigAssayMethodId() != null) {
			configSubSampleMethodList = configSubSampleMethodMapper.selectByConfigSubSampleIdsAndConfigAssayMethodId(configSubSampleIdList, pageReqVO.getConfigAssayMethodId());
		} else if (pageReqVO.getConfigAssayMethodDictionaryBusinessId() != null) {
			configSubSampleMethodList = configSubSampleMethodMapper.selectByConfigSubSampleIdsAndConfigAssayMethodDictionaryBusinessId(configSubSampleIdList, pageReqVO.getConfigAssayMethodDictionaryBusinessId());
		} else if (StringUtils.isNotBlank(pageReqVO.getConfigAssayMethodDictionaryBusinessKey())) {
			configSubSampleMethodList = configSubSampleMethodMapper.selectByConfigSubSampleIdsAndConfigAssayMethodDictionaryBusinessKey(configSubSampleIdList, pageReqVO.getConfigAssayMethodDictionaryBusinessKey());
		}
		
		List<Long> businessAssayTaskDataIdList = list.stream().map(m -> m.getId()).collect(Collectors.toList());
		//查询检测项目
		List<BusinessAssayProjectDataExtendRespVO> businessAssayProjectDataList = businessAssayProjectDataMapper.selectByBusinessAssayTaskDataIds(businessAssayTaskDataIdList);
		List<Long> businessAssayProjectDataIdList = businessAssayProjectDataList.stream().map(m -> m.getId()).collect(Collectors.toList());
		//查询检测项目参数
		List<BusinessAssayParameterDataExtendRespVO> businessAssayParameterDataList = businessAssayParameterDataMapper.selectExtendByBusinessAssayProjectDataIds(businessAssayProjectDataIdList);
		//查询分析任务属性
		List<BusinessAssayTaskParameterDataExtendRespVO> businessAssayTaskParameterDataList = businessAssayTaskParameterDataMapper.selectExtendByBusinessAssayTaskDataIds(businessAssayTaskDataIdList);
		
    	for (BusinessAssayTaskDataExtendRespVO businessAssayTaskData : list) {
    		ConfigSubSampleMethodExtendRespVO configSubSampleMethod = configSubSampleMethodList.stream().filter(f -> f.getConfigSubSampleId().equals(businessAssayTaskData.getConfigSubSampleId()) && f.getConfigAssayMethodId().equals(businessAssayTaskData.getConfigAssayMethodId())).findFirst().orElse(null);
    		String configInfomation = configSubSampleMethod.getConfigInfomation();
			if (StringUtils.isNotBlank(configInfomation)) {
				ConfigSubSampleMethodConfInfo configSubSampleMethodConfInfo = JSON.parseObject(configInfomation, ConfigSubSampleMethodConfInfo.class);
				List<ConfigSubSampleMethodConfItem> getParamList = configSubSampleMethodConfInfo.getGetParam();
				StringBuilder ingredientInfoBuilder = new StringBuilder();
				for (ConfigSubSampleMethodConfItem configSubSampleMethodConfItem : getParamList) {
					ConfigSubSampleMethodConfPoint target = configSubSampleMethodConfItem.getTarget();
					if (StringUtils.isNotBlank(target.getProject())) {//来自检测项目参数
						List<String> projectList = Arrays.asList(target.getProject().split(","));//来源可以有多个
						for (String project : projectList) {
							String parameter = target.getParameter();
							BusinessAssayProjectDataExtendRespVO currentBusinessAssayProjectData = businessAssayProjectDataList.stream().filter(f -> f.getBusinessAssayTaskDataId().equals(businessAssayTaskData.getId()) && project.equals(f.getSimpleName())).findFirst().orElse(null);
							if (currentBusinessAssayProjectData == null) {//如果检测项目为空，则跳出当前循环
								continue;
							}
							BusinessAssayParameterDataExtendRespVO currentBusinessAssayParameterData = businessAssayParameterDataList.stream().filter(f -> f.getBusinessAssayProjectDataId().equals(currentBusinessAssayProjectData.getId()) && parameter.equals(f.getParameterKey())).findFirst().orElse(null);
							if (currentBusinessAssayParameterData != null && StringUtils.isNotBlank(currentBusinessAssayParameterData.getValue())) {
								ingredientInfoBuilder.append(currentBusinessAssayParameterData.getParameterName()).append("：").append(currentBusinessAssayParameterData.getValue()).append("、");
								break;
							}
						}
					} else if (StringUtils.isNotBlank(target.getAttribute())) {//来自分析任务属性
						BusinessAssayTaskParameterDataExtendRespVO currentBusinessAssayTaskParameterData = businessAssayTaskParameterDataList.stream().filter(f -> f.getBusinessAssayTaskDataId().equals(businessAssayTaskData.getId()) && target.getAttribute().endsWith(f.getKey())).findFirst().orElse(null);
						if (currentBusinessAssayTaskParameterData != null && StringUtils.isNotBlank(currentBusinessAssayTaskParameterData.getValue())) {
							ingredientInfoBuilder.append(currentBusinessAssayTaskParameterData.getParameterName()).append("：").append(currentBusinessAssayTaskParameterData.getValue()).append("、");
						}
					}
				}
				if (ingredientInfoBuilder.length() > 0) {
					ingredientInfoBuilder.delete(ingredientInfoBuilder.length() - 1, ingredientInfoBuilder.length());
				}
				businessAssayTaskData.setIngredientInfo(ingredientInfoBuilder.toString());
			}
		}
        return page;
    }

}