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.DrugHandingOverApply;
import digital.laboratory.platform.imr.entity.DrugMaterialInfo;
import digital.laboratory.platform.imr.enums.DrugHandingOverApplyStatus;
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.DrugHandingOverApplyService;
import digital.laboratory.platform.imr.service.DrugMaterialInfoService;
import digital.laboratory.platform.imr.vo.DrugCaseInfoVO;
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;

/**
* @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 DrugHandingOverApplyService drugHandingOverApplyService;

    /**
     * 保存案件实体信息和毒品检材信息
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(DrugDepotsDTO dto) {
        DrugHandingOverApply drugHandingOverApply = drugHandingOverApplyService.getById(dto.getApplyId());
        if (!drugHandingOverApply.getStatus().equals(DrugHandingOverApplyStatus.WAIT_HANDING_OVER.getStatus())) {
            throw new ValidateCodeException("申请已经提交！不能在添加毒品信息！");
        }
        List<DrugMaterialInfoDTO> drugMaterialInfoDTOList = dto.getDrugMaterialInfoDTOList();
        boolean flag = true;
        for (DrugMaterialInfoDTO drugMaterialInfoDTO : drugMaterialInfoDTOList) {
            String caseNo = drugMaterialInfoDTO.getCaseNo();
            String caseName = drugMaterialInfoDTO.getCaseName();
            DrugCaseInfo one = super.getOne(Wrappers.<DrugCaseInfo>lambdaQuery().eq(DrugCaseInfo::getCaseNo, caseNo).or().eq(DrugCaseInfo::getCaseName, caseName));
            if (one != null && (!one.getCaseName().equals(caseName) || !one.getCaseNo().equals(caseNo))) {
                throw new ValidateCodeException(
                        String.format("新录入的案件名称 [%s] 案件编号 [%s] 和系统中已存在的案件名称 [%s] 案件编号 [%s] 发生冲突！",
                                caseName, caseNo, one.getCaseName(), one.getCaseNo())
                );
            } else if (one == null) {
                // 都为空则新录入案件信息
                one = DrugCaseInfoConvert.dtoTOEntity(drugMaterialInfoDTO);
                one.setApplyId(dto.getApplyId());
                super.save(one);
            }
            DrugMaterialInfo drugMaterialInfo = DrugMaterialInfoConvert.dtoToEntity(drugMaterialInfoDTO);
            if (StrUtil.isBlank(drugMaterialInfo.getId())) {
                flag = drugMaterialInfoService.saveDrugMaterialBatch(CollUtil.newArrayList(drugMaterialInfo), one);
            } else {
                flag = drugMaterialInfoService.updateById(drugMaterialInfo);
            }
        }

        return flag;
    }

    @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;
    }

}




