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

import cn.hutool.core.collection.CollUtil;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

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

import com.zt.plat.framework.common.pojo.PageResult;
import com.zt.plat.framework.common.pojo.PageParam;
import com.zt.plat.framework.common.util.object.BeanUtils;
import com.zt.plat.module.qms.business.bus.controller.vo.*;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessSampleEntrustUnStandardProjectDO;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessSubSampleAnalysisGroupDO;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessSampleEntrustUnStandardProjectMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessSubSampleAnalysisGroupMapper;

import static com.zt.plat.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.zt.plat.framework.common.util.collection.CollectionUtils.convertList;
import static com.zt.plat.framework.common.util.collection.CollectionUtils.diffList;
import static com.zt.plat.module.qms.enums.ErrorCodeConstants.*;

/**
 * 委检登记样品检测项目表(无标准) Service 实现类
 *
 * @author 后台管理
 */
@Service
@Validated
public class BusinessSampleEntrustUnStandardProjectServiceImpl implements BusinessSampleEntrustUnStandardProjectService {

    @Resource
    private BusinessSampleEntrustUnStandardProjectMapper businessSampleEntrustUnStandardProjectMapper;
    
    @Resource
    private BusinessSubSampleAnalysisGroupMapper businessSubSampleAnalysisGroupMapper;

    @Override
    public BusinessSampleEntrustUnStandardProjectRespVO createBusinessSampleEntrustUnStandardProject(BusinessSampleEntrustUnStandardProjectSaveReqVO createReqVO) {
        // 插入
        BusinessSampleEntrustUnStandardProjectDO businessSampleEntrustUnStandardProject = BeanUtils.toBean(createReqVO, BusinessSampleEntrustUnStandardProjectDO.class);
        businessSampleEntrustUnStandardProjectMapper.insert(businessSampleEntrustUnStandardProject);
        // 返回
        return BeanUtils.toBean(businessSampleEntrustUnStandardProject, BusinessSampleEntrustUnStandardProjectRespVO.class);
    }

    @Override
    public void updateBusinessSampleEntrustUnStandardProject(BusinessSampleEntrustUnStandardProjectSaveReqVO updateReqVO) {
        // 校验存在
        validateBusinessSampleEntrustUnStandardProjectExists(updateReqVO.getId());
        // 更新
        BusinessSampleEntrustUnStandardProjectDO updateObj = BeanUtils.toBean(updateReqVO, BusinessSampleEntrustUnStandardProjectDO.class);
        businessSampleEntrustUnStandardProjectMapper.updateById(updateObj);
    }

    @Override
    public void deleteBusinessSampleEntrustUnStandardProject(Long id) {
        // 校验存在
        validateBusinessSampleEntrustUnStandardProjectExists(id);
        // 删除
        businessSampleEntrustUnStandardProjectMapper.deleteById(id);
    }

    @Override
        public void deleteBusinessSampleEntrustUnStandardProjectListByIds(List<Long> ids) {
        // 校验存在
        validateBusinessSampleEntrustUnStandardProjectExists(ids);
        // 删除
        businessSampleEntrustUnStandardProjectMapper.deleteByIds(ids);
        }

    private void validateBusinessSampleEntrustUnStandardProjectExists(List<Long> ids) {
        List<BusinessSampleEntrustUnStandardProjectDO> list = businessSampleEntrustUnStandardProjectMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(BUSINESS_SAMPLE_ENTRUST_UN_STANDARD_PROJECT_NOT_EXISTS);
        }
    }

    private void validateBusinessSampleEntrustUnStandardProjectExists(Long id) {
        if (businessSampleEntrustUnStandardProjectMapper.selectById(id) == null) {
            throw exception(BUSINESS_SAMPLE_ENTRUST_UN_STANDARD_PROJECT_NOT_EXISTS);
        }
    }

    @Override
    public BusinessSampleEntrustUnStandardProjectDO getBusinessSampleEntrustUnStandardProject(Long id) {
        return businessSampleEntrustUnStandardProjectMapper.selectById(id);
    }

    @Override
    public PageResult<BusinessSampleEntrustUnStandardProjectDO> getBusinessSampleEntrustUnStandardProjectPage(BusinessSampleEntrustUnStandardProjectPageReqVO pageReqVO) {
        return businessSampleEntrustUnStandardProjectMapper.selectPage(pageReqVO);
    }

	@Override
	public List<BusinessSampleEntrustUnStandardProjectExtendRespVO> getBusinessSampleEntrustUnStandardProjectList(
			BusinessSampleEntrustUnStandardProjectPageReqVO reqVO) {
		return businessSampleEntrustUnStandardProjectMapper.selectList(reqVO);
	}

	@Override
	public List<BusinessSampleEntrustUnStandardProjectExtendRespVO> listByBusinessBaseSampleId(Long businessBaseSampleId) {
		return businessSampleEntrustUnStandardProjectMapper.selectByBusinessBaseSampleId(businessBaseSampleId);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveAssayDept(BusinessSampleEntrustUnStandardProjectAssayDeptSaveReqVO reqVO) {
		List<BusinessSampleEntrustUnStandardProjectSaveReqVO> reqList = reqVO.getReqList();
		BusinessSubSampleSaveReqVO subSampleReqVO = reqVO.getSubSampleReqVO();

		List<BusinessSampleEntrustUnStandardProjectDO> saveList = new ArrayList<>();
		List<BusinessSampleEntrustUnStandardProjectDO> updateList = new ArrayList<>();
		List<BusinessSubSampleAnalysisGroupDO> saveAnalysisGroupDOList = new ArrayList<>();

		//查询旧的分析部门
		List<BusinessSubSampleAnalysisGroupDO> oldAnalysisGroupDOList = businessSubSampleAnalysisGroupMapper.selectByBusinessSubSampleId(subSampleReqVO.getId());
		//过滤出分析部门
		HashMap<Long, String> assayDepartmentMap = reqList.stream().collect(Collectors.toMap(
				BusinessSampleEntrustUnStandardProjectSaveReqVO::getAssayDepartmentId,
				BusinessSampleEntrustUnStandardProjectSaveReqVO::getAssayDepartmentName,
                (first, second) -> first,   // 保留第一个，丢弃后面的
                HashMap::new));
		for (Map.Entry<Long, String> entry : assayDepartmentMap.entrySet()) {
			Long assayDepartmentId = entry.getKey();
			String assayDepartmentName = entry.getValue();
			
			BusinessSubSampleAnalysisGroupDO businessSubSampleAnalysisGroupDO = new BusinessSubSampleAnalysisGroupDO();

			businessSubSampleAnalysisGroupDO.setBusinessBaseSampleId(subSampleReqVO.getBusinessBaseSampleId());
			businessSubSampleAnalysisGroupDO.setBusinessSubParentSampleId(subSampleReqVO.getBusinessSubParentSampleId());
			businessSubSampleAnalysisGroupDO.setBusinessSubSampleId(subSampleReqVO.getId());
			businessSubSampleAnalysisGroupDO.setAssayDepartmentId(assayDepartmentId);
			businessSubSampleAnalysisGroupDO.setAssayDepartmentName(assayDepartmentName);
			businessSubSampleAnalysisGroupDO.setSampleStatus("待收样");
			
			
			saveAnalysisGroupDOList.add(businessSubSampleAnalysisGroupDO);
		}
		
		for (BusinessSampleEntrustUnStandardProjectSaveReqVO req : reqList) {
			req.setBusinessSubSampleId(subSampleReqVO.getId());
			if (req.getId() == null) {
				saveList.add(BeanUtils.toBean(req, BusinessSampleEntrustUnStandardProjectDO.class));
			} else {
				updateList.add(BeanUtils.toBean(req, BusinessSampleEntrustUnStandardProjectDO.class));
			}
		}
		
		if (CollUtil.isNotEmpty(saveList)) {
			businessSampleEntrustUnStandardProjectMapper.insertBatch(saveList);
		}
		if (CollUtil.isNotEmpty(updateList)) {
			businessSampleEntrustUnStandardProjectMapper.updateBatch(updateList);
		}
		if (CollUtil.isNotEmpty(saveAnalysisGroupDOList)) {
			businessSubSampleAnalysisGroupMapper.insertBatch(saveAnalysisGroupDOList);
		}
		if (CollUtil.isNotEmpty(oldAnalysisGroupDOList)) {
			List<Long> oldAnalysisGroupDOIdList = oldAnalysisGroupDOList.stream().map(m -> m.getId()).collect(Collectors.toList());
			businessSubSampleAnalysisGroupMapper.deleteByIds(oldAnalysisGroupDOIdList);
		}
	}

}