using Serilog;
using StackExchange.Profiling;
using static Tiobon.Core.Extensions.CustomApiVersion;

namespace Tiobon.Core.Controllers
{
    /// <summary>
    /// 博客管理
    /// </summary>
    [Produces("application/json")]
    [Route("api/Tiobon"), ApiExplorerSettings(GroupName = Grouping.GroupName_Other)]
    public class TiobonController : BaseApiController
    {
        public ITiobonArticleServices _TiobonArticleServices { get; set; }
        private readonly ILogger<TiobonController> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger"></param>
        /// 
        public TiobonController(ILogger<TiobonController> logger)
        {
            _logger = logger;
        }


        /// <summary>
        /// 获取博客列表【无权限】
        /// </summary>
        /// <param name="id"></param>
        /// <param name="page"></param>
        /// <param name="bcategory"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ServiceResult<PageModel<TiobonArticle>>> Get(int id, int page = 1, string bcategory = "技术博文", string key = "")
        {
            int intPageSize = 6;
            if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key))
            {
                key = "";
            }

            Expression<Func<TiobonArticle, bool>> whereExpression = a => (a.bcategory == bcategory && a.IsDeleted == false) && ((a.btitle != null && a.btitle.Contains(key)) || (a.bcontent != null && a.bcontent.Contains(key)));

            var pageModelTiobon = await _TiobonArticleServices.QueryPage(whereExpression, page, intPageSize, " bID desc ");

            using (MiniProfiler.Current.Step("获取成功后，开始处理最终数据"))
            {
                foreach (var item in pageModelTiobon.data)
                {
                    if (!string.IsNullOrEmpty(item.bcontent))
                    {
                        item.bRemark = (HtmlHelper.ReplaceHtmlTag(item.bcontent)).Length >= 200 ? (HtmlHelper.ReplaceHtmlTag(item.bcontent)).Substring(0, 200) : (HtmlHelper.ReplaceHtmlTag(item.bcontent));
                        int totalLength = 500;
                        if (item.bcontent.Length > totalLength)
                        {
                            item.bcontent = item.bcontent.Substring(0, totalLength);
                        }
                    }
                }
            }

            return SuccessPage(pageModelTiobon);
        }


        /// <summary>
        /// 获取博客详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        //[Authorize(Policy = "Scope_TiobonModule_Policy")]
        [Authorize]
        public async Task<ServiceResult<TiobonViewModels>> Get(long id)
        {
            return Success(await _TiobonArticleServices.GetTiobonDetails(id));
        }


        /// <summary>
        /// 获取详情【无权限】
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("DetailNuxtNoPer")]
        public async Task<ServiceResult<TiobonViewModels>> DetailNuxtNoPer(long id)
        {
            _logger.LogInformation("xxxxxxxxxxxxxxxxxxx");
            Log.Information("yyyyyyyyyyyyyyyyy");
            return Success(await _TiobonArticleServices.GetTiobonDetails(id));
        }

        [HttpGet]
        [Route("GoUrl")]
        public async Task<IActionResult> GoUrl(long id = 0)
        {
            var response = await _TiobonArticleServices.QueryById(id);
            if (response != null && response.bsubmitter.IsNotEmptyOrNull())
            {
                string Url = @"^http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?$";
                if (Regex.IsMatch(response.bsubmitter, Url))
                {
                    response.btraffic += 1;
                    await _TiobonArticleServices.Update(response);
                    return Redirect(response.bsubmitter);
                }

            }

            return Ok();
        }

        [HttpGet]
        [Route("GetTiobonsByTypesForMVP")]
        public async Task<ServiceResult<List<TiobonArticle>>> GetTiobonsByTypesForMVP(string types = "", int id = 0)
        {
            if (types.IsNotEmptyOrNull())
            {
                var Tiobons = await _TiobonArticleServices.Query(d => d.bcategory != null && types.Contains(d.bcategory) && d.IsDeleted == false, d => d.bID, false);
                return Success(Tiobons);
            }
            return Success(new List<TiobonArticle>() { });
        }

        [HttpGet]
        [Route("GetTiobonByIdForMVP")]
        public async Task<ServiceResult<TiobonArticle>> GetTiobonByIdForMVP(long id = 0)
        {
            if (id > 0)
            {
                return Success(await _TiobonArticleServices.QueryById(id));
            }
            return Success(new TiobonArticle());
        }

        /// <summary>
        /// 获取博客测试信息 v2版本
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        ////MVC自带特性 对 api 进行组管理
        //[ApiExplorerSettings(GroupName = "v2")]
        ////路径 如果以 / 开头，表示绝对路径，反之相对 controller 的想u地路径
        //[Route("/api/v2/Tiobon/Tiobontest")]
        //和上边的版本控制以及路由地址都是一样的

        [CustomRoute(ApiVersions.V2, "Tiobontest")]
        public ServiceResult<string> V2_Tiobontest()
        {
            return Success<string>("我是第二版的博客信息");
        }

        /// <summary>
        /// 添加博客【无权限】
        /// </summary>
        /// <param name="TiobonArticle"></param>
        /// <returns></returns>
        [HttpPost]
        //[Authorize(Policy = "Scope_TiobonModule_Policy")]
        [Authorize]
        public async Task<ServiceResult<string>> Post([FromBody] TiobonArticle TiobonArticle)
        {
            if (TiobonArticle.btitle.Length > 5 && TiobonArticle.bcontent.Length > 50)
            {

                TiobonArticle.bCreateTime = DateTime.Now;
                TiobonArticle.bUpdateTime = DateTime.Now;
                TiobonArticle.IsDeleted = false;
                TiobonArticle.bcategory = "技术博文";
                var id = (await _TiobonArticleServices.Add(TiobonArticle));
                return id > 0 ? Success<string>(id.ObjToString()) : Failed("添加失败");
            }
            else
            {
                return Failed("文章标题不能少于5个字符，内容不能少于50个字符！");
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="TiobonArticle"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("AddForMVP")]
        [Authorize(Permissions.Name)]
        public async Task<ServiceResult<string>> AddForMVP([FromBody] TiobonArticle TiobonArticle)
        {
            TiobonArticle.bCreateTime = DateTime.Now;
            TiobonArticle.bUpdateTime = DateTime.Now;
            TiobonArticle.IsDeleted = false;
            var id = (await _TiobonArticleServices.Add(TiobonArticle));
            return id > 0 ? Success<string>(id.ObjToString()) : Failed("添加失败");
        }
        /// <summary>
        /// 更新博客信息
        /// </summary>
        /// <param name="TiobonArticle"></param>
        /// <returns></returns>
        // PUT: api/User/5
        [HttpPut]
        [Route("Update")]
        [Authorize(Permissions.Name)]
        public async Task<ServiceResult<string>> Put([FromBody] TiobonArticle TiobonArticle)
        {
            if (TiobonArticle != null && TiobonArticle.bID > 0)
            {
                var model = await _TiobonArticleServices.QueryById(TiobonArticle.bID);

                if (model != null)
                {
                    model.btitle = TiobonArticle.btitle;
                    model.bcategory = TiobonArticle.bcategory;
                    model.bsubmitter = TiobonArticle.bsubmitter;
                    model.bcontent = TiobonArticle.bcontent;
                    model.btraffic = TiobonArticle.btraffic;

                    if (await _TiobonArticleServices.Update(model))
                    {
                        return Success<string>(TiobonArticle?.bID.ObjToString());
                    }
                }
            }
            return Failed("更新失败");
        }



        /// <summary>
        /// 删除博客
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        [Authorize(Permissions.Name)]
        [Route("Delete")]
        public async Task<ServiceResult<string>> Delete(long id)
        {
            if (id > 0)
            {
                var TiobonArticle = await _TiobonArticleServices.QueryById(id);
                if (TiobonArticle == null)
                {
                    return Failed("查询无数据");
                }
                TiobonArticle.IsDeleted = true;
                return await _TiobonArticleServices.Update(TiobonArticle) ? Success(TiobonArticle?.bID.ObjToString(), "删除成功") : Failed("删除失败");
            }
            return Failed("入参无效");
        }
        /// <summary>
        /// apache jemeter 压力测试
        /// 更新接口
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("ApacheTestUpdate")]
        public async Task<ServiceResult<bool>> ApacheTestUpdate()
        {
            return Success(await _TiobonArticleServices.Update(new { bsubmitter = $"laozhang{DateTime.Now.Millisecond}", bID = 1 }), "更新成功");
        }
    }
}