using Hotline.Push;
using Hotline.Repository.SqlSugar.Extensions;
using Hotline.Share.Dtos;
using Hotline.Share.Dtos.Push;
using MapsterMapper;
using Microsoft.AspNetCore.Mvc;
using System.Text.RegularExpressions;
using XF.Domain.Exceptions;
using XF.Domain.Repository;

namespace Hotline.Api.Controllers
{
    public class TemplateDomainController : BaseController
    {
        private readonly IRepository<MessageTemplate> _messageTemplateRepository;
        private readonly IMapper _mapper;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="messageTemplateRepository"></param>
        /// <param name="mapper"></param>
        public TemplateDomainController(IRepository<MessageTemplate> messageTemplateRepository, IMapper mapper)
        {
            _messageTemplateRepository = messageTemplateRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPut("add")]
        public async Task<string> AddTemplate([FromBody] TemplateDto dto)
        {
            var data = await _messageTemplateRepository.GetAsync(p => p.Code == dto.Code, HttpContext.RequestAborted);
            if (data != null)
                throw UserFriendlyException.SameMessage("存在相同Code！");

            var template = _mapper.Map<MessageTemplate>(dto);

            Regex regex = new(@"\{[a-zA-Z0-9]{1,}\}");
            var matches = regex.Matches(template.Content);
            List<string> list = new List<string>();
            for (int i = 0; i < matches.Count; i++)
            {
                if (list.Find(p => p == matches[i].ToString()) != null)
                    throw UserFriendlyException.SameMessage("存在相同的替换参数");

                list.Add(matches[i].ToString());
            }

            return await _messageTemplateRepository.AddAsync(template, HttpContext.RequestAborted);
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPut("update")]
        public async Task UpdateTemplate([FromBody] UpdateTemplateDto dto)
        {
            var model =await _messageTemplateRepository.GetAsync(dto.Id, HttpContext.RequestAborted);
            if (model.Code!=dto.Code)
                throw UserFriendlyException.SameMessage("不能修改编码");

            _mapper.Map(dto,model);

            Regex regex = new(@"\{[a-zA-Z0-9]{1,}\}");
            var matches = regex.Matches(model.Content);
            List<string> list = new List<string>();
            for (int i = 0; i < matches.Count; i++)
            {
                if (list.Find(p => p == matches[i].ToString()) != null)
                    throw UserFriendlyException.SameMessage("存在相同的替换参数");

                list.Add(matches[i].ToString());
            }

            await _messageTemplateRepository.UpdateAsync(model, HttpContext.RequestAborted);
        }

        /// <summary>
        /// 查询详情
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpGet("info/{Id}")]
        public async Task<UpdateTemplateDto> Info(string Id)
        {
            var template = await _messageTemplateRepository.GetAsync(Id, HttpContext.RequestAborted);
            if (template is null)
                throw UserFriendlyException.SameMessage("查询失败！");
            return _mapper.Map<UpdateTemplateDto>(template);
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <param name="pagedDto"></param>
        /// <returns></returns>
        [HttpGet("getlist")]
        public async Task<PagedDto<TemplateDataDto>> GetList([FromQuery] TemplatePagedDto pagedDto)
        {
            var (total, items) = await _messageTemplateRepository
                    .Queryable()
                    .WhereIF(!string.IsNullOrEmpty(pagedDto.Keyword), d => d.Code.Contains(pagedDto.Keyword!) || d.Content.Contains(pagedDto.Keyword!) || d.Name.Contains(pagedDto.Keyword!))
                 
                    .OrderByDescending(it => it.CreationTime)
                    .ToPagedListAsync(pagedDto.PageIndex, pagedDto.PageSize, HttpContext.RequestAborted);

            return new PagedDto<TemplateDataDto>(total, _mapper.Map<IReadOnlyList<TemplateDataDto>>(items));

        }
    }
}
