using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;
using System.Text.RegularExpressions;
using DirectService.Tools;
using JLHHJSvr.BLL;
using JLHHJSvr.Com;
using JLHHJSvr.Com.Model;
using JLHHJSvr.LJFramework.Tools;
using LJLib.DAL.SQL;
using LJLib.Net.SPI.Server;
using Newtonsoft.Json.Linq;

namespace JLHHJSvr.Excutor
{
    internal sealed class FormulaCheckExcutor : ExcutorBase<FormulaCheckRequest, FormulaCheckResponse>
    {
        protected override void ExcuteInternal(FormulaCheckRequest request, object state, FormulaCheckResponse rslt)
        {
            var tokendata = BllHelper.GetToken(request.token);
            if (tokendata == null)
            {
                rslt.ErrMsg = "会话已经中断，请重新登录";
                return;
            }

            if(string.IsNullOrEmpty(request.formula))
            {
                rslt.ErrMsg = "公式为空,请检查!";
                return;
            }
            
            var replacements = new Dictionary<string, decimal>();

            var formula = request.formula.Replace("（", "(")
                 .Replace("）", ")")
                 .Replace("，", ",")
                 .Replace("。", ".")
                 .Replace("：", ":")
                 .Replace("；", ";")
                 .Replace("“", "\"")
                 .Replace("”", "\"")
                 .Replace("‘", "'")
                 .Replace("’", "'");
            // 定义正则表达式模式，匹配包含【】的内容
            string pattern = @"【(.*?)】";
            Regex regex = new Regex(pattern);
            MatchCollection matches = regex.Matches(formula);
            foreach (Match match in matches)
            {
                if (!replacements.ContainsKey(match.Value))
                {
                    replacements.Add(match.Value, 999M);
                }
            }

            // 相关变量会默认代入999，主要验证运算逻辑是否合理即可。避免除数为0即可
            foreach (var item in replacements)
            {
                formula = formula.Replace(item.Key, "(" + item.Value + ")");
            }

            if (LJExprParser.CheckFormula(formula,out var arg_msg))
            {
                rslt.ErrMsg = $"解析表达式{request.formula}失败:{arg_msg}";
            }
        }
    }
}
