package thyyxxk.webserver.service.examinations;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.constants.Capacity;
import thyyxxk.webserver.dao.his.examinations.BloodSugarQueryDao;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.entity.examinations.BloodSugar.BgNursingTestSync;
import thyyxxk.webserver.entity.examinations.BloodSugar.PackagedBloodGlucoseData;
import thyyxxk.webserver.entity.inpatient.patient.Patient;
import thyyxxk.webserver.utils.DateUtil;
import thyyxxk.webserver.utils.ListUtil;
import thyyxxk.webserver.utils.ResultVoUtil;
import thyyxxk.webserver.utils.StringUtil;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
@Slf4j
public class BloodSugarQueryServer {

    private final BloodSugarQueryDao dao;

    public BloodSugarQueryServer(BloodSugarQueryDao dao) {
        this.dao = dao;
    }

    private final static List<String> NAME_LIST = Arrays.asList("空腹", "早餐后", "中餐前", "中餐后", "晚餐前", "晚餐后", "零点", "三点");


    public ResultVo<Map<String, Object>> getPatientLoodSugar(String panNo, Integer times) {
        Patient patient = dao.getPatientInfo("zy_actpatient", panNo, times);
        if (patient == null) {
            patient = dao.getPatientInfo("zy_inactpatient", panNo, times);
        }
        if (patient == null) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "没有查询到患者信息");
        }

        if (patient.getBirthDate() != null && patient.getAdmissDate() != null) {
            patient.setAge(DateUtil.calculateAge(DateUtil.parse(patient.getBirthDate()), patient.getAdmissDate()));
        }

        Map<String, Object> returnValue = new HashMap<>(Capacity.TWO);
        returnValue.put("patientInfo", patient);

        List<BgNursingTestSync> list = dao.getPatientLoodSugar(panNo, times);

        if (ListUtil.isBlank(list)) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "没有查询到该患者的血糖信息。");
        }
        AtomicInteger count = new AtomicInteger();
        Map<String, List<BgNursingTestSync>> map = new TreeMap<>();

        list.forEach(item -> {
            if (!NAME_LIST.contains(item.getTimecodeName())) {
                item.setTimecodeName("随机血糖");
            }
            if (!StringUtil.isChinese(item.getTestResult())) {
                count.incrementAndGet();
            }
            String key = DateUtil.formatDatetime(item.getTestTime(), DateUtil.DATE);

            if (map.containsKey(key)) {
                map.get(key).add(item);
            } else {
                List<BgNursingTestSync> temp = new ArrayList<>();
                temp.add(item);
                map.put(key, temp);
            }
        });

        List<PackagedBloodGlucoseData> data = new ArrayList<>();

        for (Map.Entry<String, List<BgNursingTestSync>> entrySet : map.entrySet()) {
            Map<String, Integer> a = new HashMap<>();
            // "空腹", "早餐后", "中餐前", "中餐后", "晚餐前", "晚餐后", "零点", "三点",随机血糖
            a.put("空腹", 0);
            a.put("早餐后", 0);
            a.put("中餐前", 0);
            a.put("中餐后", 0);
            a.put("晚餐前", 0);
            a.put("晚餐后", 0);
            a.put("零点", 0);
            a.put("三点", 0);
            a.put("随机血糖", 0);

            List<PackagedBloodGlucoseData> row = new ArrayList<>();

            for (BgNursingTestSync item : entrySet.getValue()) {
                Integer timecodeNameIndex = a.get(item.getTimecodeName());
                int rowSize = timecodeNameIndex + 1;
                a.replace(item.getTimecodeName(), rowSize);

                String name = item.getTimecodeName();

                if ("随机血糖".equals(item.getTimecodeName())) {

                    if (timecodeNameIndex >= 3) {
                        name = item.getTimecodeName() + ((timecodeNameIndex % 3) + 1);
                        timecodeNameIndex = timecodeNameIndex / 3;
                        rowSize = timecodeNameIndex + 1;
                    } else {
                        name += (timecodeNameIndex + 1);
                        timecodeNameIndex = 0;
                        rowSize = 1;
                    }
                }
                if (rowSize > row.size()) {
                    PackagedBloodGlucoseData temp = new PackagedBloodGlucoseData();
                    temp.setDate(entrySet.getKey());
                    temp.setData(new HashMap<>());
                    row.add(temp);
                }
                row.get(timecodeNameIndex).getData().put(name, item);
            }
            data.addAll(row);
        }

        returnValue.put("size", count);
        returnValue.put("bloodSugarData", data);

        return ResultVoUtil.success(returnValue);
    }

    public ResultVo<String> modifyPatientBloodGlucoseInfo(BgNursingTestSync param) {
        if (param.getId() == null) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "血糖id 为空");
        }
        dao.modifyPatientBloodGlucoseInfo(param);
        return ResultVoUtil.success();
    }


}
