package com.lantone.qc.trans.beilun;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lantone.qc.pub.model.doc.transferrecord.TransferIntoDoc;
import com.lantone.qc.pub.model.doc.transferrecord.TransferOutDoc;
import com.lantone.qc.pub.model.doc.transferrecord.TransferRecordDoc;
import com.lantone.qc.pub.model.vo.MedrecVo;
import com.lantone.qc.pub.util.FastJsonUtils;
import com.lantone.qc.pub.util.ListUtil;
import com.lantone.qc.pub.util.StringUtil;
import com.lantone.qc.trans.ModelDocTrans;
import com.lantone.qc.trans.beilun.util.BeiLunHtmlAnalysis;
import com.lantone.qc.trans.beilun.util.BeiLunTransferIntoHtmlAnalysis;
import com.lantone.qc.trans.beilun.util.BeiLunTransferOutHtmlAnalysis;
import com.lantone.qc.trans.comsis.OrdinaryAssistant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;

import java.util.*;

/**
 * @Description: 转科记录文档生成
 * @author: rengb
 * @time: 2020/3/20 16:10
 */
@Slf4j
public class BeiLunTransferRecordDocTrans extends ModelDocTrans {

    @Override
    public TransferRecordDoc extract(MedrecVo medrecVo) {
        TransferRecordDoc transferRecordDoc = new TransferRecordDoc();

        Map<String, List<String>> contentMap = (Map) medrecVo.getContent().get("content");
        if (contentMap == null) {
            return transferRecordDoc;
        }
        List<Map<String, Object>> into = (List) contentMap.get("转入记录");
        List<Map<String, Object>> out = (List) contentMap.get("转出记录");
        List<Map<String, Object>> all = new ArrayList<>();

        Map<String, TransferIntoDoc> transferIntoDocMap = new HashMap<>();
        Map<String, TransferOutDoc> transferOutDocMap = new HashMap<>();
        if (into != null) {
            all.addAll(into);
            transferIntoDocMap = getTransferIntoDocMap(into);
        }
        if (out != null) {
            all.addAll(out);
            transferOutDocMap = getTransferOutDocMap(out);
        }
        Map<String, TransferRecordDoc> transferAllDocMap = getTransferAllDocMap(all);

        //转入
        Map<Date, TransferIntoDoc> dateRecordIn = new TreeMap<>(new Comparator<Date>() {
            @Override
            public int compare(Date o1, Date o2) {
                // 升序排列
                return o1.compareTo(o2);
            }
        });
        for (TransferIntoDoc transferIntoDoc : transferIntoDocMap.values()) {
            Map<String, String> structureMap = transferIntoDoc.getStructureMap();
            String inDateStr = structureMap.get("转科日期");
            if (StringUtil.isBlank(inDateStr)) {
                inDateStr = structureMap.get("病历日期");
            }
            Date inDate = StringUtil.parseDateTime(inDateStr);
            if (inDate == null) {
                continue;
            }
            dateRecordIn.put(inDate, transferIntoDoc);
        }
        transferRecordDoc.setTransferIntoDocs(new ArrayList<>(dateRecordIn.values()));
        //转出
        Map<Date, TransferOutDoc> dateRecordOut = new TreeMap<>(new Comparator<Date>() {
            @Override
            public int compare(Date o1, Date o2) {
                // 升序排列
                return o1.compareTo(o2);
            }
        });
        for (TransferOutDoc transferOutDoc : transferOutDocMap.values()) {
            Map<String, String> structureMap = transferOutDoc.getStructureMap();
            String outDateStr = structureMap.get("转科日期");
            if (StringUtil.isBlank(outDateStr)) {
                outDateStr = structureMap.get("病历日期");
            }
            Date outDate = StringUtil.parseDateTime(outDateStr);
            if (outDate == null) {
                continue;
            }
            dateRecordOut.put(outDate, transferOutDoc);
        }
        transferRecordDoc.setTransferOutDocs(new ArrayList<>(dateRecordOut.values()));

        //全部转科记录
        Map<Date, TransferRecordDoc> dateRecordAll = new TreeMap<>(new Comparator<Date>() {
            @Override
            public int compare(Date o1, Date o2) {
                // 升序排列
                return o1.compareTo(o2);
            }
        });
        for (TransferRecordDoc transferRecordAllDoc : transferAllDocMap.values()) {
            Map<String, String> structureMap = transferRecordAllDoc.getStructureMap();
            String transferDateStr = structureMap.get("转科日期");
            if (StringUtil.isBlank(transferDateStr)) {
                transferDateStr = structureMap.get("病历日期");
            }
            Date transferDate = StringUtil.parseDateTime(transferDateStr);
            if (transferDate == null) {
                continue;
            }
            dateRecordAll.put(transferDate, transferRecordAllDoc);
        }
        transferRecordDoc.setAllTransferDocs(new ArrayList<>(dateRecordAll.values()));

        return transferRecordDoc;
    }


    /**************************************************转入*******************************************************/
    private Map<String, TransferIntoDoc> getTransferIntoDocMap(List<Map<String, Object>> contentMaps) {
        Map<String, TransferIntoDoc> retMap = Maps.newHashMap();
        if (ListUtil.isEmpty(contentMaps)) {
            return retMap;
        }
        int index = 1;
        String transferRecordName = null;
        for (Map<String, Object> contentMap : contentMaps) {
            if (contentMap.get("xmlText") == null || StringUtil.isBlank(contentMap.get("xmlText").toString())) {
                continue;
            }
            try {
                TransferIntoDoc transferIntoDoc = getTransferIntoDoc(contentMap);
                if (transferIntoDoc != null) {
                    transferRecordName = index + "";
                    transferIntoDoc.setTransferRecordName(transferRecordName);
                    retMap.put(transferRecordName, transferIntoDoc);
                    index++;
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
        return retMap;
    }

    private TransferIntoDoc getTransferIntoDoc(Map<String, Object> contentMap) {
        String content = contentMap.get("xmlText").toString();
        Map<String, String> structureMap = new HashMap<>();
        if (contentMap.get("isParsed") != null && "1".equals(contentMap.get("isParsed").toString())) {
            structureMap = (Map) FastJsonUtils.getJsonToMap(content);
        } else {
            String recTitle = contentMap.get("recTitle").toString();
            String recTypeId = contentMap.get("recTypeId").toString();
            BeiLunHtmlAnalysis beiLunHtmlAnalysis = new BeiLunTransferIntoHtmlAnalysis();
            Map<String, String> sourceMap = beiLunHtmlAnalysis.analysis(content, recTitle, recTypeId);
            if (MapUtils.isNotEmpty(sourceMap)) {
                structureMap = OrdinaryAssistant.mapKeyContrast(sourceMap, keyContrasts);
                structureMap.put("记录编号", contentMap.get("recId").toString());
                structureMap.put("病历号", contentMap.get("behospitalCode") == null ? null : contentMap.get("behospitalCode").toString());
            }
        }
        //存入转入时间
        getTransDate(contentMap.get("transferInDate"), "转入时间", structureMap);
        if (MapUtils.isNotEmpty(structureMap)) {
            TransferIntoDoc transferIntoDoc = new TransferIntoDoc();
            transferIntoDoc.setStructureMap(structureMap);
            transferIntoDoc.setPageData((Map) structureMap);
            return transferIntoDoc;
        } else {
            return null;
        }
    }

    /**************************************************全部*******************************************************/
    private Map<String, TransferRecordDoc> getTransferAllDocMap(List<Map<String, Object>> contentMaps) {
        Map<String, TransferRecordDoc> retMap = Maps.newHashMap();
        if (ListUtil.isEmpty(contentMaps)) {
            return retMap;
        }
        int index = 1;
        String transferRecordName = null;
        for (Map<String, Object> contentMap : contentMaps) {
            if (contentMap.get("xmlText") == null || StringUtil.isBlank(contentMap.get("xmlText").toString())) {
                continue;
            }
            try {
                TransferRecordDoc transferRecordDoc = getTransferAllDoc(contentMap);
                if (transferRecordDoc != null) {
                    transferRecordName = index + "";
                    transferRecordDoc.setTransferRecordName(transferRecordName);
                    retMap.put(transferRecordName, transferRecordDoc);
                    index++;
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
        return retMap;
    }

    private TransferRecordDoc getTransferAllDoc(Map<String, Object> contentMap) {
        String content = contentMap.get("xmlText").toString();
        Map<String, String> structureMap = new HashMap<>();
        if (contentMap.get("isParsed") != null && "1".equals(contentMap.get("isParsed").toString())) {
            structureMap = (Map) FastJsonUtils.getJsonToMap(content);
        } else {
            String recTitle = contentMap.get("recTitle").toString();
            String recTypeId = contentMap.get("recTypeId").toString();
            BeiLunHtmlAnalysis beiLunHtmlAnalysis = new BeiLunTransferOutHtmlAnalysis();
            Map<String, String> sourceMap = beiLunHtmlAnalysis.analysis(content, recTitle, recTypeId);
            if (MapUtils.isNotEmpty(sourceMap)) {
                structureMap = OrdinaryAssistant.mapKeyContrast(sourceMap, keyContrasts);
                structureMap.put("记录编号", contentMap.get("recId").toString());
                structureMap.put("病历号", contentMap.get("behospitalCode") == null ? null : contentMap.get("behospitalCode").toString());
            }
        }
        //存入转入时间
        getTransDate(contentMap.get("transferInDate"), "转入时间", structureMap);
        //存入转出时间
        getTransDate(contentMap.get("transferOutDate"), "转出时间", structureMap);
        if (MapUtils.isNotEmpty(structureMap)) {
            TransferRecordDoc transferAllDoc = new TransferRecordDoc();
            transferAllDoc.setStructureMap(structureMap);
            transferAllDoc.setPageData((Map) structureMap);
            return transferAllDoc;
        } else {
            return null;
        }
    }


    /**************************************************转出*******************************************************/
    private Map<String, TransferOutDoc> getTransferOutDocMap(List<Map<String, Object>> contentMaps) {
        Map<String, TransferOutDoc> retMap = Maps.newHashMap();
        if (ListUtil.isEmpty(contentMaps)) {
            return retMap;
        }
        int index = 1;
        String transferRecordName = null;
        for (Map<String, Object> contentMap : contentMaps) {
            if (contentMap.get("xmlText") == null || StringUtil.isBlank(contentMap.get("xmlText").toString())) {
                continue;
            }
            try {
                TransferOutDoc transferOutDoc = getTransferOutDoc(contentMap);
                if (transferOutDoc != null) {
                    transferRecordName = index + "";
                    transferOutDoc.setTransferRecordName(transferRecordName);
                    retMap.put(transferRecordName, transferOutDoc);
                    index++;
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
        return retMap;
    }

    private TransferOutDoc getTransferOutDoc(Map<String, Object> contentMap) {
        String content = contentMap.get("xmlText").toString();
        Map<String, String> structureMap = new HashMap<>();
        if (contentMap.get("isParsed") != null && "1".equals(contentMap.get("isParsed").toString())) {
            structureMap = (Map) FastJsonUtils.getJsonToMap(content);
        } else {
            String recTitle = contentMap.get("recTitle").toString();
            String recTypeId = contentMap.get("recTypeId").toString();
            BeiLunHtmlAnalysis beiLunHtmlAnalysis = new BeiLunTransferOutHtmlAnalysis();
            Map<String, String> sourceMap = beiLunHtmlAnalysis.analysis(content, recTitle, recTypeId);
            if (MapUtils.isNotEmpty(sourceMap)) {
                structureMap = OrdinaryAssistant.mapKeyContrast(sourceMap, keyContrasts);
                structureMap.put("记录编号", contentMap.get("recId").toString());
                structureMap.put("病历号", contentMap.get("behospitalCode") == null ? null : contentMap.get("behospitalCode").toString());
            }
        }
        //存入转出时间
        getTransDate(contentMap.get("transferOutDate"), "转出时间", structureMap);
        if (MapUtils.isNotEmpty(structureMap)) {
            TransferOutDoc transferOutDoc = new TransferOutDoc();
            transferOutDoc.setStructureMap(structureMap);
            transferOutDoc.setPageData((Map) structureMap);
            return transferOutDoc;
        } else {
            return null;
        }
    }

    //存入转入转出时间
    private void getTransDate(Object transferDates, String dateStr, Map<String, String> structureMap) {
        if (transferDates != null) {
            structureMap.put(dateStr, transferDates.toString());
        }
    }

    private List<String> keyContrasts = Lists.newArrayList(
            "医师签名=记录医生",
            "病历标题=标题",
            "病情记录=病历内容",
            "签名时间=记录时间"
    );

}