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)
        {
            #region AdvancedSearch
            var invok = _invoiceRepo
                .Get(w => w.CompanyID == CompanyID && !w.IsDeleted && w.ID==ID);


            #endregion
            //-----------------------
            return await invok
                .Include(inc => inc.invoiceDetails)
                .Include(inc => inc.payments)
                .Include(inc => inc.pattern)
                .Select(s => new InvoiceDTO()
                {
                    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(),
                    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.am,
                        vra = x.vra
                    }).ToList(),
                    payments = 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);

            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));
            //foreach (InputObj item in inputObjs)
            //    invok = invok.Where(ExMethod.GetFunc<Customer>(item.Param, item.Value));

            #endregion
            //-----------------------
            return await invok
                .Include(inc => inc.invoiceDetails)
                .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(),
                })
                .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<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"))
                {
                    var item= await _invoiceRepo.AddAsync(invoice);
                    return item.ID;
                }
                   
                return -1;
            }
            else
            {
                var item = await _invoiceRepo.AddAsync(invoice);
                return item.ID;
            }

        }
        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)
                .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<bool> 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)
                    return await _invoiceRepo.UpdateAsync(invoiceitem);
                else return true;
                //_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 false;
            }



        }
    }
}
