using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Enums;
using APT.Infrastructure.Core;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.IServices.FM;
using System;
using System.Linq;
using System.Net;
using APT.Infrastructure.Api;
namespace APT.BaseData.Services.Services.FM
{
    public class PFSysLogService : CommonService, IPFSysLogService
    {
        public PFSysLogService(IRepository repository)
          : base(repository)
        {
        }

        /// <summary>
        /// 添加登入系统日志
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="platformType">平台类型 PFPlatTypeEnum</param>
        public void AddLoginLog(Guid userId, int platformType)
        {
            var user = this.GetEntity<T_FM_USER>(userId.ToString());
            if (user != null)
                AddLog(user.ORG_ID.Value, userId, PFSysLogTypeEnum.登入,
                    string.Format("用户【{0}】登入{1}系统", user.NAME, ((PFPlatTypeEnum)platformType).ToString()),
                    string.Format("用户ID：{0}", userId.ToString()));
        }
        public void AddLoginLogByApp(Guid userId, int platformType,KeywordFilter filter)
        {
            var user = this.GetEntity<T_FM_USER>(x=>x.ID== userId, filter);
            if (user != null)
                AddLog(user.ORG_ID.Value, userId, PFSysLogTypeEnum.登入,
                    string.Format("用户【{0}】登入{1}系统", user.NAME, ((PFPlatTypeEnum)platformType).ToString()),
                    string.Format("用户ID：{0}", userId.ToString()),filter);
        }  
        /// <summary>
        /// 添加登出系统日志
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="platformType">平台类型 PFPlatTypeEnum</param>
        public void AddLoginOut(Guid userId, int platformType)
        {
            var user = this.GetEntity<T_FM_USER>(userId.ToString());
            if (user != null)
                AddLog(user.ORG_ID.Value, userId, PFSysLogTypeEnum.登出,
                    string.Format("用户【{0}】退出{1}系统", user.NAME, ((PFPlatTypeEnum)platformType).ToString()),
                    string.Format("用户ID：{0}", userId.ToString()));
        }

        /// <summary>
        /// 添加新增日志
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="formCode"></param>
        /// <param name="ids">实体ID列表 多个逗号隔开</param>
        /// <param name="codes">实体编号 多个逗号隔开</param>
        /// <param name="extData">额外数据</param>
        public void AddAddLog(Guid userId, string formCode, string ids, string codes, string extData)
        {
            var user = this.GetEntity<T_FM_USER>(userId.ToString());
            if (user != null)
            {
                T_PF_FORM form = null;
                if (!string.IsNullOrEmpty(formCode))
                    form = this.GetEntity<T_PF_FORM>(t => t.CODE == formCode, new BaseFilter(user.ORG_ID));
                AddLog(user.ORG_ID.Value, userId, PFSysLogTypeEnum.新增, formCode,
                    string.Format("用户【{0}】:新增{1}{2}", user.NAME, (form == null ? string.Empty : ("表单:" + form.NAME)), (string.IsNullOrEmpty(codes) ? string.Empty : (",编号:" + codes))),
                    string.Format("ID：{0}", ids), extData);
            }
        }


        /// <summary>
        /// 添加编辑日志
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="formCode"></param>
        /// <param name="ids">实体ID列表 多个逗号隔开</param>
        /// <param name="codes">实体编号 多个逗号隔开</param>
        /// <param name="extData">额外数据</param>
        public void AddEditLog(Guid userId, string formCode, string ids, string codes, string extData)
        {
            var user = this.GetEntity<T_FM_USER>(userId.ToString());
            if (user != null)
            {
                T_PF_FORM form = null;
                if (!string.IsNullOrEmpty(formCode))
                    form = this.GetEntity<T_PF_FORM>(t => t.CODE == formCode, new BaseFilter(user.ORG_ID));
                AddLog(user.ORG_ID.Value, userId, PFSysLogTypeEnum.编辑, formCode,
                    string.Format("用户【{0}】:编辑{1}{2}", user.NAME, (form == null ? string.Empty : ("表单:" + form.NAME)), (string.IsNullOrEmpty(codes) ? string.Empty : (",编号:" + codes))),
                    string.Format("ID：{0}", ids), extData);
            }
        }


        /// <summary>
        /// 添加删除日志
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="formCode"></param>
        /// <param name="ids">实体ID列表 多个逗号隔开</param>
        /// <param name="tableName">实体名称</param>
        /// <param name="extData">额外数据</param>
        public void AddDeleteLog(Guid userId, string formCode, string ids, string tableName,string extData)
        {
            var user = this.GetEntity<T_FM_USER>(userId.ToString());
            if (user != null)
            {
                T_PF_FORM form = null;
                if (!string.IsNullOrEmpty(formCode))
                    form = this.GetEntity<T_PF_FORM>(t => t.CODE == formCode, new BaseFilter(user.ORG_ID));
                AddLog(user.ORG_ID.Value, userId, PFSysLogTypeEnum.删除, formCode,
                    string.Format("用户【{0}】删除{1}", user.NAME, (form == null ? string.Empty : ("表单:" + form.NAME))),
                    string.Format("ID：{0},{1}", ids, (string.IsNullOrEmpty(tableName) ? string.Empty : ("表名:" + tableName))),
                    extData);
            }
        }


        /// <summary>
        /// 添加其他日志
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="formCode"></param>
        /// <param name="title">标题</param>
        /// <param name="data">数据</param>
        /// <param name="extData">额外数据</param>
        public void AddOtherLog(Guid userId, string formCode, string title, string data, string extData)
        {
            var user = this.GetEntity<T_FM_USER>(userId.ToString());
            if (user != null)
            {
                AddLog(user.ORG_ID.Value, userId, PFSysLogTypeEnum.其他, formCode,
                    title, data, extData);
            }
        }



        /// <summary>
        /// 添加系统日志
        /// </summary>
        /// <param name="orgId">组织</param>
        /// <param name="userId">用户</param>
        /// <param name="type">类型</param>
        /// <param name="title">标题</param>
        /// <param name="data">数据</param>
        public void AddLog(Guid orgId, Guid userId, PFSysLogTypeEnum type, string title, string data)
        {
            this.AddLog(orgId, userId, type, string.Empty, title, data, string.Empty);
        }
        public void AddLog(Guid orgId, Guid userId, PFSysLogTypeEnum type, string title, string data, KeywordFilter filter)
        {
            this.AddLog(orgId, userId, type, string.Empty, title, data, string.Empty, filter);
        }
        /// <summary>
        /// 添加系统日志
        /// </summary>
        /// <param name="orgId">组织</param>
        /// <param name="userId">用户</param> 
        /// <param name="title">标题</param>
        /// <param name="data">数据</param>
        public void AddLog(Guid orgId, Guid userId, string title, string data)
        {
            this.AddLog(orgId, userId, title, data, string.Empty);
        }
        /// <summary>
        /// 添加系统日志
        /// </summary>
        /// <param name="orgId">组织</param>
        /// <param name="userId">用户</param> 
        /// <param name="title">标题</param>
        /// <param name="data">数据</param>
        /// <param name="extData">额外数据</param>
        public void AddLog(Guid orgId, Guid userId, string title, string data, string extData)
        {
            this.AddLog(orgId, userId, null, title, data, extData);
        }
        /// <summary>
        /// 添加系统日志
        /// </summary>
        /// <param name="orgId">组织</param>
        /// <param name="userId">用户</param>
        /// <param name="formCode">表单</param>
        /// <param name="title">标题</param>
        /// <param name="data">数据</param>
        /// <param name="extData">额外数据</param>
        public void AddLog(Guid orgId, Guid userId, string formCode, string title, string data, string extData)
        {
            this.AddLog(orgId, userId, PFSysLogTypeEnum.其他, formCode, title, data, extData);
        }
        /// <summary>
        /// 添加系统日志
        /// </summary>
        /// <param name="orgId">组织</param>
        /// <param name="userId">用户</param>
        /// <param name="type">类型</param>
        /// <param name="formCode">表单编号</param>
        /// <param name="title">标题</param>
        /// <param name="data">数据</param>
        /// <param name="extData">额外数据</param>
        public void AddLog(Guid orgId, Guid userId, PFSysLogTypeEnum type, string formCode, string title, string data, string extData)
        {
            var sysLog = this.DoAddLog(orgId, userId, type, formCode, title, data, extData);
            this.AddEntity(sysLog);
        }
        public void AddLog(Guid orgId, Guid userId, PFSysLogTypeEnum type, string formCode, string title, string data, 
            string extData, KeywordFilter filter)
        {
            var sysLog = this.DoAddLog(orgId, userId, type, formCode, title, data, extData, filter);
            this.AddEntityByConn(sysLog,filter.SpecifyDbConn);
        }
        private T_PF_SYS_LOG DoAddLog(Guid orgId, Guid userId, PFSysLogTypeEnum type, string formCode, string title, string data, string extData)
        {
            var httpRequest = HttpContext.Current.Request;
            string ip = string.Empty;
            string ipv4 = string.Empty;
            string hostName = string.Empty;
            string browser = string.Empty;
            if (httpRequest.HttpContext.Connection.RemoteIpAddress != null)
                ip = httpRequest.HttpContext.Request.Headers["X-Forwarded-For"];
            if (string.IsNullOrEmpty(ip))
                ip = httpRequest.Host.Host;
            try
            {
                foreach (IPAddress ipAddr in Dns.GetHostEntry(ip).AddressList)
                {
                    if (ipAddr.AddressFamily.ToString() == "InterNetwork")
                    {
                        ipv4 = ipAddr.ToString();
                    }
                }
            }
            catch { }
            try
            {
                hostName = Dns.GetHostEntry(ip).HostName;
            }
            catch { }
            if (string.IsNullOrEmpty(hostName) && string.Compare(ip, httpRequest.HttpContext.Request.Host.Value, true) != 0)
                hostName = httpRequest.HttpContext.Request.Host.Value;
            if (httpRequest.HttpContext.Request.Headers["User-Agent"].Count >= 0)
                browser = httpRequest.HttpContext.Request.Headers["User-Agent"].FirstOrDefault();

            T_PF_SYS_LOG sysLog = new T_PF_SYS_LOG();
            sysLog.ID = Guid.NewGuid();
            sysLog.ORG_ID = orgId;
            sysLog.LOG_TYPE = (int)type;
            sysLog.USER_ID = userId;
            sysLog.LOG_TIME = DateTime.Now;
            sysLog.LOG_TITLE = title;
            sysLog.LOG_DATA = data;
            sysLog.EXT_DATA = extData;
            sysLog.HOST_NAME = (string.IsNullOrEmpty(hostName) ? string.Empty : string.Format("主机名:{0},", hostName))
                + (string.IsNullOrEmpty(ipv4) ? string.Empty : string.Format("IP:{0}", ipv4));
            sysLog.BROWSER_NAME = browser;
            if (!string.IsNullOrEmpty(formCode))
            {
                var form = this.GetEntity<T_PF_FORM>(t => t.CODE == formCode, new BaseFilter(orgId));
                if (form != null)
                    sysLog.LOG_FORM_ID = form.ID;
            }
            return sysLog;
        }
        /// <summary>
        /// APP登录  多库
        /// </summary>
        /// <param name="orgId"></param>
        /// <param name="userId"></param>
        /// <param name="type"></param>
        /// <param name="formCode"></param>
        /// <param name="title"></param>
        /// <param name="data"></param>
        /// <param name="extData"></param>
        /// <returns></returns>
        private T_PF_SYS_LOG DoAddLog(Guid orgId, Guid userId, PFSysLogTypeEnum type, string formCode, 
            string title, string data, string extData, KeywordFilter filter)
        {
            var httpRequest = HttpContext.Current.Request;
            string ip = string.Empty;
            string ipv4 = string.Empty;
            string hostName = string.Empty;
            string browser = string.Empty;
            if (httpRequest.HttpContext.Connection.RemoteIpAddress != null)
                ip = httpRequest.HttpContext.Request.Headers["X-Forwarded-For"];
            if (string.IsNullOrEmpty(ip))
                ip = httpRequest.Host.Host;
            try
            {
                foreach (IPAddress ipAddr in Dns.GetHostEntry(ip).AddressList)
                {
                    if (ipAddr.AddressFamily.ToString() == "InterNetwork")
                    {
                        ipv4 = ipAddr.ToString();
                    }
                }
            }
            catch { }
            try
            {
                hostName = Dns.GetHostEntry(ip).HostName;
            }
            catch { }
            if (string.IsNullOrEmpty(hostName) && string.Compare(ip, httpRequest.HttpContext.Request.Host.Value, true) != 0)
                hostName = httpRequest.HttpContext.Request.Host.Value;
            if (httpRequest.HttpContext.Request.Headers["User-Agent"].Count >= 0)
                browser = httpRequest.HttpContext.Request.Headers["User-Agent"].FirstOrDefault();

            T_PF_SYS_LOG sysLog = new T_PF_SYS_LOG();
            sysLog.ID = Guid.NewGuid();
            sysLog.ORG_ID = orgId;
            sysLog.LOG_TYPE = (int)type;
            sysLog.USER_ID = userId;
            sysLog.LOG_TIME = DateTime.Now;
            sysLog.LOG_TITLE = title;
            sysLog.LOG_DATA = data;
            sysLog.EXT_DATA = extData;
            sysLog.HOST_NAME = (string.IsNullOrEmpty(hostName) ? string.Empty : string.Format("主机名:{0},", hostName))
                + (string.IsNullOrEmpty(ipv4) ? string.Empty : string.Format("IP:{0}", ipv4));
            sysLog.BROWSER_NAME = browser;
            if (!string.IsNullOrEmpty(formCode))
            {
                var form = this.GetEntity<T_PF_FORM>(t => t.CODE == formCode, filter);
                if (form != null)
                    sysLog.LOG_FORM_ID = form.ID;
            }
            return sysLog;
        }
    }
}
