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

namespace Atomx.Admin.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class SpecificationAttributeController : ControllerBase
    {
        readonly ILogger<SpecificationAttributeController> _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 SpecificationAttributeController(ILogger<SpecificationAttributeController> 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(SpecificationAttributeSearch search, int page, int size = 20)
        {
            var result = new ApiResult<PagingList<SpecificationAttributeItemModel>>();
            try
            {
                var pager = new PagingList<SpecificationAttributeItemModel>() { Size = size, Index = page < 1 ? 1 : page };

                var query = from p in _dbContext.SpecificationAttributes
                            select p;
                if (!string.IsNullOrEmpty(search.Name))
                {
                    query = from p in query
                            where p.Name.Contains(search.Name)
                            select p;
                }
                if (search.CategoryId > 0)
                {
                    query = from p in query
                            where p.CategoryId == search.CategoryId
                            select p;
                }

                pager.Count = query.Count();

                var data = query.OrderByDescending(p => p.Id).Skip((pager.Index - 1) * size).Take(size).ToList();
                var categoryIds = data.Select(p => p.CategoryId).ToList();
                var categories = _dbContext.Categories.Where(c => categoryIds.Contains(c.Id)).ToList();
                var items = new List<SpecificationAttributeItemModel>();
                foreach (var item in data)
                {
                    var attribute = item.Adapt<SpecificationAttributeItemModel>();
                    attribute.CategoryName = categories.SingleOrDefault(p => p.Id == item.CategoryId)?.Name ?? string.Empty;
                    items.Add(attribute);
                }
                pager.Items = items;

                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<SpecificationAttribute>();
            try
            {
                var data = _dbContext.SpecificationAttributes.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(SpecificationAttributeModel model)
        {
            var result = new ApiResult<string>();
            var validator = new SpecificationAttributeModelValidator();
            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.SpecificationAttributes.Count(p => p.Name == model.Name && p.Id != 0) > 0)
            {
                result = result.IsFail("名称已经被使用，请更换名称", null);
                return new JsonResult(result);
            }

            try
            {
                model.Id = _idCreator.NewId();
                var data = _mapper.Map<SpecificationAttribute>(model);
                data.CreateTime = DateTime.UtcNow;

                _dbContext.SpecificationAttributes.Add(data);
                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(SpecificationAttributeModel model)
        {
            var result = new ApiResult<string>();
            var validator = new SpecificationAttributeModelValidator();
            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.SpecificationAttributes.Count(p => p.Name == model.Name && p.Id != model.Id) > 0)
            {
                result = result.IsFail("名称已经被使用，请更换名称", null);
                return new JsonResult(result);
            }


            try
            {
                var data = _dbContext.SpecificationAttributes.Where(p => p.Id == model.Id).SingleOrDefault();
                if (data != null)
                {
                    data = _mapper.Map(model, data);
                    data.UpdateTime = DateTime.UtcNow;
                    int count = _dbContext.SaveChanges();
                    result = result.IsSuccess(count.ToString());
                }
                else
                {
                    result = result.IsFail("数据不存在");
                    return new JsonResult(result);
                }
            }
            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>();
            var num = _dbContext.SpecificationAttributeOptions.Count(p=>p.SpecificationId == id);
            if (num > 0)
            {
                result = result.IsFail("无法删除有预设值的规格属性");
            }
            else
            {
                try
                {
                    Console.WriteLine($"{id} deleted");
                    var count = _dbContext.SpecificationAttributes.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);
        }
    }
}