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.Extension;
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 CurrencyController : ControllerBase
    {
        private readonly ILogger<CurrencyController> _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;


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

        ///// <summary>
        ///// 分页获取制造商列表
        ///// </summary>
        ///// <param name="page"></param>
        ///// <param name="name"></param>
        ///// <param name="start"></param>
        ///// <param name="end"></param>
        ///// <param name="size"></param>
        ///// <returns></returns>
        //[HttpGet("enabled")]
        //public async Task<IActionResult> GetEnabledList()
        //{

        //    var result = new Result<List<Currency>>();
        //    var data = await _cacheService.GetCurrencies();

        //    result.Data = data;

        //    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>
        //[HttpGet("list")]
        //public async Task<IActionResult> GetList(int page, string? name, DateTime? start, DateTime? end, int size = 20)
        //{
        //    if (page < 1)
        //    {
        //        page = 1;
        //    }
        //    var result = new Result<PagingList<CurrencyModel>>();
        //    var list = new PagingList<CurrencyModel>() { Index = page, Size = size };

        //    var table = new List<Currency>();
        //    var query = from p in _dbContext.Currencies
        //                select p;

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

        //    if (start.HasValue)
        //    {
        //        query = from p in query
        //                where p.CreateTime >= start.Value
        //                select p;
        //    }
        //    if (end.HasValue)
        //    {
        //        query = from p in query
        //                where p.CreateTime <= end.Value
        //                select p;
        //    }
        //    list.Count = query.Count();
        //    table = query.OrderByDescending(p => p.CreateTime).Skip((page - 1) * size).Take(size).ToList();

        //    var ids = table.Select(p => p.Id).ToList();

        //    list.Items = _mapper.Map<List<CurrencyModel>>(table);

        //    var config = await _cacheService.GetGeneralConfig();

        //    foreach (var item in list.Items)
        //    {
        //        if (config.PrimaryCurrencyId == item.Id)
        //        {
        //            item.PrimaryCurrency = true;
        //        }
        //    }

        //    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<CurrencyModel>();

        //    var data = _dbContext.Currencies.SingleOrDefault(p => p.Id == id);
        //    if (data == null)
        //    {
        //        return new JsonResult(result);
        //    }
        //    var localizedList = _dbContext.LocalizedProperties.Where(p => p.EntityId == id).ToList();

        //    var currency = _mapper.Map<CurrencyModel>(data);
        //    currency.Localized = localizedList;

        //    result.Data = currency;

        //    return new JsonResult(result);
        //}

        ///// <summary>
        ///// 保存货币信息
        ///// </summary>
        ///// <param name="model"></param>
        ///// <returns></returns>
        //[HttpPost("save")]
        //public async Task<IActionResult> ManufacturerEdit(CurrencyModel model)
        //{
        //    var result = new Result<bool>();
        //    var validator = new CurrencyModelValidator();
        //    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 && model.Id > 0)
        //    {
        //        var data = _dbContext.Currencies.SingleOrDefault(p => p.Id == model.Id);
        //        if (data == null)
        //        {
        //            result.Message = "数据不存在，请更换！";
        //            result.Success = false;
        //            return new JsonResult(result);
        //        }

        //        if (model.Language.ToInt() == 0)
        //        {

        //            data = _mapper.Map(model, data);
        //            data.UpdateTime = DateTime.UtcNow;
        //            _dbContext.SaveChanges();
        //            await _cacheService.GetCurrenciesById(model.Id, data);
        //        }
        //        else
        //        {
        //            var localizedList = _dbContext.LocalizedProperties.Where(p => p.LanguageNumber == model.Language.ToInt() && p.EntityId == model.Id).ToList();
        //            var name = nameof(model.Name);

        //            var nameData = localizedList.SingleOrDefault(p => p.Key == name);

        //            var newLocalizedList = new List<LocalizedProperty>();

        //            var addLocalizedList = new List<LocalizedProperty>();

        //            if (nameData == null)
        //            {
        //                if (!string.IsNullOrEmpty(model.Name))
        //                {
        //                    nameData = new LocalizedProperty()
        //                    {
        //                        Id = _idCreator.NewId(),
        //                        EntityId = model.Id,
        //                        LanguageNumber = model.Language.ToInt(),
        //                        Type = (int)LocalizedType.Manufacturer,
        //                        Key = name,
        //                        Value = model.Name
        //                    };
        //                    addLocalizedList.Add(nameData);
        //                }
        //            }
        //            else
        //            {
        //                if (!string.IsNullOrEmpty(model.Name))
        //                {
        //                    nameData.Value = model.Name;
        //                }
        //                else
        //                {
        //                    _dbContext.LocalizedProperties.Remove(nameData);
        //                }

        //            }
        //            if (nameData != null)
        //            {
        //                newLocalizedList.Add(nameData);
        //            }

        //            if (addLocalizedList.Any())
        //            {
        //                _dbContext.LocalizedProperties.AddRange(addLocalizedList);
        //            }

        //            data.Enabled = model.Enabled;
        //            data.DisplayOrder = model.DisplayOrder;
        //            data.UpdateTime = DateTime.UtcNow;


        //            try
        //            {

        //                _dbContext.SaveChanges();
        //            }
        //            catch (Exception ex)
        //            {
        //                Console.WriteLine($"{ex.Message}");
        //            }

        //            await _cacheService.GetCurrenciesById(model.Id, data);
        //            await _cacheService.GetLocalizedProperty(model.Id, model.Language.ToInt(), newLocalizedList);
        //        }
        //    }
        //    else
        //    {
        //        var data = _mapper.Map<Currency>(model);
        //        var maxid = _dbContext.PaymentChannels.Max(p => p.Id);

        //        data.Id = maxid + 1;
        //        data.CreateTime = DateTime.UtcNow;

        //        _dbContext.Currencies.Add(data);
        //        _dbContext.SaveChanges();
        //        await _cacheService.GetCurrenciesById(model.Id, data);
        //    }

        //    result.Data = true;

        //    return new JsonResult(result);
        //}

        ///// <summary>
        ///// 删除制造商
        ///// </summary>
        ///// <param name="model"></param>
        ///// <returns></returns>

        //[HttpPost("delete")]
        //public async Task<IActionResult> DeleteAsync(long id)
        //{
        //    var result = new Result<bool>();
        //    var data = _dbContext.Currencies.SingleOrDefault(p => p.Id == id);
        //    if (data != null)
        //    {
        //        _dbContext.Currencies.Remove(data);
        //        _dbContext.SaveChanges();
        //        await _cacheService.RemoveCurrencies(data.Id);
        //    }
        //    result.Data = true;

        //    return new JsonResult(result);
        //}
    }
}
