using Hotline.Settings;
using Hotline.Share.Attributes;
using Hotline.Share.Dtos.Settings;
using Hotline.Share.Requests;
using Hotline.Tools;
using MapsterMapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Org.BouncyCastle.Asn1.Ocsp;
using SqlSugar;
using System.Text;
using XF.Domain.Dependency;
using XF.Domain.Repository;

namespace Hotline.Application.Systems
{
    public class SystemLogApplication : ISystemLogApplication, IScopeDependency
	{
		private readonly IMapper _mapper;
		private readonly IRepository<SystemLog> _systemLogRepository;
		public SystemLogApplication(IMapper mapper, IRepository<SystemLog> systemLogRepository) { _mapper = mapper; _systemLogRepository = systemLogRepository; }

		public async Task AddLog<T>(string name, string res, T entity, HttpContext context, string crName ="") {
			SystemLog log = new SystemLog();
			log.Name = name;
			var Method = "";
			switch (context.Request.Method.ToUpper())
			{
				case "GET":
					Method = "GET";
					log.ExecuteParam = context.Request.QueryString.Value;
					break;

				case "POST":
					Method = "POST";
					log.ExecuteUrl += context.Request.QueryString.Value;
					log.ExecuteParam = entity;
					break;
			}
			log.ExecuteUrl = Method + "|" + context.Request.Path;
			log.Status = 1;
			log.ExecuteResult = JsonConvert.SerializeObject(res);
			log.IpUrl = context.Connection.RemoteIpAddress.ToString();
			log.InitId();
			await  _systemLogRepository.AddAsync(log);
			if (!string.IsNullOrEmpty(crName))
				await _systemLogRepository.Updateable().SetColumns(l => new SystemLog() { CreatorName = crName }).Where(l => l.Id == log.Id).ExecuteCommandAsync();
		}

        public async Task<bool> HasByIpUrlAsync(string ipUrl)
        {
			return await _systemLogRepository.Queryable().Where(x => x.IpUrl == ipUrl).AnyAsync();
        }

		[ExportExcel("操作日志")]
        public ISugarQueryable<SystemLogDto> GetSystemLotItems(SysLogPagedKeywordRequest dto)
		{
			var query =  _systemLogRepository.Queryable()
				.WhereIF(dto.IsAll.HasValue && !dto.IsAll.Value, x => !string.IsNullOrEmpty(x.Name))
				.WhereIF(!string.IsNullOrEmpty(dto.Name), x => x.Name.Contains(dto.Name))
				.WhereIF(!string.IsNullOrEmpty(dto.CreatorName), x => x.CreatorName.Contains(dto.CreatorName))
				.WhereIF(!string.IsNullOrEmpty(dto.ExecuteUrl), x => x.ExecuteUrl.Contains(dto.ExecuteUrl))
				.WhereIF(!string.IsNullOrEmpty(dto.ExecuteParam),
					x => SqlFunc.JsonLike(x.ExecuteParam, dto.ExecuteParam))
				.WhereIF(dto.StartTime.HasValue && dto.EndTime.HasValue,
					x => x.CreationTime >= dto.StartTime && x.CreationTime <= dto.EndTime)
				//.WhereIF(!string.IsNullOrEmpty(dto.Keyword), x => x.Name.Contains(dto.Keyword!) || x.CreatorName.Contains(dto.Keyword!))
				.Select(x => new SystemLogDto
				{
					ExecuteParam = x.ExecuteParam
				}, true)
				.OrderByDescending(x => x.CreationTime);
			return query;
        }
    }
}
