using Back.Data.Contracts;
using Back.Data.Models;
using Shared.DTOs.Serch;
using Shared.DTOs;
using Back.Common;
using Microsoft.EntityFrameworkCore;

namespace Back.Services
{
    public class servInvoice
    {
        private readonly IAsyncRepository<Invoice> _invoiceRepo;
        private readonly IAsyncRepository<InvoiceStatusChang> _invoiceStatusChangPaymentRepo;
        private readonly CheckPermission _checkPermission;
        public servInvoice(IAsyncRepository<Invoice> invoiceRepo, CheckPermission checkPermission
                          , IAsyncRepository<InvoiceStatusChang> invoiceStatusChangPaymentRepo)
        {
            _invoiceStatusChangPaymentRepo = invoiceStatusChangPaymentRepo;
            _invoiceRepo = invoiceRepo;
            _checkPermission = checkPermission;

        }
        public async Task<InvoiceDTO?> GetInvoice(int CompanyID, int ID, bool notloaddelete = true)
        {
            #region AdvancedSearch
            var invok = _invoiceRepo
                .Get(w => w.CompanyID == CompanyID  && w.ID == ID);
            if (notloaddelete)
            {
                 invok = invok
               .Where(w => !w.IsDeleted);
                 
            }

            #endregion
            //-----------------------
            return await invok
                .Include(inc => inc.invoiceDetails)
                  .ThenInclude(inc => inc.cODItem)
                                       .ThenInclude(inc => inc.CODUnit)
                                       .Include(inc=>inc.sentTax)
                //.Include(inc => inc.payments)
                .Include(inc => inc.pattern)
                .Select(s => new InvoiceDTO()
                {
                    IsDeleted=s.IsDeleted,
                    PatternID = s.PatternID,
                    PatternTitle = s.pattern.Title,
                    CustomerID = s.CustomerID,
                    CustomerName = s.Customer.FullName,
                    ID = s.ID,
                    InvoiceDate = s.InvoiceDate.ShamciToFormatShamci(),
                    invoiceTypeTitle = s.invoiceType.GetEnumDisplayName(),
                    invoiceType = s.invoiceType,
                    Title = s.Title,
                    InvoicIssueDate = s.InvoicIssueDate.ShamciToFormatShamci(),
                    BillReference = s.BillReference,
                    tbill = s.tbill,
                    Des = s.Des,
                    PreparedtoSendtoTax = s.PreparedtoSendtoTax,
                    tdis = s.tdis,
                    tvam = s.tvam,
                    Udate = s.Udate.ShamciToFormatShamci(),
                    InvoiceSendTaxs=s.sentTax.OrderBy(o => o.ID).Select(s=>new SentTaxDto()
                    {
                        Date = s.Date.ShamciToFormatShamci(),
                        Time = s.Time,
                        ID = s.ID,
                        InvoiceID = s.InvoiceID,
                        SentStatus = s.SentStatus,
                        InvoiceType= s.InvoiceType,
                        msgInvoiceType = s.InvoiceType.GetEnumDisplayName(),
                        msgSentStatus = s.SentStatus.GetEnumDisplayName()
                    }).ToList(),
                    items = s.invoiceDetails.OrderBy(o => o.ID).Select(x => new InvoiceItemDTO()
                    {
                        ID = x.ID,
                        CODID = x.CODID,
                        adis = x.adis,
                        am = x.am.Value,
                        dis = x.dis,
                        fee = x.fee.Value,
                        mu = x.unitTitle,
                        sstt = x.sstt,
                        tsstam = x.tsstam,
                        vam = x.vam,
                        vra = x.vra,
                        prdis = x.prdis
                    }).ToList(),
                    payments = new List<InvoicePaymentDTO>() //s.payments.OrderBy(o => o.ID).Select(x => new InvoicePaymentDTO()
                    //{
                    //    ID = x.ID,
                    //    acn = x.acn,
                    //    iinn = x.acn,
                    //    pcn = x.acn,
                    //    pdt = x.pdt,
                    //    PaymentDateTime=x.PaymentDateTime,
                    //    pid = x.pid,
                    //    pmt = x.pmt,
                    //    pv = x.pv,
                    //    trmn = x.trmn,
                    //    trn = x.acn
                    //}).ToList()
                    ,
                })
                .FirstOrDefaultAsync();
        }
        public async Task<PagingDto<InvoiceGridDTO>?> GetInvoices(int CompanyID, ItemSerchGetInvoices itemSerch)
        {
            #region AdvancedSearch
            var invok = _invoiceRepo
                .Get(w => w.CompanyID == CompanyID && !w.IsDeleted/* && !w.BillReference.HasValue*/);

            if (itemSerch.InvoiceID != null)
                invok = invok.Where(w => w.ID == itemSerch.InvoiceID);

            if (itemSerch.CustomerID != null)
                invok = invok.Where(w => w.CustomerID == itemSerch.CustomerID);

            if (itemSerch.invoiceType != null)
                invok = invok.Where(w => w.invoiceType == itemSerch.invoiceType);

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

            if (itemSerch.refInvoiceID != null)
                invok = invok.Where(w => w.BillReference==itemSerch.refInvoiceID);
            //foreach (InputObj item in inputObjs)
            //    invok = invok.Where(ExMethod.GetFunc<Customer>(item.Param, item.Value));

            #endregion
            //-----------------------
            return await invok
                .Include(inc => inc.invoiceDetails)
                     .ThenInclude(inc => inc.cODItem)
                     .ThenInclude(inc => inc.CODUnit)
                //.Include(inc => inc.payments)
                .Include(inc => inc.pattern)
                .Select(s => new InvoiceGridDTO()
                {
                    
                    CustomerID = s.CustomerID,
                    CustomerName = s.Customer.FullName,
                    ID = s.ID,
                    invoiceTypeTitle = s.invoiceType.GetEnumDisplayName(),
                    Title = s.Title,
                    InvoicIssueDate = s.InvoicIssueDate.ShamciToFormatShamci(),
                    tbill = s.tbill,
                    tdis = s.tdis,
                    tvam = s.tvam,
                    Udate = s.Udate.ShamciToFormatShamci(),
                    BillReference = s.BillReference
                })
                .Paging(itemSerch.PageIndex, itemSerch.PageSize);
        }
        public async Task<bool> ExistInvoiceByInvoiceID(int CompanyID, int InvoiceID)
        {
            return await _invoiceRepo.Get(w => w.ID == InvoiceID && w.CompanyID == CompanyID && !w.IsDeleted).AnyAsync();

        }
        public async Task<bool> checkFatherInvoiceByInvoiceID(int CompanyID, int InvoiceID)
        {
            return await _invoiceRepo.Get(w => w.BillReference == InvoiceID && w.CompanyID == CompanyID && !w.IsDeleted).AnyAsync();

        }
        public async Task<int> AddInvoice(Invoice invoice, bool calculate = true)
        {
            invoice.Cdate = DateTime.Now.ConvertMiladiToShamsi();
            invoice.Udate = DateTime.Now.ConvertMiladiToShamsi();
            invoice.PreparedtoSendtoTax = false;
            if (calculate)
            {
                if (await _checkPermission.ExtensionofAccess(invoice.CompanyID.Value, 3, "-1"))
                {
                    try
                    {
                        var item = await _invoiceRepo.AddAsync(invoice);
                        return item.ID;
                    }
                    catch (Exception ex )
                    {
                        return -1;
                        
                    }
                   
                }

                return -1;
            }
            else
            {
                try
                {
                    var item = await _invoiceRepo.AddAsync(invoice);
                    return item.ID;
                }
                catch (Exception ex)
                {
                    return -1;
                    
                }
             
            }

        }
        public async Task<bool> UpdateInvoice(Invoice invoice)
        {
            invoice.Udate = DateTime.Now.ConvertMiladiToShamsi();
            invoice.PreparedtoSendtoTax = false;


            return await _invoiceRepo.UpdateAsync(invoice);
        }
        public async Task<Invoice?> GetInvoiceByInvoiceID(int CompanyID, int InvoiceID)
        {
            return await _invoiceRepo
                .Get(w => w.ID == InvoiceID && w.CompanyID == CompanyID && !w.IsDeleted)
                .Include(inc=>inc.invoiceDetails)
                .FirstOrDefaultAsync();
        }
        public async Task<bool> DeleteInvoice(Invoice item)
        {

            try
            {
                item.Udate = DateTime.Now.ConvertMiladiToShamsi();
                item.IsDeleted = true;
                return await _invoiceRepo.UpdateAsync(item);
                //SysLog log = new SysLog()
                //{
                //    TraceIdentifierID = _httpContextAccessor.HttpContext.TraceIdentifier,
                //    Datetime = DateTime.Now.ConvertMiladiToShamsi(),
                //    Method = $"{_httpContextAccessor.HttpContext.Request.Method}/{this.GetType().FullName}/DeleteCustomer",
                //    Value = JsonConvert.SerializeObject(item.ID),
                //    Route = _httpContextAccessor.HttpContext.Request.Path,
                //    Type = "User"
                //};
                //_contextMongodb.InsertItem(log);
            }
            catch (Exception ex)
            {
                //SysLog log = new SysLog()
                //{
                //    TraceIdentifierID = _httpContextAccessor.HttpContext.TraceIdentifier,
                //    Datetime = DateTime.Now.ConvertMiladiToShamsi(),
                //    Method = $"{_httpContextAccessor.HttpContext.Request.Method}/{this.GetType().FullName}/DeleteCustomer",
                //    Value = ex.Message,
                //    Route = _httpContextAccessor.HttpContext.Request.Path,
                //    Type = "catch"
                //};
                //_contextMongodb.InsertItem(log);
                return false;

            }
        }
        public async Task<InvoiceDTO?> ChangeInvoiceType(Invoice invoiceitem, InvoiceType item, bool action = true)
        {
            string old = invoiceitem.invoiceType.GetEnumDisplayName();
            invoiceitem.invoiceType = item;
            invoiceitem.Udate = DateTime.Now.ConvertMiladiToShamsi();
            invoiceitem.PreparedtoSendtoTax = false;
            try
            {
                await _invoiceStatusChangPaymentRepo.AddBoolResultAsync(new InvoiceStatusChang()
                {
                    InvoiceID = invoiceitem.ID,
                    ToStatus = item.GetEnumDisplayName(),
                    FromStatus = old,
                    Date = DateTime.Now.ConvertMiladiToShamsi(),
                    UserID = invoiceitem.LastChangeUserID
                });
                if (action)
                {
                    var result = await _invoiceRepo.UpdateAsync(invoiceitem);
                    if (result)
                    {
                        return await GetInvoice(invoiceitem.CompanyID.Value, invoiceitem.ID);
                    }
                    else
                    {
                        return null;
                    }

                }
                else return await GetInvoice(invoiceitem.CompanyID.Value, invoiceitem.ID);
                //_contextMongodb.InsertItem(new SysLog()
                //{
                //    TraceIdentifierID = _httpContextAccessor.HttpContext.TraceIdentifier,
                //    Datetime = DateTime.Now.ConvertMiladiToShamsi(),
                //    Method = $"{_httpContextAccessor.HttpContext.Request.Method}/{this.GetType().FullName}/ChangeInvoiceType",
                //    Value = $"From {old} to {item.ToString()}",
                //    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}/ChangeInvoiceType",
                //    Value = $"From {old} to {item.ToString()}" + '\n' + ex.Message,
                //    Route = _httpContextAccessor.HttpContext.Request.Path,
                //    Type = "catch"
                //});
                return null;
            }



        }
    }
}
