package digital.laboratory.platform.imr.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import digital.laboratory.platform.common.core.exception.ValidateCodeException;
import digital.laboratory.platform.imr.convert.DrugCaseInfoConvert;
import digital.laboratory.platform.imr.convert.DrugMaterialInfoConvert;
import digital.laboratory.platform.imr.dto.DrugDepotsDTO;
import digital.laboratory.platform.imr.dto.DrugMaterialInfoDTO;
import digital.laboratory.platform.imr.entity.DrugCaseInfo;
import digital.laboratory.platform.imr.entity.DrugMaterialInfo;
import digital.laboratory.platform.imr.mapper.DrugCaseInfoMapper;
import digital.laboratory.platform.imr.mapper.DrugMaterialInfoMapper;
import digital.laboratory.platform.imr.query.DrugDepotsQuery;
import digital.laboratory.platform.imr.service.CommonFeignService;
import digital.laboratory.platform.imr.service.DrugCaseInfoService;
import digital.laboratory.platform.imr.service.DrugMaterialInfoService;
import digital.laboratory.platform.imr.vo.DrugCaseInfoVO;
import digital.laboratory.platform.imr.vo.DrugMaterialInfoVO;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author ChenJiangBao
* @description 针对表【b_drug_case_info(毒品库中关联的案事件信息)】的数据库操作Service实现
* @createDate 2024-11-07 12:04:42
*/
@Service
public class DrugCaseInfoServiceImpl extends ServiceImpl<DrugCaseInfoMapper, DrugCaseInfo>
    implements DrugCaseInfoService {

    @Resource
    private DrugMaterialInfoService drugMaterialInfoService;

    @Resource
    private DrugMaterialInfoMapper drugMaterialInfoMapper;

    @Resource
    private CommonFeignService commonFeignService;

    /**
     * 保存案件实体信息和毒品检材信息
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<DrugMaterialInfoVO> save(DrugDepotsDTO dto) {
        DrugCaseInfo drugCaseInfo = DrugCaseInfoConvert.dtoTOEntity(dto);
        boolean flag = true;
        if (StrUtil.isBlank(drugCaseInfo.getId())) {
            if (super.save(drugCaseInfo)) {
                // 保存毒品检材
                List<DrugMaterialInfo> drugMaterialInfos = DrugMaterialInfoConvert.dtoToEntityList(dto.getDrugMaterialInfoDTOList());
                flag = drugMaterialInfoService.saveDrugMaterialBatch(drugMaterialInfos, drugCaseInfo);
            }
        } else {
            if (this.updateById(drugCaseInfo)) {
                // 转换成毒品检材实体
                List<DrugMaterialInfo> drugMaterialInfos = DrugMaterialInfoConvert.dtoToEntityList(dto.getDrugMaterialInfoDTOList());
                // 根据id 是否存在判断调用更新还是新增
                List<DrugMaterialInfo> saveList = drugMaterialInfos.stream().filter(o -> StrUtil.isBlank(o.getId())).collect(Collectors.toList());
                List<DrugMaterialInfo> updateList = drugMaterialInfos.stream().filter(o -> StrUtil.isNotBlank(o.getId())).collect(Collectors.toList());
                // 直接更新
                if (CollUtil.isNotEmpty(updateList)) {
                    flag = drugMaterialInfoService.updateBatchById(updateList);
                }
                if (CollUtil.isNotEmpty(saveList)) {
                    flag = drugMaterialInfoService.saveDrugMaterialBatch(saveList, drugCaseInfo);
                }
            }
        }
        if (flag) {
            return drugMaterialInfoMapper.getDrugMaterialVO(Wrappers.<DrugMaterialInfo>lambdaQuery().eq(DrugMaterialInfo::getCaseId, dto.getId()));
        }
        return null;
    }

    @Override
    public IPage<DrugCaseInfoVO> getDrugCaseInfoVOPage(DrugDepotsQuery query) {
        String keywords = query.getKeywords();
        IPage<DrugCaseInfoVO> page = baseMapper.queryDrugCaseInfoVOPage(
                new Page<>(query.getCurrent(), query.getSize()),
                Wrappers.<DrugCaseInfo>lambdaQuery().and(
                                StrUtil.isNotBlank(keywords),
                                wrapper -> wrapper
                                        .like(DrugCaseInfo::getCaseNo, keywords)
                                        .or()
                                        .like(DrugCaseInfo::getCaseName, keywords))
                        .orderByDesc(DrugCaseInfo::getUpdateTime));
        List<DrugCaseInfoVO> drugCaseInfoVOS = page.getRecords();
        drugCaseInfoVOS.parallelStream().forEach(item -> item.setHandingOverOrgName(commonFeignService.remoteGetSysOrg(item.getHandingOverOrg()).getName()));
        return page;
    }

    @Override
    public DrugCaseInfo drugCaseSave(DrugDepotsDTO dto) {
        DrugCaseInfo drugCaseInfo = DrugCaseInfoConvert.dtoTOEntity(dto);
        try {
            super.save(drugCaseInfo);
        } catch (DataIntegrityViolationException e) {
            // 检查是否是唯一约束违规异常并抛出自定义异常
            Throwable cause = e.getCause();
            if (cause instanceof SQLIntegrityConstraintViolationException
                    && cause.getMessage().contains("Duplicate entry")) {
                throw new ValidateCodeException("案件编号已经存在: " + dto.getCaseNo());
            }
            throw e; // 其他异常继续向上抛出
        }
        return drugCaseInfo;
    }

}




