using Shared.DTOs;
using Back.Data.Models;
using Back.Services;
using Back.Validations;
using FluentValidation;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Shared.DTOs;
using System.Security.Cryptography;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;
using Shared.DTOs.Serch;
using Back.Common;

namespace Back.Controllers
{
    [Route("api/[controller]")]
    [Authorize]
    [ApiController]
    public class TicketController : ControllerBase
    {
        private readonly MobileValidation _mobilevalidation;
        private readonly servTicket _servTicket;
        private readonly ServValidatinMsg _servValidatinMsg;
        private readonly servSendMsg _servSendMsg;
        private readonly servCompany _servCompany;
        private readonly servUser _servUser;
        public TicketController(MobileValidation mobilevalidation, servTicket servTicket
                                , ServValidatinMsg servValidatinMsg, servSendMsg servSendMsg
                                , servCompany servCompany, servUser servUser)
        {
            _mobilevalidation = mobilevalidation;
            _servTicket = servTicket;
            _servValidatinMsg = servValidatinMsg;
            _servSendMsg = servSendMsg;
            _servUser = servUser;
            _servCompany = servCompany;
        }
        [HttpPost("GetAll")]
        public async Task<ActionResult<PagingDto<TicketDTO>>> GetAll(ItemSerchGetTicket itemSerch)
        {
            var claim = HttpContext.User.Claims.First(c => c.Type == "UserID");
            var UserID = claim.Value;
            var user = await _servUser.GetUserByUserID(Convert.ToInt32(UserID));

            return Ok(await _servTicket.GetAll(user.RolUsers.First().CompanyID, itemSerch));
        }
        [HttpGet("GetSubTicket/{TicketID}")]
        public async Task<ActionResult<ICollection<SubTicketDTO>>> GetSubTicket(int TicketID)
        {
            var claim = HttpContext.User.Claims.First(c => c.Type == "UserID");
            var UserID = claim.Value;
            var user = await _servUser.GetUserByUserID(Convert.ToInt32(UserID));

            return Ok(await _servTicket.GetSubTicket(user.RolUsers.First().CompanyID, TicketID));
        }
        [HttpPost("NewTicket")]
        public async Task<ActionResult<int>> NewTicket(CTicketDto item)
        {
            var claim = HttpContext.User.Claims.First(c => c.Type == "UserID");
            var UserID = claim.Value;
            var user = await _servUser.GetUserByUserID(Convert.ToInt32(UserID));

            if (string.IsNullOrEmpty(item.CompanyID))
            {
                item.CompanyID = user.RolUsers.First().CompanyID.ToString();
            }
            else
            {
               if(!await _servCompany.ExsistCompanyByComoanyIDandUserID(Convert.ToInt32(item.CompanyID), Convert.ToInt32(UserID)))
                    item.CompanyID = user.RolUsers.First().CompanyID.ToString();
            }
            var res = await _servTicket.NewTicket(item);
            return Ok(res != null);
        }
        [HttpPost("AddSubicket")]
        public async Task<ActionResult<int>> AddSubicket(AddSubTicket item)
        {
            var claim = HttpContext.User.Claims.First(c => c.Type == "UserID");
            var UserID = claim.Value;
            var user = await _servUser.GetUserByUserID(Convert.ToInt32(UserID));
            var Ticket = await _servTicket.GetTicketorgbyTicketID(user.RolUsers.First().CompanyID,item.TicketID);
            if (Ticket==null)
                return NotFound(new List<string>() { "تیکت یافت نشد" });
            
            if (!string.IsNullOrEmpty(Ticket.EndDate)) return BadRequest(new List<string>() { "این تیکت بسته شده" });

            var subTicket = await _servTicket.AddSubTicket(item);
            Ticket.Status = StatusTicket.Awaitingreview;
           await _servTicket.UpdateTicket(Ticket);
          return Ok(subTicket);
        }
        [HttpPut("CancelTicket/{TicketID}")]
        public async Task<ActionResult<bool>> CancelTicket(int TicketID)
        {
            var claim = HttpContext.User.Claims.First(c => c.Type == "UserID");
            var UserID = claim.Value;
            var user = await _servUser.GetUserByUserID(Convert.ToInt32(UserID));

            var Ticket = await _servTicket.GetTicketorgbyTicketID(user.RolUsers.First().CompanyID,TicketID);
            if (Ticket == null)
                return NotFound(new List<string>() { "تیکت یافت نشد" });
          //  if (!string.IsNullOrEmpty(Ticket.EndDate)) return BadRequest("این تیکت قبلا بسته شده");
            if (Ticket.Status == StatusTicket.Awaitingreview || Ticket.Status == StatusTicket.Read_Checking
        || Ticket.Status == StatusTicket.hasbeenanswered)
            {
                Ticket.Status = StatusTicket.optout;
                Ticket.EndDate = DateTime.Now.ConvertMiladiToShamsi();
                Ticket.EndTime = DateTime.Now.ToString("hh:mm tt");
                return Ok(await _servTicket.UpdateTicket(Ticket));
            }
            return Ok();
        }
        [HttpPost("NewTicketNoAuthentication")]
        [AllowAnonymous]
        public async Task<ActionResult<int>> NewTicketNoAuthentication(CTicketNoAuthenticationDto item)
        {
            var resultValidationmodel = await _mobilevalidation.ValidateAsync(Tuple.Create(item.Mobile, ActionMobileValidation.No));
            if (!resultValidationmodel.IsValid)
                return BadRequest(resultValidationmodel.Errors.Select(s => s.ErrorMessage).ToList());

            var pid = await _servTicket.NewPepole(item.FullName, item.Mobile);
            item.CompanyID = pid.Value.ToString();
            var Ticket = await _servTicket.NewTicket(item, StatusTicket.unknownPerson);

            var modelvc = await _servValidatinMsg.GenerateCode(new VerificationCode
            {
                prm = Ticket.ID.ToString(),
                val = item.Mobile,
                Type = "NewTicketNoAuthentication"
            });
            _servSendMsg.toContinue(modelvc.Code.ToString(),item.Mobile, "ثبت نظر");
            return Ticket == null ? BadRequest() : Ok(modelvc.ID);
        }
    }
}
