using Back.Common;
using Shared.DTOs;
using Back.Data.Contracts;
using Back.Data.Models;
using Shared.DTOs.Serch;
using Microsoft.EntityFrameworkCore;
using Back.Data.Infrastructure.Repository;
using System.Net.Sockets;

namespace Back.Services
{
    public class servTicket
    {
        private readonly IAsyncRepository<TiceketUnknownPeople> _ticketUnknownPeopleRepo;
        private readonly RepositoryBase<Ticket> _ticketRepo;
        private readonly IAsyncRepository<SubTicket> _subticketRepo;
        public servTicket(IAsyncRepository<TiceketUnknownPeople> ticketUnknownPeopleRepo
                            , RepositoryBase<Ticket> ticketRepo
            ,IAsyncRepository<SubTicket> subticketRepo
            )
        {
            _ticketUnknownPeopleRepo = ticketUnknownPeopleRepo;
            _ticketRepo = ticketRepo;
            _subticketRepo = subticketRepo;
        }
        public async Task<PagingDto<TicketDTO>> GetAll(int CompanyID, ItemSerchGetTicket itemSerch)
        {
            #region AdvancedSearch
            var invok = _ticketRepo
                .Get(w => w.CompanyIDOrMobile == CompanyID.ToString());

            if (!string.IsNullOrEmpty(itemSerch.Title))
                invok = invok.Where(w => w.Title.Contains(itemSerch.Title));

            if (itemSerch.TicketID.HasValue)
                invok = invok.Where(w => w.ID == itemSerch.TicketID);

            #endregion

            //-----------------------
            return await invok.OrderByDescending(o => o.ID)
                .Select(s => new TicketDTO()
                {
                    CreateDate = s.CreateDate.ShamciToFormatShamci(),
                    CreateTime = s.CreateTime,
                    TicketID = s.ID,
                    EndDate = s.EndDate.ShamciToFormatShamci(),
                    EndTime = s.EndTime,
                    Status = s.Status,
                    MsgStatus = s.Status.GetEnumDisplayName(),
                    Title = s.Title
                })
                .Paging(itemSerch.PageIndex, itemSerch.PageSize);
        }
        public async Task<Ticket?> GetTicketorgbyTicketID(int CompanyID, int TicketID)
        {
            return await _ticketRepo.Get(w => w.ID == TicketID 
            && w.CompanyIDOrMobile == CompanyID.ToString()).FirstOrDefaultAsync();
        }
        public async Task<ICollection<SubTicketDTO>> GetSubTicket(int CompanyID, int TicketID)
        {
            #region AdvancedSearch
            var invok = _subticketRepo
                .Get(w => w.TicketID == TicketID && w.Ticket.CompanyIDOrMobile==CompanyID.ToString());
            #endregion

            //-----------------------
            return await invok.OrderBy(o => o.ID).Select(s => new SubTicketDTO()
            {
                Date = s.Date.ShamciToFormatShamci(),
                Text = s.Text,
                Time = s.Time,
                Type = s.Type,
                MsgType = s.Type.GetEnumDisplayName()
            })
                .ToListAsync();
        }
        public async Task<bool> ExistTicketByTicketID(int TicketID)
        {
            return await _ticketRepo.Get(a => a.ID == TicketID && (a.Status != StatusTicket.End && a.Status != StatusTicket.optout)).AnyAsync();
        }
        public async Task<Ticket?> NewTicket(CTicketDto item, StatusTicket status = StatusTicket.Awaitingreview)
        {
            try
            {
                using var transaction =await _ticketRepo._dbContext.Database.BeginTransactionAsync();
                var ticket = await _ticketRepo.AddAsync(new Ticket
                {
                    CompanyIDOrMobile = item.CompanyID,
                    CreateDate = DateTime.Now.ConvertMiladiToShamsi(),
                    CreateTime = DateTime.Now.ToString("hh:mm tt"),
                    Title = item.Title,
                    Status = status
                });
                if (ticket.ID>0)
                {
                    if (await _subticketRepo.AddBoolResultAsync(new SubTicket
                    {
                        Date = DateTime.Now.ConvertMiladiToShamsi(),
                        Time = DateTime.Now.ToString("hh:mm tt"),
                        TicketID = ticket.ID,
                        Text = item.Text,
                        Type = SideType.Customer
                    }))
                    {
                       await transaction.CommitAsync();
                        return ticket;
                    }
                    else 
                    { 
                        await transaction.RollbackAsync();
                        return null;
                    }
                }
                else 
                {
                    await transaction.RollbackAsync();
                    return null;
                }
                
                //_contextMongodb.InsertItem(new SysLog()
                //{
                //    TraceIdentifierID = _httpContextAccessor.HttpContext.TraceIdentifier,
                //    Datetime = DateTime.Now.ConvertMiladiToShamsi(),
                //    Method = $"{_httpContextAccessor.HttpContext.Request.Method}/{this.GetType().FullName}/NewTicket",
                //    Value = JsonConvert.SerializeObject(item),
                //    Route = _httpContextAccessor.HttpContext.Request.Path,
                //    Type = "User"
                //});
       
            }
            catch (Exception ex)
            {
                //_contextMongodb.InsertItem(new SysLog()
                //{
                //    TraceIdentifierID = _httpContextAccessor.HttpContext.TraceIdentifier,
                //    Datetime = DateTime.Now.ConvertMiladiToShamsi(),
                //    Method = $"{_httpContextAccessor.HttpContext.Request.Method}/{this.GetType().FullName}/NewTicket",
                //    Value = ex.Message,
                //    Route = _httpContextAccessor.HttpContext.Request.Path,
                //    Type = "catch"
                //});
                return null;
            }
        }
        public async Task<int?> NewPepole(string FullName, string Mobile)
        {
            try
            {
                var ID = _ticketUnknownPeopleRepo.Get(w => w.Mobile == Mobile).Select(s => s.ID).FirstOrDefault();
                if (ID != null && ID > 0)
                    return ID;
                var item = await _ticketUnknownPeopleRepo.AddAsync(new TiceketUnknownPeople
                {
                    FullName = FullName,
                    Mobile = Mobile
                });
                //_contextMongodb.InsertItem(new SysLog()
                //{
                //    TraceIdentifierID = _httpContextAccessor.HttpContext.TraceIdentifier,
                //    Datetime = DateTime.Now.ConvertMiladiToShamsi(),
                //    Method = $"{_httpContextAccessor.HttpContext.Request.Method}/{this.GetType().FullName}/NewPepole",
                //    Value = JsonConvert.SerializeObject(item),
                //    Route = _httpContextAccessor.HttpContext.Request.Path,
                //    Type = "User"
                //});
                return item.ID;
            }
            catch (Exception ex)
            {
                //_contextMongodb.InsertItem(new SysLog()
                //{
                //    TraceIdentifierID = _httpContextAccessor.HttpContext.TraceIdentifier,
                //    Datetime = DateTime.Now.ConvertMiladiToShamsi(),
                //    Method = $"{_httpContextAccessor.HttpContext.Request.Method}/{this.GetType().FullName}/NewPepole",
                //    Value = ex.Message,
                //    Route = _httpContextAccessor.HttpContext.Request.Path,
                //    Type = "catch"
                //});
                return 0;
            }

        }
        public async Task<bool> AddSubTicket(AddSubTicket item)
        {
            try
            {
               return await _subticketRepo.AddBoolResultAsync(new SubTicket
                {
                    Date = DateTime.Now.ConvertMiladiToShamsi(),
                    Time = DateTime.Now.ToString("hh:mm tt"),
                    TicketID = item.TicketID,
                    Text = item.Text,
                    Type = SideType.Customer
                });
                //_contextMongodb.InsertItem(new SysLog()
                //{
                //    TraceIdentifierID = _httpContextAccessor.HttpContext.TraceIdentifier,
                //    Datetime = DateTime.Now.ConvertMiladiToShamsi(),
                //    Method = $"{_httpContextAccessor.HttpContext.Request.Method}/{this.GetType().FullName}/AddSubTicket",
                //    Value = JsonConvert.SerializeObject(item),
                //    Route = _httpContextAccessor.HttpContext.Request.Path,
                //    Type = "User"
                //});

            }
            catch (Exception ex)
            {
                //_contextMongodb.InsertItem(new SysLog()
                //{
                //    TraceIdentifierID = _httpContextAccessor.HttpContext.TraceIdentifier,
                //    Datetime = DateTime.Now.ConvertMiladiToShamsi(),
                //    Method = $"{_httpContextAccessor.HttpContext.Request.Method}/{this.GetType().FullName}/AddSubTicket",
                //    Value = ex.Message,
                //    Route = _httpContextAccessor.HttpContext.Request.Path,
                //    Type = "catch"
                //});
                return false;
            }

        }
        public async Task<bool> UpdateTicket(Ticket ticket)
        {
            try
            {
               return await _ticketRepo.UpdateAsync(ticket);
                //_contextMongodb.InsertItem(new SysLog()
                //{
                //    TraceIdentifierID = _httpContextAccessor.HttpContext.TraceIdentifier,
                //    Datetime = DateTime.Now.ConvertMiladiToShamsi(),
                //    Method = $"{_httpContextAccessor.HttpContext.Request.Method}/{this.GetType().FullName}/UpdateTicket",
                //    Value = JsonConvert.SerializeObject(ticket),
                //    Route = _httpContextAccessor.HttpContext.Request.Path,
                //    Type = "User"
                //});
              
            }
            catch (Exception ex)
            {
                //_contextMongodb.InsertItem(new SysLog()
                //{
                //    TraceIdentifierID = _httpContextAccessor.HttpContext.TraceIdentifier,
                //    Datetime = DateTime.Now.ConvertMiladiToShamsi(),
                //    Method = $"{_httpContextAccessor.HttpContext.Request.Method}/{this.GetType().FullName}/UpdateTicket",
                //    Value = ex.Message,
                //    Route = _httpContextAccessor.HttpContext.Request.Path,
                //    Type = "catch"
                //});
                return false;
            }

        }

    }
}
