using FactorySystemModel.ResponseModel;
using FactorySystemModel.SqlSugarModel;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net.Http;
using System.Threading;

namespace FactorySystemCommon
{
    /// <summary>
    /// 异常处理
    /// </summary>
    public static class ExceptionHelper
    {
        /// <summary>
        /// 返回错误原因TryCatch统一处理
        /// </summary>
        public static ApiResult TryReturnException(Action action, ApiResult response, HttpRequestMessage request, object inParam = null,
            [System.Runtime.CompilerServices.CallerMemberName] string memberName = "",
            [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = "",
            [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0)
        {
            try
            {
                action();
            }
            catch (Exception ex)
            {
                response = new ApiResult().Error(ex);
                //保存日志
                WriteMessage(ex.Message, 1);
            }
            //通用接口调用日志
            new Thread(o =>
            {
                try
                {
                    TFS_SystemJournal journal = new TFS_SystemJournal()
                    {
                        FID = DateTime.Now.ToString("yyMMdd"),
                        FParamIn = inParam == null ? "" : JsonConvert.SerializeObject(inParam),
                        FParamOut = JsonConvert.SerializeObject(response),
                        FAddUser = HttpContextHelp.GetUserId(request),
                        FBower = HttpContextHelp.GetBrowserInfo(request),
                        FApiUrl = request.RequestUri.AbsolutePath,
                        FIP = HttpContextHelp.GetIPAddress(request)
                    };
                    AppSettingsHelper.GetSqlSugar().Insertable(journal).ExecuteCommandAsync();
                }
                catch (Exception) { }
            })
            { IsBackground = true }.Start();
            if (request.Properties.ContainsKey("reticket")) response.Ticket = request.Properties["reticket"].ToString();
            return response;
        }

        public static void AddSystemJournal(HttpRequestMessage request, object inParam = null, object outParam = null, int userId = -1, string apiUrl = "")
        {
            //通用接口调用日志
            new Thread(o =>
            {
                try
                {
                    TFS_SystemJournal journal = new TFS_SystemJournal()
                    {
                        FID = DateTime.Now.ToString("yyMMdd"),
                        FParamIn = inParam == null ? "" : JsonConvert.SerializeObject(inParam),
                        FParamOut = outParam == null ? "" : JsonConvert.SerializeObject(outParam),
                        FAddUser = userId > 0 ? userId : HttpContextHelp.GetUserId(request),
                        FBower = HttpContextHelp.GetBrowserInfo(request),
                        FApiUrl = !string.IsNullOrEmpty(apiUrl) ? apiUrl : request != null ? request.RequestUri.AbsolutePath : "",
                        FIP = HttpContextHelp.GetIPAddress(request)
                    };
                    AppSettingsHelper.GetSqlSugar().Insertable(journal).ExecuteCommandAsync();
                }
                catch (Exception) { }
            })
            { IsBackground = true }.Start();
        }

        public static void WriteMessage(string msgData, int msgType)
        {
            try
            {
                if (msgData.IndexOf("TFS_SystemJournal") != -1) return;
                string path = AppDomain.CurrentDomain.BaseDirectory + "/log/" + DateTime.Now.ToString("yyyy-MM") + "/";
                path = path.Replace("\\", "/").Trim('/') + "/";
                if (!Directory.Exists(path)) Directory.CreateDirectory(path);
                string fileType = ".log";
                switch (msgType)
                {
                    case 1:
                        fileType = "_error" + fileType;
                        break;
                    case 2:
                        fileType = "_debug" + fileType;
                        break;
                    default:
                        fileType = "_info" + fileType;
                        break;
                }
                File.AppendAllText(path + DateTime.Now.ToString("dd") + fileType, msgData + "\r\n");
            }
            catch (Exception) { }
        }
    }
}
