package com.lantone.qc.dbanaly.facade.comsis;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.lantone.qc.dbanaly.lt.entity.ModuleInfo;
import com.lantone.qc.dbanaly.lt.entity.ModuleMapping;
import com.lantone.qc.dbanaly.lt.entity.RecordAnalyzeDetail;
import com.lantone.qc.dbanaly.lt.service.impl.ModuleInfoServiceImpl;
import com.lantone.qc.dbanaly.lt.service.impl.ModuleMappingServiceImpl;
import com.lantone.qc.dbanaly.lt.service.impl.RecordAnalyzeDetailServiceImpl;
import com.lantone.qc.dbanaly.lt.service.impl.RecordAnalyzeServiceImpl;
import com.lantone.qc.dbanaly.util.ModuleMappingUtil;
import com.lantone.qc.pub.util.ListUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

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

/**
 * @Description:
 * @author: rengb
 * @time: 2020/5/29 17:10
 */
@Slf4j
@Component
public class ModuleHelper {
    @Autowired
    @Qualifier("moduleInfoServiceImpl")
    private ModuleInfoServiceImpl moduleInfoService;
    @Autowired
    @Qualifier("moduleMappingServiceImpl")
    private ModuleMappingServiceImpl moduleMappingService;
    @Autowired
    @Qualifier("recordAnalyzeServiceImpl")
    private RecordAnalyzeServiceImpl recordAnalyzeService;
    @Autowired
    @Qualifier("recordAnalyzeDetailServiceImpl")
    private RecordAnalyzeDetailServiceImpl recordAnalyzeDetailService;
    @Value("${qc.hospital_id}")
    private String hospitalIds;

    /**
     * 加载医院模板映射信息
     */
    public boolean loadModuleInfo() {
        try {
            List<String> xmlDataTypeHospitalIds = Lists.newArrayList("1", "2", "3");
            for (String hospitalId : hospitalIds.split(",")) {
                if (!xmlDataTypeHospitalIds.contains(hospitalId)) {
                    continue;
                }
                loadModuleInfoByHospitalId(hospitalId);
            }
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            ModuleMappingUtil.xmlDataTypeModuleInfo.clear();
            return false;
        }
    }

    private void loadModuleInfoByHospitalId(String hospitalId) {
        Map<Set<String>, String> result = Maps.newHashMap();
        QueryWrapper<ModuleInfo> moduleInfoQe = new QueryWrapper<>();
        moduleInfoQe.eq("is_deleted", "N");
        moduleInfoQe.eq("hospital_id", Long.parseLong(hospitalId));
        moduleInfoQe.select("id", "mode_id");
        List<ModuleInfo> moduleInfoList = moduleInfoService.list(moduleInfoQe);
        if (ListUtil.isEmpty(moduleInfoList)) {
            return;
        }
        List<Long> moduleInfoIds = moduleInfoList.stream().filter(i -> i.getModeId().intValue() == 6).map(i -> i.getId()).collect(Collectors.toList());
        if (moduleInfoIds.size() == 1) {
            result.put(Sets.newHashSet("mode_id=6"), moduleInfoIds.get(0) + "");
        }
        moduleInfoIds = moduleInfoList.stream().filter(i -> i.getModeId().intValue() != 6).map(i -> i.getId()).collect(Collectors.toList());
        if (ListUtil.isEmpty(moduleInfoIds)) {
            return;
        }

        QueryWrapper<ModuleMapping> moduleMappingQe = new QueryWrapper<>();
        moduleMappingQe.eq("is_deleted", "N");
        moduleMappingQe.eq("hospital_id", Long.parseLong(hospitalId));
        moduleMappingQe.in("module_id", moduleInfoIds);
        moduleMappingQe.select("module_id", "record_id");
        List<ModuleMapping> moduleMappingList = moduleMappingService.list(moduleMappingQe);
        if (ListUtil.isEmpty(moduleMappingList)) {
            return;
        }

        Map<Long, String> recordIdModuleIdMap = moduleMappingList.stream().collect(Collectors.toMap(i -> i.getRecordId(), i -> i.getModuleId().toString()));
        List<Long> recordIds = moduleMappingList.stream().map(i -> i.getRecordId()).collect(Collectors.toList());
        recordIds = recordAnalyzeService.listByIds(recordIds).stream().filter(i -> i.getIsDeleted().equals("N")).map(i -> i.getId()).collect(Collectors.toList());
        if (ListUtil.isEmpty(recordIds)) {
            return;
        }

        QueryWrapper<RecordAnalyzeDetail> recordAnalyzeDetailQe = new QueryWrapper<>();
        recordAnalyzeDetailQe.in("record_analyze_id", recordIds);
        Map<Long, Set<String>> recordIdMapKeysMap = recordAnalyzeDetailService.list(recordAnalyzeDetailQe).stream().collect(Collectors.groupingBy(i -> i.getRecordAnalyzeId(), Collectors.mapping(i -> i.getMapKey(), Collectors.toSet())));

        recordIdMapKeysMap.keySet().forEach(key -> {
            result.put(recordIdMapKeysMap.get(key), recordIdModuleIdMap.get(key));
        });
        ModuleMappingUtil.xmlDataTypeModuleInfo.put(hospitalId, result);
    }

}