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

namespace Back.Services
{
    public class servTaxPayer
    {
        private readonly IAsyncRepository<SentTax> _repoSentTax;
        private readonly IAsyncRepository<Pattern> _repoPattern;
        private readonly IAsyncRepository<Invoice> _invoiceRepo;
        private readonly IAsyncRepository<InvoiceItem> _invoiceitemRepo;
        private readonly IAsyncRepository<FildModeInPattern> _fildModeInPatternRepo;
        private readonly IAsyncRepository<Coding> _codingRepo;
        private readonly IAsyncRepository<SpecialCondition> _specialConditionRepo;
        public servTaxPayer(IAsyncRepository<SentTax> repoSentTax, IAsyncRepository<Pattern> repoPattern
            , IAsyncRepository<Invoice> invoiceRepo, IAsyncRepository<FildModeInPattern> fildModeInPatternRepo
            , IAsyncRepository<Coding> codingRepo, IAsyncRepository<SpecialCondition> specialConditionRepo
            , IAsyncRepository<InvoiceItem> invoiceitemRepo)
        {
            _repoSentTax = repoSentTax;
            _repoPattern = repoPattern;
            _invoiceRepo = invoiceRepo;
            _fildModeInPatternRepo = fildModeInPatternRepo;
            _codingRepo = codingRepo;
            _specialConditionRepo = specialConditionRepo;
            _invoiceitemRepo = invoiceitemRepo;
        }
        public async Task<bool> ExistSuccessfulorSendorpendingInvoiceinCompanyID(int CompanyID)
        {
            return await _repoSentTax.Get(w => w.invoice.CompanyID == CompanyID && (w.SentStatus == SentStatus.Successful || w.SentStatus == SentStatus.Send || w.SentStatus == SentStatus.pending)).AnyAsync();
        }
        public async Task<bool> ExistSuccessfulorSendorpendingInvoice(Invoice invoice)
        {
            return _repoSentTax.Get(w => w.InvoiceType == invoice.invoiceType && w.InvoiceID == invoice.ID &&
             (w.SentStatus == SentStatus.Successful || w.SentStatus == SentStatus.Send || w.SentStatus == SentStatus.pending)).Any();
        }
        public async Task<bool> CheckingTheCompanyKeyInformation(int CompanyID, string UniqeMemory, string PrivateKey, string EconomicCode)
        {
            return await _repoSentTax.Get(w => (w.invoice.company.UniqeMemory == UniqeMemory || w.invoice.company.PrivateKey == PrivateKey || w.invoice.company.EconomicCode == EconomicCode)
            && (w.SentStatus == SentStatus.Successful || w.SentStatus == SentStatus.Send || w.SentStatus == SentStatus.pending)
            && w.invoice.CompanyID != CompanyID).AnyAsync();
        }
        public async Task<List<IdName<int>>> GetPatterns()
        {
            return await _repoPattern.Get(w=>w.Status).Select(s => new IdName<int> { ID = s.ID, Title = s.Title }).ToListAsync();

        }
        public async Task<bool> UpdateInvoice(Invoice invoice)
        {
           return await _invoiceRepo.UpdateAsync(invoice);
        }
        public async Task<Invoice?> GetInvoice(int CompanyID, int ID)
        {
            #region AdvancedSearch
            var invok = _invoiceRepo
                .Get(w => w.CompanyID == CompanyID && w.ID == ID && !w.IsDeleted);
            

            #endregion
            //-----------------------
            return await invok
                    .Include(inc => inc.Customer)
                     .Include(inc => inc.company)
                         .Include(inc => inc.company)
                         .Include(inc => inc.pattern)
                          .ThenInclude(inc => inc.BillType)
                 .Include(inc => inc.payments)
                          .Include(inc => inc.invoice)
                .Include(inc => inc.invoiceDetails)
                  .ThenInclude(inc => inc.cODItem)
                                       .ThenInclude(inc => inc.CODUnit)
                .FirstOrDefaultAsync();
        }
        public async Task<SentTax> GetSentTax(int CompanyID, int ID)
        {
           return await _repoSentTax.Get(w=>w.ID== ID && w.invoice.CompanyID==CompanyID).FirstOrDefaultAsync();
        }
        public async Task<bool> UpdateSentTax(SentTax sent)
        {
            return await _repoSentTax.UpdateAsync(sent);
        }
        public async Task<bool> AddSentTax(SentTax sentTax)
        {
            return await _repoSentTax.AddBoolResultAsync(sentTax);
        }
        public async Task<_TaxPayer.Atemplatefield> GetFildInvoiceForPreparation(Invoice InvoiceItem)
        {
            _TaxPayer.Atemplatefield ret = new _TaxPayer.Atemplatefield();
           

            var invok = _fildModeInPatternRepo.Get
                (w => w.PatternID == InvoiceItem.PatternID && w.FildModeID != 4 && (w.Fild.InputBox == "fild" || w.Fild.InputBox == "fromdb" || w.Fild.InputBox == "autofild") && w.pattern.Status);

            //-----------------------head
            var head = await invok.Where(w => w.Fild.Title == "H").Select(s => new _TaxPayer.Fild()
            {
                FildID = s.FildID,
                eName = s.Fild.Name == "indatim" ? "InvoicIssueDate" : s.Fild.Name == "Indati2m" ? "InvoiceDate" : s.Fild.Name == "cdcd" ? "CottageDateOfCustomsDeclaration" : s.Fild.Name,
                fName = s.Fild.Type,
                ModeID = s.FildModeID,
                ModeTitle = s.FildMode.Title,
                Title = s.Fild.Title,
                InputBox = s.Fild.Name == "indatim" || s.Fild.Name == "Indati2m" || s.Fild.Name == "cdcd" ? "autofild" : s.Fild.InputBox

            }).ToListAsync();
            foreach (_TaxPayer.Fild item in head)
            {
                var resval = InvoiceItem.GetType().GetProperties().Where(w => w.Name == item.eName).Select(s => s.GetValue(InvoiceItem)).FirstOrDefault();
                item.Value = resval == null ? "" : (item.eName == "InvoicIssueDate" || item.eName == "InvoiceDate" || item.eName == "CottageDateOfCustomsDeclaration" ? resval.ToString().ShamciToFormatShamci() :resval.ToString().Split('.').Length==2 ? ((decimal)resval).ToString("N0") : resval.ToString());
                item.DefVals = item.InputBox == "fromdb" ? _codingRepo.Get(w => w.FildID == item.FildID).Select(ss => new _TaxPayer.Coding() { ID = ss.Code, Name = ss.Title }).ToList() : new List<_TaxPayer.Coding>();
                item.Des = item.ModeID == 3 ? _specialConditionRepo.Get(w => w.FildID == item.FildID).Select(ss => ss.condition).ToArray() : null;
            }
            ret.header = new _TaxPayer.Filds() { ID = InvoiceItem.ID, filds = head };
            //-------------------body
            var body = await invok.Where(w => w.Fild.Title == "B").Select(s => new _TaxPayer.Fild()
            {
                FildID = s.FildID,
                eName = s.Fild.Name,
                fName = s.Fild.Type,
                ModeID = s.FildModeID,
                ModeTitle = s.FildMode.Title,
                Title = s.Fild.Title,
                InputBox = s.Fild.Name == "dis" || s.Fild.Name == "fee" || s.Fild.Name == "am" ? "autofild" : s.Fild.InputBox

            }).ToListAsync();
            foreach (var invoicedetail in InvoiceItem.invoiceDetails)
            {
                foreach (_TaxPayer.Fild item in body)
                {
                    var resval = invoicedetail.GetType().GetProperties().Where(w => w.Name == item.eName).Select(s => s.GetValue(invoicedetail)).FirstOrDefault();
                    item.Value = resval == null ? "" : resval.ToString().Split('.').Length == 2 ? ((decimal)resval).ToString("N0") : resval.ToString();
                    item.DefVals = item.InputBox == "fromdb" ? _codingRepo.Get(w => w.FildID == item.FildID).Select(ss => new _TaxPayer.Coding() { ID = ss.Code, Name = ss.Title }).ToList() : new List<_TaxPayer.Coding>();
                    item.Des = item.ModeID == 3 ? _specialConditionRepo.Get(w => w.FildID == item.FildID).Select(ss => ss.condition).ToArray() : null;
                }
                ret.Bodys.Add(new _TaxPayer.Filds() { ID = invoicedetail.ID, filds = body });
            }
            //-----------------payment
            var pay = await invok.Where(w => w.Fild.Title == "P").Select(s => new _TaxPayer.Fild()
            {
                FildID = s.FildID,
                eName = s.Fild.Name == "pdt" ? "PaymentDateTime" : s.Fild.Name,
                fName = s.Fild.Type,
                ModeID = s.FildModeID,
                ModeTitle = s.FildMode.Title,
                Title = s.Fild.Title,
                InputBox = s.Fild.Name == "pdt" ? "fild" : s.Fild.InputBox

            }).ToListAsync();
            foreach (var invoicepay in InvoiceItem.payments)
            {
                foreach (_TaxPayer.Fild item in pay)
                {
                    var resval = InvoiceItem.payments.GetType().GetProperties().Where(w => w.Name == item.eName).Select(s => s.GetValue(InvoiceItem.payments)).FirstOrDefault();
                    item.Value = resval == null ? "" : resval.ToString().Split('.').Length == 2 ? ((decimal)resval).ToString("N0") : resval.ToString();
                    item.DefVals = item.InputBox == "fromdb" ? _codingRepo.Get(w => w.FildID == item.FildID).Select(ss => new _TaxPayer.Coding() { ID = ss.Code, Name = ss.Title }).ToList() : new List<_TaxPayer.Coding>();
                    item.Des = item.ModeID == 3 ? _specialConditionRepo.Get(w => w.FildID == item.FildID).Select(ss => ss.condition).ToArray() : null;
                }
                ret.Payments.Add(new _TaxPayer.Filds() { ID = invoicepay.ID, filds = pay });
            }

            return ret;
        }
        public async Task<bool> PreparationInvoiceBeforeSending(Shared.DTOs._TaxPayer.Atemplatefield FildItems, Invoice InvoiceItem)
        {
            foreach (var item in FildItems.header.filds.Where(w=>w.InputBox== "fild" || w.InputBox == "fromdb"))
            {
                if (item.eName == "indatim" || item.eName == "Indati2m" || item.eName == "cdcd")
                    item.Value = item.Value.Replace("/", "");
                SetValue(item, ref InvoiceItem);

            }
            if (await _invoiceRepo.UpdateAsync(InvoiceItem))
            {
                foreach (var Bitem in FildItems.Bodys)
                {
                    var invoiceDetItem = InvoiceItem.invoiceDetails.Where(w => w.ID == Bitem.ID).FirstOrDefault();
                    foreach (var item in Bitem.filds.Where(w => w.InputBox == "fild" || w.InputBox == "fromdb"))
                    {
                        if (invoiceDetItem != null)
                            SetValue(item, ref invoiceDetItem);
                    }
                    if (!await _invoiceitemRepo.UpdateAsync(invoiceDetItem))
                        return false;
                }
            }
            else return false;
            return true;

            //foreach (var Pitem in FildItems.Payments)
            //{
            //    var invoicepayItem = InvoiceItem.payments.Where(w => w.ID == Pitem.ID).FirstOrDefault();
            //    foreach (var item in Pitem.filds)
            //    {
            //        if (invoicepayItem != null)
            //        {
            //            SetValue(item, ref invoicepayItem);
            //        }

            //    }
            //    // _repositores.UPDATE(invoicepayItem);
            //}

   

      
        }
        public async Task<PagingDto<SentTaxDto>> GetSentTax(int CompanyID, ItemSerchGetSentTax itemSerchGetSentTax)
        {
            var request = _repoSentTax.Get(w => w.invoice.CompanyID == CompanyID);

            if (itemSerchGetSentTax.ID.HasValue)
                request = request.Where(w => w.ID == itemSerchGetSentTax.ID.Value);

            if (itemSerchGetSentTax.invoiceType.HasValue)
                request = request.Where(w => w.invoice.invoiceType == itemSerchGetSentTax.invoiceType.Value);

            if (itemSerchGetSentTax.SentStatus.HasValue)
                request = request.Where(w => w.SentStatus == itemSerchGetSentTax.SentStatus.Value);

            if (itemSerchGetSentTax.InvoiceID.HasValue)
                request = request.Where(w => w.InvoiceID == itemSerchGetSentTax.InvoiceID.Value);

            return await  request.OrderByDescending(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()

                }).Paging(itemSerchGetSentTax.PageIndex, itemSerchGetSentTax.PageSize);
        }
        private void SetValue<T>(_TaxPayer.Fild fild, ref T obj)
        {
            var resvaltype = obj.GetType().GetProperties().Where(w => w.Name == fild.eName).FirstOrDefault();
            //if (resvaltype != null)
            //{
                if ((resvaltype.GetValue(obj) == null && !string.IsNullOrEmpty(fild.Value))
                 ||
                 resvaltype.GetValue(obj) != null && resvaltype.GetValue(obj).ToString() != fild.Value)
                {
                    if (resvaltype != null && resvaltype.CanWrite)
                    {
                        string _type = ""; object _val = "";

                        if (resvaltype.PropertyType.FullName.Contains("Nullable"))
                            _type = resvaltype.PropertyType.GenericTypeArguments[0].FullName;
                        else
                            _type = resvaltype.PropertyType.FullName;

                        try
                        {
                            _val = Convert.ChangeType(fild.Value, Type.GetType(_type));
                        }
                        catch (Exception ex)
                        {
                            //_contextMongodb.InsertItem(new SysLog()
                            //{
                            //    TraceIdentifierID = _httpContextAccessor.HttpContext.TraceIdentifier,
                            //    Datetime = DateTime.Now.ConvertMiladiToShamsi(),
                            //    Method = $"{_httpContextAccessor.HttpContext.Request.Method}/{this.GetType().FullName}/SetValue",
                            //    Value = ex.Message + '\n' + "_____________" + '\n' + JsonConvert.SerializeObject(fild),
                            //    Route = _httpContextAccessor.HttpContext.Request.Path,
                            //    Type = "catch"
                            //});

                            switch (_type)
                            {
                                case "string":
                                    _val = Convert.ChangeType("", Type.GetType(_type));
                                    break;

                                case "bool":
                                    if (fild.Value == "1" || fild.Value == "true") _val = Convert.ChangeType(true, Type.GetType(_type));
                                    else _val = Convert.ChangeType(false, Type.GetType(_type));
                                    break;

                                default:
                                    _val = Convert.ChangeType("0", Type.GetType(_type));
                                    break;
                            }
                        }

                        resvaltype.SetValue(obj, _val);
                    }
                }

           // }

        }


    }
}
