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.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Atomx.Admin.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class LanguageController : ControllerBase
    {
        private readonly ILogger<LanguageController> _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 LocalizationFile _localizationFile;


        /// <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 LanguageController(ILogger<LanguageController> logger, IIdCreatorService idCreator, IdentityService identityService, DataContext dbContext, IMapper mapper, JwtSetting jwtSettings, ICacheService cacheService, LocalizationFile localizationFile)
        {
            _logger = logger;
            _idCreator = idCreator;
            _identityService = identityService;
            _dbContext = dbContext;
            _mapper = mapper;
            _jwtSettings = jwtSettings;
            _cacheService = cacheService;
            _localizationFile = localizationFile;
        }

        /// <summary>
        /// 获取启用用的语言
        /// </summary>
        /// <returns></returns>
        [HttpGet("enabled")]
        public async Task<IActionResult> CacheLanguage()
        {
            var result = new Result<List<Language>>();

            var list = await _cacheService.GetLanguages(true);

            result.Data = list;

            return new JsonResult(result);
        }

        /// <summary>
        /// 分页获取语言列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="name"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        [HttpPost("search")]
        public IActionResult LanguageList(LanguageSearch search, int page,int size = 20)
        {
            if (page < 1)
            {
                page = 1;
            }
            var result = new Result<PagingList<Language>>();
            var list = new PagingList<Language>() { Index = page, Size = size };
            var query = from p in _dbContext.Languages
                        select p;

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

            result.Data = list;

            return new JsonResult(result);
        }

        /// <summary>
        /// 获取语言信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("detail")]
        public IActionResult GetManufacturer(long id)
        {
            var result = new Result<Language>();

            var data = _dbContext.Languages.SingleOrDefault(p => p.Id == id);
            if (data == null)
            {
                return new JsonResult(result);
            }

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



        /// <summary>
        /// 保存语言信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("save")]
        public async Task<IActionResult> LanguageEdit(LanguageModel model)
        {
            var result = new Result<bool>();
            var validator = new LanguageModelValidator();
            var validation = validator.Validate(model);
            if (!validation.IsValid)
            {
                result.Message = ModelState.Values.First().Errors[0].ErrorMessage;
                result.Success = false;
                return new JsonResult(result);
            }
            if (model.IsEdit)
            {
                var data = _dbContext.Languages.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.GetLanguageById(model.Id, data);
            }
            else
            {
                var data = _mapper.Map<Language>(model);
                data.CreateTime = DateTime.UtcNow;
                _dbContext.Languages.Add(data);
                _dbContext.SaveChanges();
                await _cacheService.GetLanguageById(model.Id, data);
            }

            result.Data = true;

            return new JsonResult(result);
        }
    }
}
