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

namespace Back.Services
{
    public class servCustomer
    {
        private readonly IAsyncRepository<Customer> _repoCus;
        private readonly CheckPermission _checkPermission;
        public servCustomer(IAsyncRepository<Customer> repoCus, CheckPermission checkPermission)
        {
           _repoCus = repoCus;
            _checkPermission = checkPermission;

        }
        public async Task<PagingDto<RCustomer>?> GetCustomers(int CompanyID, ItemSerchGetCustomer itemSerch)
        {
            #region AdvancedSearch
            var invok = _repoCus
                .Get(w => w.CompanyID == CompanyID && !w.IsDeleted);
            //foreach (InputObj item in inputObjs)
            //    invok = invok.Where(ExMethod.GetFunc<Customer>(item.Param, item.Value));
            if (!string.IsNullOrEmpty(itemSerch.ZipCode))
                invok = invok.Where(w=>w.ZipCode.Contains(itemSerch.ZipCode));
            
            if (!string.IsNullOrEmpty(itemSerch.Phone))
                invok = invok.Where(w => w.Phone.Contains(itemSerch.Phone));

           

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

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

            if (!string.IsNullOrEmpty(itemSerch.EconomicCode))
                invok = invok.Where(w => w.EconomicCode.Contains(itemSerch.EconomicCode) || w.MeliCode.Contains(itemSerch.EconomicCode));
            #endregion
            //-----------------------
            return await invok.Select(s=>new RCustomer()
                {
                
                Address = s.Address,
                CustomerTypeTitle = s.CustomerType.GetEnumDisplayName(),
                    EconomicCode = s.EconomicCode,
                Email = s.Email,
                FullName = s.FullName,
                    ID = s.ID,
                Info = s.Info,
                Phone =s.Phone,
                BranchID = s.BranchID,
                MeliCode = s.MeliCode,
                ZipCode = s.ZipCode,
                PassportNumber = s.PassportNumber,
                CustomerType= s.CustomerType
                //  CompanyID=s.CompanyID
            }).OrderByDescending(o=>o.ID)
                .Paging(itemSerch.PageIndex, itemSerch.PageSize); 
        }
        public async Task<List<ForCustomerSearch>?> GetCustomers(int CompanyID)
        {
            var invok = _repoCus
                .Get(w => w.CompanyID == CompanyID && !w.IsDeleted);
           
            //-----------------------
            return await invok.Select(s => new ForCustomerSearch()
            {
                CustomerName=s.FullName,
                ID = s.ID
               
            }).OrderByDescending(o => o.ID)
                .ToListAsync();
        }
        public async Task<Customer?> GetCustomerByCustomerID(int CustomerID, int CompanyID)
        {
            return await _repoCus
                .Get(w => w.ID == CustomerID && w.CompanyID == CompanyID && !w.IsDeleted).FirstOrDefaultAsync();
        }
        //public async Task<Customer> GetCustomerByCustomerID(int CustomerID)
        //{
        //    return await _repositores.GET<Customer>()
        //        .Where(w => w.ID == CustomerID && !w.IsDeleted).FirstOrDefaultAsync();
        //}
        public async Task<bool> ExistCustomerByCustomerID(int CustomerID, int CompanyID)
        {
            return await _repoCus
                .Get(w => w.ID == CustomerID && w.CompanyID == CompanyID && !w.IsDeleted).AnyAsync();
        }
        //public async Task<CUCustomer> GetCustomerByCustomerIDByDTO(int CustomerID)
        //{
        //    return await _repositores.GET<Customer>()
        //        .Where(w => w.ID == CustomerID && !w.IsDeleted)
        //        .Select(s => new CUCustomer()
        //        {
        //            Address = s.Address,
        //            CustomerType = s.CustomerType,
        //            EconomicCode = s.EconomicCode,
        //            Email = s.Email,
        //            FullName = s.FullName,
        //            ID = s.ID,
        //            Info = s.Info,
        //            Phone = s.Phone,
        //            BranchID = s.BranchID,
        //            MeliCode = s.MeliCode,
        //            ZipCode = s.ZipCode,
        //            PassportNumber = s.PassportNumber,
        //            //CompanyID = s.CompanyID
        //        })
        //        .FirstOrDefaultAsync();
        //}
        public async Task<bool> AddOrUpdateCustomer(Customer item)
        {
            try
            {
                //SysLog log = new SysLog()
                //{
                //    TraceIdentifierID = _httpContextAccessor.HttpContext.TraceIdentifier,
                //    Datetime = DateTime.Now.ConvertMiladiToShamsi(),
                //    Method = $"{_httpContextAccessor.HttpContext.Request.Method}/{this.GetType().FullName}/AddORUpdateCustomer",
                //    Value = "*" + JsonConvert.SerializeObject(item),
                //    Route = _httpContextAccessor.HttpContext.Request.Path,
                //    Type = "User"
                //};
                //_contextMongodb.InsertItem(log);

                if (item.ID == null || item.ID <= 0)
                {
                    if(await _checkPermission.ExtensionofAccess(item.CompanyID, 5, "-1"))
                  return await _repoCus.AddBoolResultAsync(item);
                   
                    return false;
                }
                else
                {
                    return await _repoCus.UpdateAsync(item);
                }
            }
            catch (Exception ex)
            {
                //SysLog log = new SysLog()
                //{
                //    TraceIdentifierID = _httpContextAccessor.HttpContext.TraceIdentifier,
                //    Datetime = DateTime.Now.ConvertMiladiToShamsi(),
                //    Method = $"{_httpContextAccessor.HttpContext.Request.Method}/{this.GetType().FullName}/AddORUpdateCustomer",
                //    Value = ex.Message,
                //    Route = _httpContextAccessor.HttpContext.Request.Path,
                //    Type = "catch"
                //};
                //_contextMongodb.InsertItem(log);
                return false;
            }

        }
        public async Task<bool> DeleteCustomer(Customer item)
        {

            try
            {
                item.IsDeleted = true;
              return await _repoCus.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;

            }
        }


    }
}
