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

namespace Atomx.Admin.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AdminController : ControllerBase
    {
        readonly ILogger<AdminController> _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 AdminController(ILogger<AdminController> 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(AdminSearch search, int page, int size = 20)
        {
            var startTime = search.RangeTime[0];
            if (startTime != null)
            {
                search.StartTime = startTime.Value.ConvertStartDateUTCTime();
            }
            try
            {
                var endTime = search.RangeTime[1];
                if (endTime != null)
                {
                    search.EndTime = endTime.Value.ConvertEndDateUTCTime();
                }
            }
            catch
            {
                search.EndTime = null;
            }

            var result = new ApiResult<PagingList<Common.Entities.Admin>>();
            try
            {
                var pager = new PagingList<Common.Entities.Admin>() { Size = size, Index = page < 1 ? 1 : page };

                var query = from p in _dbContext.Admins
                            select p;
                if (!string.IsNullOrEmpty(search.Mobile))
                {
                    query = from p in query
                            where p.Mobile == search.Mobile
                            select p;
                }
                if (!string.IsNullOrEmpty(search.Username))
                {
                    query = from p in query
                            where p.Username.Contains(search.Username)
                            select p;
                }
                if (!string.IsNullOrEmpty(search.Email))
                {
                    query = from p in query
                            where p.Email.Contains(search.Email)
                            select p;
                }
                if (!string.IsNullOrEmpty(search.Status))
                {
                    query = from p in query
                            where p.Status == search.Status.ToInt()
                            select p;
                }
                if (search.StartTime.HasValue)
                {
                    query = from p in query
                            where p.CreateTime >= search.StartTime.Value.ToUniversalTime()
                            select p;
                }
                if (search.EndTime.HasValue)
                {
                    query = from p in query
                            where p.CreateTime <= search.EndTime.Value.ToUniversalTime()
                            select p;
                }

                pager.Count = query.Count();

                pager.Items = query.OrderByDescending(p => p.CreateTime).Skip((pager.Index - 1) * size).Take(size).ToList();
                result = result.IsSuccess(pager);
            }
            catch (Exception ex)
            {
                result = result.IsFail(ex.Message);
                _logger.LogError(ex.Message);
            }
            return new JsonResult(result);
        }

        /// <summary>
        /// 根据id获取数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id:long}")]
        public IActionResult Get(long id)
        {
            var result = new ApiResult<Common.Entities.Admin>();
            try
            {
                var data = _dbContext.Admins.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(AdminModel model)
        {
            var result = new ApiResult<string>();
            var validator = new AdminModelValidator();
            var validation = validator.Validate(model);
            if (!validation.IsValid)
            {
                var message = validation.Errors.FirstOrDefault()?.ErrorMessage ?? string.Empty;
                result = result.IsFail(message, null);
                return new JsonResult(result);
            }

            if (_dbContext.Admins.Count(p => p.Username == model.Username && p.Id != 0) > 0)
            {
                result = result.IsFail("用户名已经被使用，请更换用户名", null);
                return new JsonResult(result);
            }

            if (!string.IsNullOrEmpty(model.Email))
            {
                if (_dbContext.Admins.Count(p => p.Email == model.Email && p.Id != 0) > 0)
                {
                    result = result.IsFail("电子邮件已被使用，请更换常用邮件地址", null);
                    return new JsonResult(result);
                }
            }

            try
            {
                model.Id = _idCreator.NewId();
                model.Password = model.Password.ToMd5Password();
                
                var admin = _mapper.Map<Common.Entities.Admin>(model);
                admin.CreateTime = DateTime.UtcNow;

                _dbContext.Admins.Add(admin);
                int 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(AdminModel model)
        {
            var result = new ApiResult<string>();
            var validator = new AdminModelValidator();
            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);
            }

            if (_dbContext.Admins.Count(p => p.Username == model.Username && p.Id != model.Id) > 0)
            {
                result = result.IsFail("用户名已经被使用，请更换用户名", null);
                return new JsonResult(result);
            }

            if (!string.IsNullOrEmpty(model.Email))
            {
                if (_dbContext.Admins.Count(p => p.Email == model.Email && p.Id != model.Id) > 0)
                {
                    result = result.IsFail("电子邮件已被使用，请更换常用邮件地址", null);
                    return new JsonResult(result);
                }
            }


            var data = _dbContext.Admins.SingleOrDefault(p => p.Id == model.Id);
            if (data == null)
            {
                result = result.IsFail("数据不存在");
                return new JsonResult(result);
            }
            if (!string.IsNullOrEmpty(model.Password))
            {
                model.Password = model.Password.Trim().ToMd5Password();
            }
            data.Username = model.Username;
            data.Email = model.Email;
            data.Mobile = model.Mobile;
            data.UpdateTime = DateTime.UtcNow;
            data.Status = model.Status;

            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
            {
                Console.WriteLine($"{id} deleted");
                var count = _dbContext.Admins.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);
        }

    }
}
