using Back.Common;
using Back.Data.Models;
using Back.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Shared.DTOs;
using Shared.DTOs.Serch;
using Shared.Enums;

namespace Back.Controllers
{

    [Route("api/[controller]")]
    [Authorize]
    [ApiController]
    public class OrdersController : ControllerBase
    {
        private readonly ServOrders _servOrders;
        private readonly ServPromotion _servPromotion;
        private readonly ServPricing _servPricing;
        private readonly servUser _servUser;
        private readonly servCompany _servCompany;
        private readonly ServWalt _servWalt;
        public OrdersController(ServOrders servOrders, ServPromotion servPromotion, ServPricing servPricing, servUser servUser, servCompany servCompany, ServWalt servWalt)
        {
            _servOrders = servOrders;
            _servPricing = servPricing;
            _servPromotion = servPromotion;
            _servUser = servUser;
            _servCompany = servCompany;
           _servWalt = servWalt;
        }
        [HttpGet("GetAllPromotion")]
        [AllowAnonymous]
        public async Task<ActionResult<List<PromotionDto>>> GetAllPromotion() =>Ok(await _servPromotion.GetAll());
        
        [HttpGet("GetAllPricing")]
        [AllowAnonymous]
        public async Task<ActionResult<List<PricingDto>>> GetAllPricing() => Ok(await _servPricing.GetPricing());
        [HttpPost("GetAllOrder")]
        public async Task<ActionResult<PagingDto< OrderDto>>> GetAllOrder(ItemSerachOrder itemSerach)
        {
            var claim = HttpContext.User.Claims.First(c => c.Type == "UserID");
            var UserID = claim.Value;
            var user = await _servUser.GetUserByUserID(Convert.ToInt32(UserID));
            int CompanyID = user.RolUsers.First().CompanyID;

            return Ok(await _servOrders.GetOrdersByCompanyID(CompanyID,itemSerach));
        }
        [HttpGet("GetOrderDetails/{OrderID}")]
        public async Task<ActionResult<List<OrderItemDto>>> GetOrderDetails(int OrderID)
        {
            var claim = HttpContext.User.Claims.First(c => c.Type == "UserID");
            var UserID = claim.Value;
            var user = await _servUser.GetUserByUserID(Convert.ToInt32(UserID));
            int CompanyID = user.RolUsers.First().CompanyID;

            return Ok(await _servOrders.GetOrderItems( OrderID, CompanyID));
        }
        [HttpDelete("CancelOrder/{OrderID}")]
        public async Task<ActionResult<List<OrderItemDto>>> CancelOrder(int OrderID)
        {
            var claim = HttpContext.User.Claims.First(c => c.Type == "UserID");
            var UserID = claim.Value;
            var user = await _servUser.GetUserByUserID(Convert.ToInt32(UserID));
            int CompanyID = user.RolUsers.First().CompanyID;

            var order =await _servOrders.GetOrder(OrderID, CompanyID);
            if (order==null)
                return NotFound();

            if (order.Status==StatusOrder.Create)
            {
                order.Status = StatusOrder.Cancel;
                order.ApprovalDate = DateTime.Now.ConvertMiladiToShamsi();
                return Ok(await _servOrders.UpdateOrder(order));
            }
            else return BadRequest(new List<string> { "در این وضعیت امکان ابطال نیست" });
        }
        [HttpPost("AddOrder")]
        public async Task<ActionResult<OrderDto>> AddOrder(PromotionDto item)
        {
            var claim = HttpContext.User.Claims.First(c => c.Type == "UserID");
            var UserID = claim.Value;
            var user = await _servUser.GetUserByUserID(Convert.ToInt32(UserID));
            int CompanyID = user.RolUsers.First().CompanyID;

            Order order = new Order();
             order = new Order()
            {
                CompanyID = CompanyID,
                ApprovalDate = DateTime.Now.ConvertMiladiToShamsi(),
                DateCreate = DateTime.Now.ConvertMiladiToShamsi(),
                Status = StatusOrder.Create,
                UserID = Convert.ToInt32(UserID)
            };
            if (item.ID<0)
            {
                var pricing = await _servPricing.GetPricing();
                if (pricing == null)
                    return NotFound();

                //permission
                order.OrderItems = item.promotionDetails.Where(w=>w.CreditAmount>0).Select(s => new OrderItem
                {
                    APrice = pricing.Where(w => w.PermissionID == s.PermissionID).Select(c => c.Price).FirstOrDefault(),
                    PermissionID = s.PermissionID,
                    Discount=0,
                    Tax=0,
                    CreditAmount=s.CreditAmount
                }).ToList();
            }
            else
            {
                //promotion
               var pro=await _servPromotion.GetByPromotionID(item.ID);
                if (pro == null)
                    return NotFound();

                order.OrderItems = pro.PromotionDetails.Select(s => new OrderItem
                {
                    APrice =s.APrice,
                    PermissionID = s.PermissionID,
                    PromotionID=s.PromotionID,
                    Discount = 0,
                    Tax = 0,
                    CreditAmount = s.CreditAmount
                }).ToList();


               
            }

          var result= await _servOrders.AddOrder(order);
            if (result !=null)
                return Ok(new OrderDto
                {
                    ApprovalDate = result.ApprovalDate.ShamciToFormatShamci(),
                    DateCreate = result.DateCreate.ShamciToFormatShamci(),
                    ID = result.ID,
                    PreDiscount = result.PreDiscount,
                    Status = result.Status,
                    TDiscount = result.TDiscount,
                    TPrice = result.TPrice,
                    TTax = result.TPrice,
                    lstDiscount = result.lstDiscount,
                });
            else return BadRequest(new List<string> { "خطا در ثبت سفارش" });

        }
        [HttpGet("SubmitOrderBywallet/{OrderID}")]
        public async Task<ActionResult<OrderDto>> SubmitOrder(int OrderID)
        {
            var claim = HttpContext.User.Claims.First(c => c.Type == "UserID");
            var UserID = claim.Value;
            var user = await _servUser.GetUserByUserID(Convert.ToInt32(UserID));
            var Company = user.RolUsers.First().Company;
            int CompanyID = Company.ID;
           var order =await _servOrders.GetOrder(OrderID, CompanyID);

            if (order.Status==StatusOrder.Create)
            {
                if (Company.Credit >= order.TPrice)
                {
                    Company.Credit -= order.TPrice;
                   var comUpdate=await _servCompany.AddORUpdateCompany(Company);
                    if (comUpdate != null)
                    {
                        if (await _servWalt.AddDocument(new CreditDocuments
                        {
                            CompanyID = CompanyID,
                            Date = DateTime.Now.ConvertMiladiToShamsi(),
                            Title = $"بابت سفارش {order.ID}",
                            type = CreditDocumentType.Decrease,
                            Value = order.TPrice
                        }))
                        {
                            if (await _servOrders.SubmitOrder(order,CompanyID))
                                return Ok();
                            
                            else
                                return BadRequest(new List<string> { "خطا در بروزرسانی سرویس ها" });
                        }
                            
                        else
                            return BadRequest(new List<string> { "خطا در بروزرسانی سند سفارش" });
                    }
                    else
                        return BadRequest(new List<string> { "خطا در بروزرسانی شرکت" });
                    
                }
                else
                    return BadRequest(new List<string> { "اعتبار کیف پول کافی نمی باشد" });
            }
            else
                return BadRequest(new List<string> { "سفارش در این حالت امکان پرداخت ندارد" });
            
        }
        [HttpPost("GetCreditDocuments")]
        public async Task<ActionResult<PagingDto<CreditDocumentDto>>> GetCreditDocuments(GridDataProviderRequestDto value)
        {
            var claim = HttpContext.User.Claims.First(c => c.Type == "UserID");
            var UserID = claim.Value;
            var user = await _servUser.GetUserByUserID(Convert.ToInt32(UserID));
            var Company = user.RolUsers.First().Company;
            int CompanyID = Company.ID;
            return Ok(await _servWalt.GetDocuments(value,CompanyID));
        }
    }
}
