package com.lantone.qc.kernel.catalogue.firstpagerecord;

import com.lantone.qc.kernel.catalogue.QCCatalogue;
import com.lantone.qc.kernel.util.CatalogueUtil;
import com.lantone.qc.pub.Content;
import com.lantone.qc.pub.model.InputInfo;
import com.lantone.qc.pub.model.OutputInfo;
import com.lantone.qc.pub.model.doc.RescueDoc;
import com.lantone.qc.pub.util.StringUtil;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ClassName : FIRP0250
 * @Description : 抢救成功次数填写错误
 * @Author : 楼辉荣
 * @Date: 2020-03-06 17:28ss
 */
@Component
public class FIRP0250 extends QCCatalogue {
    public void start(InputInfo inputInfo, OutputInfo outputInfo) {
        status.set("0");
        if (inputInfo.getFirstPageRecordDoc() != null && inputInfo.getRescueDocs().size() > 0) {
            List<RescueDoc> rescueDocs = inputInfo.getRescueDocs();
            int rescueNum = getRescueNum(rescueDocs);/* 抢救记录中抢救成功次数 */
            boolean match = false;

            Map<String, String> firstpageStructureMap = inputInfo.getFirstPageRecordDoc().getStructureMap();
            String successfulRescueTimes = firstpageStructureMap.get("病人抢救成功次数");
            int successfulRescueTimesTZ = 0;
            if (StringUtil.isNotBlank(successfulRescueTimes) && CatalogueUtil.numbersOnly(successfulRescueTimes)) {
                successfulRescueTimesTZ = Integer.parseInt(successfulRescueTimes);
            }
            if (rescueNum == successfulRescueTimesTZ) {
                match = true;
            }
            String name = firstpageStructureMap.get(Content.rescue_condition);
            if (StringUtil.isNotBlank(name)) {
                String[] split = name.split("\\s+");
                Pattern compile = Pattern.compile("(?<=成功).*(?=次)");
                Matcher matcher = compile.matcher(split[0]);
                while (matcher.find()) {
                    try {
                        String number = matcher.group(0);
                        int num = Integer.parseInt(number);
                        if (num == rescueNum) {
                            match = true;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            if (!match){
                status.set("-1");
            }
        }
    }

    private int getRescueNum(List<RescueDoc> rescueDocs) {
        int i = 0;
        for (RescueDoc re : rescueDocs) {
            Map<String, String> structureMap = re.getStructureMap();
            // 跟医学部确认，从抢救措施中读取数据
            String qjgc = structureMap.get("抢救措施");
            if (StringUtil.isNotBlank(qjgc) && !qjgc.contains("死亡")) {
                i++;
            }
        }
        return i;
    }
}