using Microsoft.Extensions.Logging;
using PARR.EsppApi.Constants;
using PARR.EsppApi.Models;
using PARR.EsppApi.Models.Query;
using PARR.EsppApi.Requests;
using PARR.EsppApi.Settings;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Unicode;

namespace PARR.EsppApi
{
    internal class EsppApiService : IEsppApiService
    {
        private readonly ILogger<EsppApiService> logger;
        private readonly EsppOrderSettings esppOrderSettings;
        private readonly EsppHttpService esppHttpService;

        public EsppApiService(ILogger<EsppApiService> logger, EsppOrderSettings esppOrderSettings, EsppHttpService esppHttpService)
        {
            this.logger = logger;
            this.esppOrderSettings = esppOrderSettings;
            this.esppHttpService = esppHttpService;
        }


        public Task<EsppResultBase<EsppResponse>> SetStatusInWorkAsync(string recordId, string resultMsg)//TODO упростить можно без RecordIdQuery
        {
            return SetStatusAsync(recordId, "2-В работе", resultMsg);
        }


        public Task<EsppResultBase<EsppResponse>> SetStatusIsDoneAsync(string recordId, string resultMsg, EsppOrderClosingCodeEnum closingCode)//TODO упростить можно без RecordIdQuery
        {
            return SetStatusAsync(recordId, "4-Выполнен", resultMsg, closingCode);
        }


        private async Task<EsppResultBase<EsppResponse>> SetStatusAsync(
            string recordId,
            string newStatusStr,
            string resultMsg,
            EsppOrderClosingCodeEnum? closingCode = null
            )
        {
            var request = new SetStatusRequest(closingCode ?? EsppOrderClosingCodeEnum.Complete)
            {
                recordid = recordId,
                status = newStatusStr,
                assignee = esppOrderSettings.AccountName,
                resolution = resultMsg,
                rzdEventCode = esppOrderSettings.CodeRRO,
                rzdKeRobot = esppOrderSettings.RobotEk
            };

            var result = await esppHttpService.SendAsync<EsppResponse>(GenerateRequest(EsppOperationsEnum.SaveTask, request));

            if (result.Data != null && result.Data.ErrorCode != "0")
                return new EsppResultBase<EsppResponse>(null, false, new Exception(result.Data.Message));

            return result;
        }


        public async Task<EsppResultBase<EsppOrder>> FindOrderByRecordIdAsync(string recordId)
        {
            //TODO упростить можно без RecordIdQuery
            //var query = $"<ROOT operation=\"GetTask\" returnFormat=\"json\">\r\n{{\"recordid\":\"{recordId}\"}}\r\n</ROOT>";

            //var result = await esppHttpService.SendAsync<EsppOrder>(QuerySanitize(query));

            var request = new GetTaskRequest { recordid = recordId };
            var result = await esppHttpService.SendAsync<EsppOrder>(GenerateRequest(EsppOperationsEnum.GetTask, request));

            return result;
        }


        public async Task<EsppResultBase<IEnumerable<EsppOrder>>> FindOrdersAsync(FindOrdersQuery query)
        {
            DateTime? generateDateStartWOTimeZone = query.GenerateDateStart.HasValue ? query.GenerateDateStart.Value.AddHours(esppOrderSettings.EsppUserTimeZone) : null;
            DateTime? generateDateEndWOTimeZone = query.GenerateDateEnd.HasValue ? query.GenerateDateEnd.Value.AddHours(esppOrderSettings.EsppUserTimeZone) : null;

            var conditions = new List<string>();

            if (!string.IsNullOrEmpty(query.StatusIs))
                conditions.Add($"status=\"{query.StatusIs}\"");

            if (!string.IsNullOrEmpty(query.DescriptionContains))
                conditions.Add($"description like \"*{query.DescriptionContains}*\"");
            //if (!string.IsNullOrEmpty(query.TemplateNameContains))
            //    conditions.Add($"templateName like \"*{query.TemplateNameContains}*\"");

            if (generateDateStartWOTimeZone.HasValue)
                //conditions.Add($"open.time>='{generateDateStartWOTimeZone.Value.Day}/{generateDateStartWOTimeZone.Value.Month}/{generateDateStartWOTimeZone.Value.Year}" +
                //    $" {generateDateStartWOTimeZone.Value.Hour}:{generateDateStartWOTimeZone.Value.Minute}:{generateDateStartWOTimeZone.Value.Second}'");
                conditions.Add($"open.time>='{generateDateStartWOTimeZone.Value.ToString(@"dd\/MM\/yyyy HH:mm:ss")}'");

            if (generateDateEndWOTimeZone.HasValue)
                //conditions.Add($"open.time<='{generateDateEndWOTimeZone.Value.Day}/{generateDateEndWOTimeZone.Value.Month}/{generateDateEndWOTimeZone.Value.Year}" +
                //    $" {generateDateEndWOTimeZone.Value.Hour}:{generateDateEndWOTimeZone.Value.Minute}:{generateDateEndWOTimeZone.Value.Second}'");
                conditions.Add($"open.time<='{generateDateEndWOTimeZone.Value.ToString(@"dd\/MM\/yyyy HH:mm:ss")}'");

            if (!conditions.Any())
            {
                logger.LogDebug("Пришёл пустой запрос в EsppHttpService.FindOrdersAsync");
                return new EsppResultBase<IEnumerable<EsppOrder>>(null, false);
            }

            //var request = $"<ROOT operation=\"GetTaskList\" returnFormat=\"json\">{{\"VIEW_QUERY\":\"{string.Join(" and ", conditions)}\"}}</ROOT>";
            //var result = await esppHttpService.SendAsync<IEnumerable<EsppOrder>>(QuerySanitize(request));

            var request = new GetTaskListRequest { VIEW_QUERY = string.Join(" and ", conditions) };

            // костыль. так как в ЕСПП не json а какой-то свой модерновый формат. формируем запрос вручную
            var viewQueryStr = $"{{\"VIEW_QUERY\":\"{request.VIEW_QUERY}\"}}";
            var result = await esppHttpService.SendAsync<IEnumerable<EsppOrder>>(GenerateRequest(EsppOperationsEnum.GetTaskList, viewQueryStr));

            //var result = await esppHttpService.SendAsync<IEnumerable<EsppOrder>>(GenerateRequest(EsppOperationsEnum.GetTaskList, request));

            return result;

        }


        public async Task<EsppResultBase<EsppResponse>> AddMTnkAsync(AddMtnkQuery mtnk)
        {
            //var query = $"<ROOT operation=\"AddMTNK\" returnFormat=\"json\">{{\"recordid\":\"{mtnk.RecordId}\"," +
            //    $"\"joboperation\":\"{mtnk.JobOperation}\",\"time\":\"{mtnk.Time}\",\"workscope\":\"{mtnk.Workspace}\"" +
            //    $"}}</ROOT>";

            //var result = await esppHttpService.SendAsync<EsppResponse>(QuerySanitize(query));

            var request = new AddMTNKRequest
            {
                recordid = mtnk.RecordId,
                joboperation = mtnk.JobOperation,
                time = mtnk.Time,
                workscope = mtnk.Workspace.ToString()
            };
            var result = await esppHttpService.SendAsync<EsppResponse>(GenerateRequest(EsppOperationsEnum.AddMTNK, request));

            if (result.Data != null && result.Data.ErrorCode != "0")
                return new EsppResultBase<EsppResponse>(null, false, new Exception(result.Data.Message));

            return result;
        }


        /// <summary>
        /// Формирует запрос в ЕСПП из строки
        /// </summary>
        /// <param name="operation"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        private string GenerateRequest(EsppOperationsEnum operation, string query)
        {
            var baseRequest = $"<ROOT operation=\"operationValue\" returnFormat=\"json\">requestValue</ROOT>";

            return baseRequest.Replace("operationValue", operation.ToString()).Replace("requestValue", query);
        }


        /// <summary>
        /// Формирует запрос в ЕСПП из jsonQuery 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="operation"></param>
        /// <param name="jsonQuery"></param>
        /// <returns></returns>
        private string GenerateRequest<T>(EsppOperationsEnum operation, T jsonQuery)
        {
            var jsonOptions = new JsonSerializerOptions { Encoder = JavaScriptEncoder.Create(UnicodeRanges.All, UnicodeRanges.Cyrillic) };
            var strQuery = JsonSerializer.Serialize(jsonQuery, jsonOptions);

            return GenerateRequest(operation, strQuery);
        }
    }
}
