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

namespace Atomx.Admin.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class AddressController : ControllerBase
    {
        private readonly ILogger<AddressController> _logger;
        private readonly DataContext _dbContext;
        private readonly IIdCreatorService _idCreator;
        private readonly IdentityService _identityService;
        private readonly IMapper _mapper;
        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 AddressController(ILogger<AddressController> logger, IIdCreatorService idCreator, IdentityService identityService, DataContext dbContext, IMapper mapper, ICacheService cacheService)
        {
            _logger = logger;
            _idCreator = idCreator;
            _identityService = identityService;
            _dbContext = dbContext;
            _mapper = mapper;
            _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("list")]
        [Authorize(Policy = Permissions.User.View)]
        public IActionResult AddressList(int page, string? name, DateTime? start, DateTime? end, int size = 20)
        {
            if (page < 1)
            {
                page = 1;
            }
            var result = new ApiResult<PagingList<Address>>();
            var list = new PagingList<Address>() { Index = page, Size = size };
            var query = from p in _dbContext.Addresses
                        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();
            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="model"></param>
        /// <returns></returns>
        [HttpPost("save")]
        public IActionResult AddressEdit(AddressModel model)
        {
            var result = new ApiResult<bool>();
            var validator = new AddressModelValidator();
            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.Addresses.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();

            }
            else
            {
                var data = _mapper.Map<Address>(model);
                data.Id = _idCreator.NewId();
                data.CreateTime = DateTime.UtcNow;
                _dbContext.Addresses.Add(data);
                _dbContext.SaveChanges();
            }

            result = result.IsSuccess();

            return new JsonResult(result);
        }

        /// <summary>
        /// 删除地址
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>

        [HttpPost("delete")]
        public async Task<IActionResult> DeleteAsync(long id)
        {
            var result = new ApiResult<bool>();

            await _dbContext.Addresses.Where(p => p.Id == id).ExecuteUpdateAsync(p => p.SetProperty(x => x.IsDelete, x => true));
            result = result.IsSuccess();

            return new JsonResult(result);
        }
    }
}
