package com.ywt.outpatient.service.rpc.common;

import com.fasterxml.jackson.databind.JsonNode;
import com.ywt.biz.common.util.Checker;
import com.ywt.biz.common.util.StringHelper;
import com.ywt.biz.common.util.serializers.JsonSerializer;
import com.ywt.outpatient.domain.entity.center.Config;
import com.ywt.outpatient.domain.entity.center.ConfigRepository;
import com.ywt.outpatient.domain.models.HisMedCardConfig;
import com.ywt.outpatient.domain.models.MriBookConfig;
import com.ywt.outpatient.domain.models.OutpatientConfig;
import com.ywt.outpatient.domain.models.enums.ConfigTypeEnum;
import com.ywt.outpatient.service.rpc.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author Walker
 * Created on 2020/6/10
 */
@Service
public class ConfigProvider {
    private final Logger logger = LoggerFactory.getLogger(ConfigProvider.class);
    @Autowired
    private ConfigRepository configRepository;

    final static String FMT_HOSPITAL_ID = "hospitalId";
    final static String FMT_TYPE_LIST = "typeList";

    public List<String> getFmtFlagList(int hospitalId) {
        List<String> list = new LinkedList<>();
        Config config = configRepository.findOneByType(ConfigTypeEnum.FMT.getValue());
        if (config == null || StringHelper.isNullOrEmpty(config.getContent())) {
            return list;
        }
        String content = config.getContent();
        try {
            if (hospitalId == 0) {
                hospitalId = Constants.TAIHE_HOSPITAL_ID;
            }
            /**
             * content 举例：
             [{"hospitalId":12,"typeList":["白云区公医","公医","天河区公医"]},{"hospitalId":41,"typeList":["白云区公医41","公医41","天河区公医41"]}]
             *
             */
            JsonNode node = JsonSerializer.readToNode(content);
            if (node != null && node.isArray()) {
                for (JsonNode jsonNode : node) {
                    String obj = jsonNode.toString();
                    Map<String, Object> map = JsonSerializer.from(obj, Map.class);
                    if (map == null) {
                        return new LinkedList<>();
                    }
                    int hospitalIdValue = (int) map.getOrDefault(FMT_HOSPITAL_ID, 0);
                    if (hospitalIdValue == hospitalId) {
                        List<String> typeList = (List<String>) map.getOrDefault(FMT_TYPE_LIST, null);
                        if (typeList == null) {
                            return new LinkedList<>();
                        }
                        typeList.stream().forEach(p -> {
                            list.add(p);
                        });
                    }
                }
            }
        } catch (Exception e) {
            logger.error("ConfigServiceProvider#getVoiceSmsPhone(content={}):Deserialize failed!\n{}", content, e.getMessage(), e);
        }
        return list;
    }

    public MriBookConfig getMriBookConfig() {
        Config config = configRepository.findOneByType(ConfigTypeEnum.MRI_BOOK.getValue());

        if (config == null || StringHelper.isNullOrEmpty(config.getContent())) {
            return null;
        }
        return JsonSerializer.from(config.getContent(), MriBookConfig.class);
    }

    public int getMriMaxBookDay() {
        MriBookConfig mriBookConfig = getMriBookConfig();
        return mriBookConfig == null ? 7 : mriBookConfig.getMaxBookDay();
    }

    public int getMriMaxBookNum() {
        MriBookConfig mriBookConfig = getMriBookConfig();
        return mriBookConfig == null ? 5 : mriBookConfig.getMaxBookNum();
    }

    public int getMriBlackListLimitation() {
        MriBookConfig mriBookConfig = getMriBookConfig();
        return mriBookConfig == null ? 3 : mriBookConfig.getBlackListLimitation();
    }

    public OutpatientConfig getOutpatientConfig(int hospitalId) {
        Config config = configRepository.findOneByType(ConfigTypeEnum.OUTPATIENT.getValue());
        if (config == null || StringHelper.isNullOrEmpty(config.getContent())) {
            return null;
        }
        String content = config.getContent();
        try {
            JsonNode node = JsonSerializer.readToNode(content);
            if (node != null && node.isArray()) {
                for (JsonNode jsonNode : node) {
                    OutpatientConfig c = JsonSerializer.from(jsonNode.toString(), OutpatientConfig.class);
                    if (c != null && Checker.getIntegerValue(c.getHospitalId()) == hospitalId) {
                        return c;
                    }
                }
            }
        } catch (Exception e) {
            logger.error("ConfigProvider#getOutpatientConfig(content={}):Deserialize failed!\n{}", content, e.getMessage(), e);
        }
        return null;
    }

    public HisMedCardConfig getHisMedCardConfig(int hospitalId) {
        Config config = configRepository.findOneByType(ConfigTypeEnum.HIS_CREAT_MEDCARD.getValue());
        if (config == null || StringHelper.isNullOrEmpty(config.getContent())) {
            return null;
        }
        String content = config.getContent();
        try {
            JsonNode node = JsonSerializer.readToNode(content);
            if (node != null && node.isArray()) {
                for (JsonNode jsonNode : node) {
                    HisMedCardConfig c = JsonSerializer.from(jsonNode.toString(), HisMedCardConfig.class);
                    if (c != null && Checker.getIntegerValue(c.getHospitalId()) == hospitalId) {
                        return c;
                    }
                }
            }
        } catch (Exception e) {
            logger.error("ConfigServiceProvider#getHisMedCardConfig(content={}):Deserialize failed!\n{}", content, e.getMessage(), e);
        }
        return null;
    }

    public List<String> getHisRegisteredFeeFlagList(int hospitalId) {
        List<String> list = new LinkedList<>();
        Config config = configRepository.findOneByType(ConfigTypeEnum.HIS_REGISTERED_FEE.getValue());
        if (config == null || StringHelper.isNullOrEmpty(config.getContent())) {
            return list;
        }
        String content = config.getContent();
        try {
            if (hospitalId == 0) {
                hospitalId = Constants.NFYYBYFY_HOSPITAL_ID;
            }
            /**
             * content 举例：
             [{"hospitalId":12,"typeList":["白云区公医","公医","天河区公医"]},{"hospitalId":41,"typeList":["白云区公医41","公医41","天河区公医41"]}]
             *
             */
            JsonNode node = JsonSerializer.readToNode(content);
            if (node != null && node.isArray()) {
                for (JsonNode jsonNode : node) {
                    String obj = jsonNode.toString();
                    Map<String, Object> map = JsonSerializer.from(obj, Map.class);
                    if (map == null) {
                        return new LinkedList<>();
                    }
                    int hospitalIdValue = (int) map.getOrDefault(FMT_HOSPITAL_ID, 0);
                    if (hospitalIdValue == hospitalId) {
                        List<String> typeList = (List<String>) map.getOrDefault(FMT_TYPE_LIST, null);
                        if (typeList == null) {
                            return new LinkedList<>();
                        }
                        typeList.stream().forEach(p -> {
                            list.add(p);
                        });
                    }
                }
            }
        } catch (Exception e) {
            logger.error("ConfigServiceProvider#getHisRegisteredFeeFlagList(content={}):Deserialize failed!\n{}", content, e.getMessage(), e);
        }
        return list;
    }
}
