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

namespace Back.Services
{
    public class ServCOD
    {
        private readonly IAsyncRepository<CODItem> _CODRepo;
        private readonly IAsyncRepository<CODUnit> _UnitRepo;
        private readonly CheckPermission _checkPermission;
        public ServCOD(IAsyncRepository<CODItem> CODRepo, IAsyncRepository<CODUnit> unitRepo
                        , CheckPermission checkPermission)
        {
            _CODRepo = CODRepo;
            _UnitRepo = unitRepo;
            _checkPermission = checkPermission;
        }
        public async Task<PagingDto<RCOD>?> GetCODs(int CompanyID, ItemSerchGetCOD itemSerch)
        {

            #region AdvancedSearch
            var invok = _CODRepo
                .Get(w => w.CompanyID == CompanyID && !w.IsDeleted);
            //foreach (InputObj item in inputObjs)
            //    invok = invok.Where(ExMethod.GetFunc<CODItem>(item.Param, item.Value));


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

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

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

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

            #endregion
            //-----------------------
            return await invok.Select(s => new RCOD()
            {
                ID = s.ID,
                TaxID = s.ItemTaxID,
                Title = s.Title,
                Unit = s.CODUnit.Title,
                UnitID=s.UnitID,
                TaxRate = s.TaxRate
            })
                .Paging(itemSerch.PageIndex, itemSerch.PageSize);
        }
        public async Task<List<CODIdName<int>>?> GetCODs(int CompanyID)
        {

            #region AdvancedSearch
            var invok = _CODRepo
                .Get(w => w.CompanyID == CompanyID && !w.IsDeleted);

            #endregion
            //-----------------------
            return await invok.Select(s => new CODIdName<int>()
            {
                ID = s.ID,
                Title = s.Title,
                Tax=s.TaxRate
            })
                .ToListAsync();
        }
        public async Task<List<IdName<int>>> GetUnits()
        {
            return await _UnitRepo.GetAll().Select(s => new IdName<int> { ID = s.ID, Title = s.Title }).ToListAsync();
        }
        public async Task<CODItem?> GetCodByCodID(int CodID, int CompanyID)
        {
            return await _CODRepo
                .Get(w => w.ID == CodID && w.CompanyID == CompanyID && !w.IsDeleted)
                .Include(inc=>inc.CODUnit).FirstOrDefaultAsync();
        }
        public async Task<bool> ExistCodByCompanyID(int CodID, int CompanyID)
        {
            return await _CODRepo
                .Get(w => w.ID == CodID && w.CompanyID == CompanyID && !w.IsDeleted).AnyAsync();
        }
        public async Task<bool> ExistUnit(int UnitID)
        {
            return await _UnitRepo
                .Get(w => w.ID == UnitID ).AnyAsync();
        }
        public async Task<bool> AddOrUpdateCod(CODItem 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, 4, "-1"))
                        return await _CODRepo.AddBoolResultAsync(item);
                        
                    return false;
                    
                    
                }
                else
                {
                    return await _CODRepo.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> DeleteCod(CODItem item)
        {

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

            }
        }
    }
}
