package cc.smtweb.framework.core.mvc.variable;

import cc.smtweb.framework.core.common.SwMap;
import cc.smtweb.framework.core.exception.BizException;
import cc.smtweb.framework.core.session.UserSession;
import cc.smtweb.framework.core.util.DateUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Akmm at 2022/5/11 19:07
 * 变量工厂，变量的注册及计算
 */
public class SwVariableFactory {
    private static SwVariableFactory instance;

    static {
        instance = new SwVariableFactory();
    }

    public static SwVariableFactory getInstance() {
        return instance;
    }

    //记录变量信息
    private Map<String, SwVariable> map = new HashMap<>();

    private SwVariableFactory() {
        regVariable("SYS_DATE", "当前日期", "YYYYMMDD格式", (params, us) -> DateUtil.nowDateLong());
        regVariable("CUR_USER_ID", "当前操作员id", "当前操作员主键", (params, us) -> us.getUserId());
    }

    //注册变量
    public void regVariable(String name, String label, String remark, ICalcVar calcVar) {
        if (map.containsKey(name)) throw new BizException("变量重复定义：name=" + name);
        map.put(name, new SwVariable(name, label, remark, calcVar));
    }

    //计算变量值
    public Object calcVar(String name, SwMap params, UserSession us) {
        SwVariable var = map.get(name);
        if (var == null) throw new BizException("没有定义此变量：" + name);
        return var.getCalcVar().calcVar(params, us);
    }
}
