using Atomx.Admin.Client.Models;
using Atomx.Admin.Client.Validators;
using Atomx.Admin.Services;
using Atomx.Common.Entities;
using Atomx.Common.Models;
using Atomx.Data;
using Atomx.Data.CacheServices;
using Atomx.Data.Services;
using Atomx.Utils.Models;
using MapsterMapper;
using Microsoft.AspNetCore.Mvc;

namespace Atomx.Admin.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class LocaleResourceController : ControllerBase
    {
        private readonly ILogger<LocaleResourceController> _logger;
        private readonly DataContext _dbContext;
        private readonly IIdCreatorService _idCreator;
        private readonly IdentityService _identityService;
        private readonly IMapper _mapper;
        private readonly JwtSetting _jwtSettings;
        private readonly ICacheService _cacheService;
        private readonly LocalizationFileService _localizationFileService;


        /// <summary>
        /// 
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="idCreator"></param>
        /// <param name="identityService"></param>
        /// <param name="dbContext"></param>
        /// <param name="mapper"></param>
        /// <param name="jwtSettings"></param>
        /// <param name="cacheService"></param>
        public LocaleResourceController(ILogger<LocaleResourceController> logger, IIdCreatorService idCreator, IdentityService identityService, DataContext dbContext, IMapper mapper, JwtSetting jwtSettings, ICacheService cacheService, LocalizationFileService localizationFileService)
        {
            _logger = logger;
            _idCreator = idCreator;
            _identityService = identityService;
            _dbContext = dbContext;
            _mapper = mapper;
            _jwtSettings = jwtSettings;
            _cacheService = cacheService;
            _localizationFileService = localizationFileService;
        }

        /// <summary>
        /// 分页获取多语言资源列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="languageId"></param>
        /// <param name="name"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        [HttpGet("list")]
        public IActionResult GetList(int page, int languageId, string? name, int size = 20)
        {
            if (page < 1)
            {
                page = 1;
            }
            var result = new Result<PagingList<LocaleResource>>();
            var list = new PagingList<LocaleResource>() { Index = page, Size = size };
            var query = from p in _dbContext.LocaleResources
                        where p.LanguageId == languageId
                        select p;

            if (!string.IsNullOrEmpty(name))
            {
                query = from p in query
                        where p.Name.Contains(name)
                        select p;
            }

            list.Count = query.Count();
            list.Items = query.OrderByDescending(p => p.Name).Skip((page - 1) * size).Take(size).ToList();

            result.Data = list;

            return new JsonResult(result);
        }

        /// <summary>
        /// 通过ID获取多语言资源
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Get(long id)
        {
            var result = new Result<LocaleResourceModel>();
            var data = _dbContext.LocaleResources.SingleOrDefault(p => p.Id == id);
            if (data == null)
            {
                result.Message = "数据不存在，请更换！";
                result.Success = false;
                return new JsonResult(result);
            }

            var model = _mapper.Map<LocaleResourceModel>(data);
            var language = await _cacheService.GetLanguageById(model.LanguageId);
            model.Culture = language?.Culture ?? string.Empty;

            result.Data = model;
            return new JsonResult(result);
        }


        /// <summary>
        /// 新增保存多语言资源
        /// </summary>
        /// <param name="localeResource"></param>
        /// <returns></returns>
        [HttpPost("save")]
        public async Task<IActionResult> SaveAsync(LocaleResourceModel model)
        {
            var result = new ApiResult<bool>();
            var validator = new LocaleResourceModelValidator();
            var validation = validator.Validate(model);
            if (!validation.IsValid)
            {
                result = result.IsFail(ModelState.Values.First().Errors[0].ErrorMessage);
                return new JsonResult(result);
            }
            if (model.IsEdit)
            {
                var data = _dbContext.LocaleResources.SingleOrDefault(p => p.Id == model.Id);
                if (data == null)
                {
                    result.Message = "数据不存在，请更换！";
                    result.Success = false;
                    return new JsonResult(result);
                }

                data = _mapper.Map(model, data);
                data.UpdateTime = DateTime.UtcNow;
                _dbContext.SaveChanges();
                await _cacheService.SetLocaleResources(data);
            }
            else
            {
                var data = _mapper.Map<LocaleResource>(model);
                data.UpdateTime = DateTime.UtcNow;
                _dbContext.LocaleResources.Add(data);
                _dbContext.SaveChanges();
                await _cacheService.SetLocaleResources(data);
            }

            //异步更新对应的json文件

            result.Data = true;

            return new JsonResult(result);
        }

        /// <summary>
        /// 获取对应的多语言文化数据的版本
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        [HttpGet("version/{culture}")]
        public async Task<IActionResult> GetVersion(string culture)
        {
            var result = new ApiResult<string>();
            var data = await _cacheService.GetLanguageByCulture(culture);
            if (data != null)
            {
                result = result.IsSuccess(data.ResourceVersion);
            }
            return new JsonResult(result);
        }

        /// <summary>
        /// 获取文化语言数据
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        [HttpGet("resources/{culture}")]
        public IActionResult GetLocaleResources(string culture)
        {
            var result = new ApiResult<LocalizationFile>();


            return new JsonResult(result);
        }
    }
}
