package cc.smtweb.framework.core.util;

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

public class ExportUtil {
    //填充变量
    public static String myReplaceStr(String s, Map<String, String> map) {
        boolean isDouble = s.startsWith("[@exprd");
        boolean isInt = s.startsWith("[@expri@]");
        if (isDouble || isInt) {
            s = s.substring(s.indexOf("@]") + 2);
            String b = "[#", e = "#]", svar;
            int n = s.indexOf(b), lb = b.length();
            Map<String, Object> mapvar = new HashMap<>();
            int i = 0;
            while (n >= 0) {
                svar = "a" + (++i);
                String fn = s.substring(n + lb, s.indexOf(e));
                s = s.replace(b + fn + e, svar);
                n = s.indexOf(b);
                mapvar.put(svar, StringUtil.getDoubleIgnoreErr(map.get(fn)));
            }
            double d;
            try {
                d = MathUtil.calcExprMapDouble(s, mapvar);
            } catch (Exception e1) {
                d = 0.0;
//                UtilLogger.error("计算错误：", e1);
            }
            if (isDouble) {
                String v = MathUtil.getAmountStr(d);
                v = v.replace(".00", "").replaceAll(",", "");
                if (v.contains(".") && v.endsWith("0")) v = v.substring(0, v.length() - 1);
                return v;
            }
            return MathUtil.toStdNumberString(d, 0);
        } else if (s.startsWith("[@d") || s.startsWith("[@i@]")) s = s.substring(s.indexOf("@]") + 2);
        else if (s.startsWith("[@expfml@]")) s = s.substring(10);

        return myReplaceStrEx(s, "[#", "#]", map);
    }

    //填充变量
    public static String myReplaceStrEx(String s, String b, String e, Map<String, String> map) {
        int n = s.indexOf(b), lb = b.length();
        while (n >= 0) {
            String fn = s.substring(n + lb, s.indexOf(e));
            s = s.replace(b + fn + e, StringUtil.checkNull(map.get(fn)));
            n = s.indexOf(b);
        }
        return s;
    }
}
