using Dapper;
using Lada.Framework.Data.Domains.Cms;
using Lada.Framework.Data.Domains.Hr;
using Lada.Framework.Data.Repositories;
using Lada.Framework.Infrastructures.Helpers;
using ladaexpress.vn.Infrastructures.DTO;
using ladaexpress.vn.Infrastructures.DTO.Models.Hr;
using Microsoft.EntityFrameworkCore;
using System.Data;

namespace ladaexpress.vn.Infrastructures.Services
{
    public interface IJobService
    {
        public Task<JobListModel> PrepareJobListModel();
        Task<JobDetailModel> PrepareJobDetailModel(int id);
    }

    public class JobService : IJobService
    {
        private readonly IRepository<JobPost> _jobPostRepository;
        private readonly IDbConnection _dbConnection;
        private readonly IRepository<UrlRecord> _urlRecordRepository;
        public JobService(IRepository<JobPost> jobPostRepository, IDbConnection dbConnection,
            IRepository<UrlRecord> urlRecordRepository)
        {
            _jobPostRepository = jobPostRepository;
            _dbConnection = dbConnection;
            _urlRecordRepository = urlRecordRepository;
        }

        public async Task<JobListModel> PrepareJobListModel()
        {
            var model = new JobListModel();
            var currentTime = DateTimeHelper.CurrentTime();
            var newTime = currentTime.AddDays(-3);//Những bài viết có ngày xuất bản 3 ngày trở về đây được coi là bài viết mới


            model.JobPosts = await PrepareJobPosts();
            model.TotalJob = await PrepareTotalJobs();
            return model;

        }

        private async Task<List<JobPostItem>> PrepareJobPosts()
        {
            var posts = new List<JobPostItem>();
            try
            {
                posts = (await _dbConnection.QueryAsync<JobPostItem>("JobPostIndex_GetJobs", commandType: CommandType.StoredProcedure)).ToList();
            }
            catch (Exception)
            {
            }
            return posts;
        }

        private async Task<int> PrepareTotalJobs()
        {



            var parameters = new DynamicParameters();
            parameters.Add("TotalRecords", dbType: DbType.Int32, direction: ParameterDirection.Output);

            await _dbConnection.ExecuteAsync("JobPostIndex_GetTotalJobs", parameters, commandType: CommandType.StoredProcedure);

            return parameters.Get<int>("TotalRecords");

        }


        public async Task<JobDetailModel> PrepareJobDetailModel(int id)
        {
            var model = new JobDetailModel();
            var currentTime = DateTimeHelper.CurrentTime();
            var post = await _jobPostRepository.Query().Include(p => p.UrlRecord).Include(j => j.JobPostTags!).ThenInclude(jpt => jpt.Tag!).ThenInclude(t => t.UrlRecord).FirstOrDefaultAsync(p => p.Id == id);

            if (post != null && post.Id > 0)
            {
                var postStartDate = post.StartDate.HasValue ? post.StartDate.Value.Date : currentTime.AddDays(1000);
                var postEndDate = post.EndDate.HasValue ? post.EndDate.Value.Date : currentTime.AddDays(-1000);

                // Luôn trả về dữ liệu để có thể tạo SEO, bất kể trạng thái
                model = post.ToDetailModel();
                model.Slug = post.UrlRecord?.Slug;

                // Kiểm tra xem tin có hiệu lực không (để hiển thị thông báo nếu cần)
                var isActive = postStartDate <= currentTime && postEndDate >= currentTime && post.JobStatus == JobStatus.Opening;
                if (post.JobPostTags != null && post.JobPostTags.Any())
                {
                    foreach (var jobPostTag in post.JobPostTags)
                    {
                        if (jobPostTag.Tag != null && jobPostTag.Tag.Id > 0)
                        {
                            var tagSlug = "";
                            if (jobPostTag.Tag.UrlRecord != null)
                            {
                                tagSlug = jobPostTag.Tag.UrlRecord.Slug;
                            }
                            model.Tags.Add(new DTO.Models.Tags.TagItem() { Id = jobPostTag.Tag.Id, Name = jobPostTag.Tag.Name, Slug = tagSlug });
                        }
                    }
                }
                //if (model.Tags!=null && model.Tags.Any())
                //{
                //    var tagIds = model.Tags.Select(t => t.Id).ToList();
                //    var tagUrlRecords = await _urlRecordRepository.Query().Where(u => u.TagId.HasValue && tagIds.Contains(u.TagId.Value)).ToListAsync();
                //    if (tagUrlRecords.Any())
                //    {
                //        foreach (var item in model.Tags)
                //        {
                //            var urlRecord = tagUrlRecords.FirstOrDefault(u => u.TagId == item.Id);
                //            if (urlRecord != null && urlRecord.Id > 0)
                //            {
                //                item.Slug = urlRecord.Slug;
                //            }
                //        }
                //    }
                //}
            }

            return model;
        }
    }
}
