using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Falcon.Extend;
using Microsoft.AspNetCore.Razor.TagHelpers;

namespace StaffManagement.Extensions
{
    /// <summary>
    /// ajax请求
    /// </summary>
    [HtmlTargetElement("a",Attributes = "fajax")]
    [HtmlTargetElement("form",Attributes = "fajax")]
    public class AjaxLinkTagHelpers:TagHelper
    {
        /// <summary>
        /// 实现ajax请求。设置为要更新的元素id并以#开头，其他则success后调用js方法。
        /// </summary>
        [HtmlAttributeName("fajax")]
        public string Fajax { get; set; }
        /// <summary>
        /// 更新模式。默认为空，可选BEFORE、AFTER或REPLACE-WITH
        /// </summary>
        [HtmlAttributeName("fajax-model")]
        public string Model { get; set; } = "";
        /// <summary>
        /// 开始ajax调用之前执行
        /// </summary>
        [HtmlAttributeName("fajax-begin")]
        public string OnBegin { get; set; } = "";
        /// <summary>
        /// 调用ajax之后执行
        /// </summary>
        [HtmlAttributeName("fajax-complete")]
        public string OnComplete { get; set; } = "";
        /// <summary>
        /// 调用失败执行
        /// </summary>
        [HtmlAttributeName("fajax-failure")]
        public string OnFailure { get; set; } = "";

        public override void Process(TagHelperContext context,TagHelperOutput output) {
            base.Process(context,output);

            if(this.Fajax.IsNullOrEmpty()) {
                return;
            }

            output.Attributes.SetAttribute("data-ajax","true");

            var fc = Fajax.Substring(0,1);
            if("#".Contains(fc)) {
                output.Attributes.SetAttribute("data-ajax-update",this.Fajax);
            } else {
                output.Attributes.SetAttribute("data-ajax-success",this.Fajax);
            }
            if(this.Model.IsNotNullOrEmpty()) {
                output.Attributes.SetAttribute("data-ajax-mode",this.Model);
            }
            if(this.OnBegin.IsNotNullOrEmpty()) {
                output.Attributes.SetAttribute("data-ajax-begin",this.OnBegin);
            }
            if(this.OnComplete.IsNotNullOrEmpty()) {
                output.Attributes.SetAttribute("data-ajax-complete",this.OnComplete);
            }
            if(this.OnFailure.IsNotNullOrEmpty()) {
                output.Attributes.SetAttribute("data-ajax-failure",this.OnFailure);
            }
        }
    }
}
