using JLHHJSvr.LJException;
using JLHHJSvr.LJFramework.Tools;
using LJLib.InstallHelper;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace JLHHJSvr.BLL
{
    internal abstract class HelperBase
    {
        /// <summary>
        /// 数据库连接
        /// </summary>
        public SqlCommand cmd { get; set; }
        /// <summary>
        /// 预留的上下文
        /// </summary>
        public Context context { get; set; }

        public static T GetHelper<T>(SqlCommand cmd, Context context = null) where T : HelperBase, new()
        {
            var rslt = new T();
            rslt.cmd = cmd;
            rslt.context = context ?? new Context();
            return rslt;
        }

        public JObject DoExecute(string apiName, JObject request)
        {
            var url = GlobalVar.ERP_API_URL + "/api/common/" + apiName;
            if (!url.StartsWith("http", StringComparison.OrdinalIgnoreCase))
            {
                url = "https://" + url;
            }
            var rslt = LJHttpUtil.PostRequest(url, request);

            var errMsg = rslt.GetValue("ErrMsg");
            if (errMsg != null && !string.IsNullOrEmpty(errMsg.ToString()))
            {
                throw new LJCommonException(errMsg.ToString());
            }
            return rslt;
        }

        public sealed class Context
        {
            private DateTime _opdate = DateTime.Now;

            public DateTime opdate
            {
                get { return _opdate; }
                set { _opdate = value; }
            }
            /// <summary>
            /// 用户登陆信息
            /// </summary>
            public TokenData tokendata { get; set; }
        }
    }
}
