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.Services;
using MapsterMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace Atomx.Admin.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UploadFileController : ControllerBase
    {
        readonly ILogger<UploadFileController> _logger;
        readonly IdentityService _identityService;
        readonly IIdCreatorService _idCreator;
        readonly IMapper _mapper;
        readonly DataContext _dbContext;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="identityService"></param>
        /// <param name="idCreator"></param>
        /// <param name="adminService"></param>
        /// <param name="mapper"></param>
        public UploadFileController(ILogger<UploadFileController> logger, IdentityService identityService, IIdCreatorService idCreator, IMapper mapper, DataContext dataContext)
        {
            _logger = logger;
            _identityService = identityService;
            _idCreator = idCreator;
            _mapper = mapper;
            _dbContext = dataContext;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="search"></param>
        /// <param name="page"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        [HttpPost("search")]
        public IActionResult Search(UploadFileSearch search, int page, int size = 20)
        {
            var result = new ApiResult<PagingList<UploadFile>>();
            try
            {
                var pager = new PagingList<UploadFile>() { Size = size, Index = page < 1 ? 1 : page };
                var query = from p in _dbContext.UploadFiles
                            select p;
                if (search.Type.HasValue)
                {
                    query = from p in query
                            where p.Type == search.Type
                            select p;
                }
                if (!string.IsNullOrEmpty(search.Name))
                {
                    query = from p in query
                            where p.Name == search.Name
                            select p;
                }
                pager.Count = query.Count();
                var list = query.OrderByDescending(p => p.UpdateTime).Skip((pager.Index - 1) * size).Take(size).ToList();
                pager.Items = list;

                result = result.IsSuccess(pager);
            }
            catch (Exception ex)
            {
                result = result.IsFail(ex.Message);
                _logger.LogError(ex.Message);
            }
            return new JsonResult(result);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id:long}")]
        public IActionResult Get(long id)
        {
            var result = new ApiResult<UploadFile>();
            try
            {
                var data = _dbContext.UploadFiles.Where(p => p.Id == id).SingleOrDefault();
                result = result.IsSuccess(data);
            }
            catch (Exception ex)
            {
                result = result.IsFail(ex.Message);
                _logger.LogError(ex.Message);
            }
            return new JsonResult(result);
        }

        /// <summary>
        /// 添加版本信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public IActionResult Add(UploadFileModel model)
        {
            var result = new ApiResult<string>();
            var validator = new UploadFileModelValidator();
            var validation = validator.Validate(model);
            if (!validation.IsValid)
            {
                var message = validation.Errors.FirstOrDefault()?.ErrorMessage;
                result = result.IsFail(message ?? string.Empty, null);
                return new JsonResult(result);
            }
            try
            {
                model.Id = _idCreator.NewId();
                var message = _mapper.Map<UploadFile>(model);
                message.CreateTime = DateTime.UtcNow;

                _dbContext.UploadFiles.Add(message);
                var count = _dbContext.SaveChanges();

                result = result.IsSuccess(count.ToString());
            }
            catch (Exception ex)
            {
                result = result.IsFail(ex.Message);
                _logger.LogError(ex.Message);
            }
            return new JsonResult(result);
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("edit")]
        public IActionResult Edit(UploadFileModel model)
        {
            var result = new ApiResult<string>();
            var validator = new UploadFileModelValidator();
            var validation = validator.Validate(model);
            if (!validation.IsValid)
            {
                var message = validation.Errors.FirstOrDefault()?.ErrorMessage;
                result = result.IsFail(message ?? string.Empty, null);
                return new JsonResult(result);
            }

            var data = _dbContext.UploadFiles.SingleOrDefault(p => p.Id == model.Id);
            if (data == null)
            {
                result = result.IsFail("数据不存在");
                return new JsonResult(result);
            }

            data.UpdateTime = DateTime.UtcNow;

            try
            {
                int count = _dbContext.SaveChanges();
                result = result.IsSuccess(count.ToString());
            }
            catch (Exception ex)
            {
                result = result.IsFail(ex.Message);
                _logger.LogError(ex.Message);
                Console.WriteLine(ex.Message);
            }
            return new JsonResult(result);
        }

        /// <summary>
        /// 根据ID删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost("delete/{id:long}")]
        public IActionResult Delete(long id)
        {
            var result = new ApiResult<string>();
            try
            {
                var count = _dbContext.UploadFiles.Where(p => p.Id == id).ExecuteDelete();
                result = result.IsSuccess(count.ToString());
            }
            catch (Exception ex)
            {
                result = result.IsFail(ex.Message);
                _logger.LogError(ex.Message);
            }
            return new JsonResult(result);
        }
    }
}
