package com.siwei.rsmonitoring.cache;

import com.siwei.rsmonitoring.domain.TDkAuditflowStep;

import java.util.*;

/**
 * 核查流程缓存信息
 * <br>
 * map记录核查流程类型，及流程步骤
 */
public class AuditFlowCacheUtil {
    private static volatile AuditFlowCacheUtil auditFlowCacheUtil;
    private static Map<String, List<TDkAuditflowStep>> cacheAuditFlowTypeMap;

    private AuditFlowCacheUtil() {
        cacheAuditFlowTypeMap = new HashMap<String, List<TDkAuditflowStep>>();
    }

    /*
     * 单例模式有两种类型
     * 懒汉式：在真正需要使用对象时才去创建该单例类对象
     * 饿汉式：在类加载时已经创建好该单例对象，等待被程序使用
     */

    // 懒汉式单例模式
    public static AuditFlowCacheUtil getInstance() {
        if (auditFlowCacheUtil == null) {// 线程A和线程B同时看到cacheSingletonUtil = null，如果不为null，则直接返回cacheSingletonUtil
            synchronized (AuditFlowCacheUtil.class) {// 线程A或线程B获得该锁进行初始化
                if (auditFlowCacheUtil == null) {// 其中一个线程进入该分支，另外一个线程则不会进入该分支
                    auditFlowCacheUtil = new AuditFlowCacheUtil();
                }
            }
        }
        return auditFlowCacheUtil;
    }

    /**
     * 添加到内存
     */
    public void addCodeCacheData(String key, List<TDkAuditflowStep> obj) {
        cacheAuditFlowTypeMap.put(key, obj);
    }

    /**
     * 从内存中取出
     */
    public List<TDkAuditflowStep> getCodeCacheData(String key) {
        return cacheAuditFlowTypeMap.get(key);
    }

    /**
     * 从内存中取出当前流程的操作标识
     */
    public TDkAuditflowStep getAuditFlowTypePresentStep(String auditFlowType, String auditFlowStep) {
        List<TDkAuditflowStep> objList = cacheAuditFlowTypeMap.get(auditFlowType);
        if (objList == null || objList.isEmpty()) {
            return null;
        }
        for (TDkAuditflowStep stepObj : objList) {
            if (stepObj.getStepCode().equals(auditFlowStep)) {
                return stepObj;
            }
        }
        return null;
    }

    /**
     * 从内存中取出当前流程的下一步操作标识
     */
    public TDkAuditflowStep getAuditFlowTypeNestStep(String auditFlowType, String auditFlowStep) {
        List<TDkAuditflowStep> objList = cacheAuditFlowTypeMap.get(auditFlowType);
        if (objList == null || objList.isEmpty()) {
            return null;
        }
        boolean checkList = false;
        for (TDkAuditflowStep stepObj : objList) {
            if (checkList) {
                return stepObj;
            }
            if (stepObj.getStepCode().equals(auditFlowStep)) {
                checkList = true;
            }
        }
        //暂定，如果查询到核查流程，且检查步骤结果为true,且没有终止。默认为程序流程为终止
        if (checkList) {
            TDkAuditflowStep step = new TDkAuditflowStep();
            step.setAuditflowCode(auditFlowType);
            step.setStepCode("-9999");
            step.setStepValue("流程完成");
            return step;
        }
        return null;
    }

    /**
     * 从内存中清除
     */
    public void removeCodeCacheData(String key) {
        cacheAuditFlowTypeMap.remove(key);
    }

}
