using System;
using Hims.Shared.UserModels.Common;
using Hims.Shared.UserModels.Receipt;

namespace Hims.Api.Controllers
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;

    using Domain.Services;
    using Hims.Api.Models;
    using Hims.Shared.EntityModels;
    using Hims.Shared.Library.Enums;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using Utilities;

    /// <inheritdoc />
    [Authorize]
    [Route("api/receipt")]
    public class ReceiptController : BaseController
    {
        /// <summary>
        /// The service
        /// </summary>
        private readonly IReceiptService service;
        /// <summary>
        /// The auditlog services.
        /// </summary>
        private readonly IAuditLogService auditLogServices;

        /// <summary>
        /// The pharmacy request service.
        /// </summary>
        private readonly IPharmacyRequestService pharmacyService;

        /// <inheritdoc />
        public ReceiptController(IReceiptService service, IAuditLogService auditLogServices,
            IPharmacyRequestService pharmacyService)
        {
            this.service = service;
            this.auditLogServices = auditLogServices;
            this.pharmacyService = pharmacyService;
        }

        /// <summary>
        /// The add icons async.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Route("fetch-receipt-types")]
        public async Task<ActionResult> FetchReceiptTypesAsync()
        {
            try
            {
                var response = await this.service.FetchReceiptTypesAsync().ConfigureAwait(false);
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Success,
                    Data = response
                });
            }
            catch (Exception ex)
            {
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Error,
                    Message = ex.Message
                });
            }
        }

        /// <summary>
        /// The add icons async.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Route("fetch")]
        public async Task<ActionResult> FetchAsync([FromBody] FilterModel model)
        {
            try
            {
                model.AdmissionId = Convert.ToInt32(model.Id);
                var response = await this.service.FetchAsync(model).ConfigureAwait(false);
                var subRecords = new List<SubViewModel>();
                var costViewModel = new CostViewModel();

                if (model.ReceiptId != null && response.First().ReceiptAreaTypeId != null)
                {
                    switch (response.First().ReceiptAreaTypeId)
                    {
                        case Domain.Entities.Enums.ReceiptAreaType.Pharmacy:
                            var indents = await this.pharmacyService.GetIssuedPharmacyIndentDetailAltAsync(response.First().ReceiptAreaMainId ?? 0);
                            foreach (var x in indents)
                            {
                                subRecords.Add(new SubViewModel
                                {
                                    Cost = x.Mrp,
                                    DiscountAmount = x.DiscountAmount ?? 0,
                                    DiscountPercentage = x.DiscountPercentage ?? 0,
                                    GstAmount = x.GstAmount,
                                    GstPercentage = x.GstPercentage,
                                    Name = x.ProductName,
                                    NetAmount = x.NetAmount,
                                    TotalAmount = x.Total,
                                    Unit = x.Quantity
                                });
                            }

                            if (indents.Any())
                            {
                                costViewModel = new CostViewModel
                                {
                                    Total = indents.First().OverallTotal,
                                    Discount = indents.First().OverallDiscount ?? 0,
                                    Gst = indents.First().OverallGst,
                                    NetAmount = indents.First().OverallNetAmount
                                };
                            }
                            break;
                    }
                }

                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Success,
                    Data = new GlobalViewModel
                    {
                        Records = response,
                        SubRecords = subRecords,
                        CostViewModel = costViewModel
                    }
                });
            }
            catch (Exception ex)
            {
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Error,
                    Message = ex.Message
                });
            }
        }

        /// <summary>
        /// The add icons async.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Route("cancel")]
        public async Task<ActionResult> CancelAsync([FromBody] IdModel model, [FromHeader] LocationHeader header)
        {
            try
            {
                var response = await this.service.CancelAsync(model.Id).ConfigureAwait(false);

                if (response > 0)
                {
                    try
                    {
                        var auditLogModel = new AuditLogModel
                        {
                            AccountId = model.LoginAccountId,
                            LogTypeId = (int)LogTypes.Services,
                            LogFrom = (short)model.LoginRoleId,
                            LogDate = DateTime.UtcNow.AddMinutes(330),
                            LogDescription = $@"Receipt No.: <b>RN-{model.Id.ToString().PadLeft(6, '0')}</b> was <b>Cancelled</b> ",
                            LocationId = Convert.ToInt32(header.LocationId)
                        };
                        await this.auditLogServices.LogAsync(auditLogModel);

                    }
                    catch (Exception e)
                    {
                        //for auditlogs
                    }
                }
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Success,
                    Data = response
                });
            }
            catch (Exception ex)
            {
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Error,
                    Message = ex.Message
                });
            }
        }

        /// <summary>
        /// The add icons async.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Route("insert")]
        [Consumes("multipart/form-data")]
        public async Task<ActionResult> InsertAsync([FromForm] InsertModel model, [FromHeader] LocationHeader header)
        {
            try
            {
                var locationId = int.Parse(header.LocationId);
                var id = await this.AddAsyncHelper(model, locationId);
                return this.Success(new GenericResponse
                {
                    Status = GenericStatus.Success,
                    Data = id
                });
            }
            catch (Exception ex)
            {
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Error,
                    Message = ex.Message
                });
            }
        }

        /// <summary>
        /// Adds the asynchronous helper.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="locationId"></param>
        /// <returns></returns>
        [NonAction]
        public async Task<int> AddAsyncHelper(InsertModel model, int locationId)
        {
            model.Active = true;
            model.AdmissionId = Convert.ToInt32(model.Id);
            model.CreatedDate = DateTime.Now;
            model.LocationId = locationId;
            var response = await this.service.InsertAsync(model).ConfigureAwait(false);

            if (response > 0)
            {
                model.ReceiptId = response;
                var result = await this.service.FetchReceiptDetailsAsync(model);
                var auditLogModel = new AuditLogModel
                {
                    AccountId = model.CreatedBy,
                    LogTypeId = (int)LogTypes.Services,
                    LogFrom = (short)model.RoleId,
                    LogDate = DateTime.UtcNow.AddMinutes(330),
                    LogDescription = $@"{model.CreatedByName} <b>Generated Receipts</b>  with <br>Receipt No.: <b>RN-{result.ReceiptId.ToString().PadLeft(6, '0')}</b> for the Patient: <b>{result.FullName}</b>",
                    LocationId = locationId
                };
                await this.auditLogServices.LogAsync(auditLogModel);
            }
            return response;
        }
    }
}

