package com.docus.server.gdszy.service.impl;

import com.docus.core.util.Func;
import com.docus.server.archive.entity.BasicExtend;
import com.docus.server.archive.entity.TBasic;
import com.docus.server.archive.mapper.TBasicMapper;
import com.docus.server.gdszy.service.GdSzyFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author YongBin Wen
 * @date 2024/9/26 9:22
 */
@Service
@Slf4j
public class GdSzyFileServiceImpl implements GdSzyFileService {
    @Autowired
    private TBasicMapper tBasicMapper;

    @Override
    public void yzyReportMerge(List<String> patientIds) {
        List<TBasic> yzyBasic = tBasicMapper.getTbasicByPatientIds(patientIds);
        if (Func.isEmpty(yzyBasic)) {
            return;
        }
        // 预住院患者信息的 jzh 关联额外表 preJzh，查出对应住院的 patientId,根据预住院和住院的patientId进行文件合并（文件表预住院的 patientId修改为住院 patientId）
        List<String> yzyJzh = yzyBasic.stream().map(TBasic::getJzh).collect(Collectors.toList());
        List<BasicExtend> zyBasicExtend = tBasicMapper.getZyPatientIdsByYzyJzh(yzyJzh);
        if (Func.isEmpty(zyBasicExtend)) {
            return;
        }
        Map<String, String> yzyBasicJzhPatientIdMap = yzyBasic.stream().collect(Collectors.toMap(TBasic::getJzh, TBasic::getPatientId));
        for (BasicExtend zyExtend : zyBasicExtend) {
            String preJzh = zyExtend.getPreJzh();
            String yzhPatientId = yzyBasicJzhPatientIdMap.get(preJzh);
            String zyPatientId = zyExtend.getPatientId();
            int number = tBasicMapper.mergeYzyFile(yzhPatientId, zyPatientId);
            log.info("预住院文件patientId：{} 合并到住院patientId: {} ,影响文件数量：{} 个", yzhPatientId, zyPatientId, number);
        }
    }
}
