
using PageAdmin.BLL;
using PageAdmin.Common;
using PageAdmin.Utils.ORM;
using PageAdmin.Utils;
using PageAdmin.Web.Filter;
using System;
using System.Collections.Specialized;
using System.Web.Mvc;

namespace PageAdmin.Web.Areas.Admin.Controllers
{
    /// <summary>
    /// 单表设置的基类
    /// </summary>
    public class SetDataBaseController : BaseController
    {

        private static object _Lock = new object();

        protected MvcControllerContext MvcContext;

        protected string GetDataWhere = "";

        protected bool CanContinue = true;//是否继续执行

        protected DbKeyValueList AddDbKeyValueList;

        protected Action IndexViewExecuting; //首页加载前的委托
        protected Action EditExecuting; // 执行更新前的委托
        protected Action EditExecuted;//更新成功后的委托

        protected IEditBLL IEditBll;

        protected DataBaseContext DbContext;

        public SetDataBaseController(string table, string classifyDirectory) : base(classifyDirectory)
        {
            AddDbKeyValueList = new DbKeyValueList();
            DbContext = DbHelper.DbContext();
            MvcContext = new MvcControllerContext();
            MvcContext.Table = table;
            MvcContext.From = FromEnum.Admin;
        }


        //在这里设置上下文数据
        protected override void OnActionExecuting(ActionExecutingContext context)
        {
            base.CurrentUser = ViewBag.CurrentUser;
            ViewBag.Uid = base.CurrentUser.Uid;
            MvcContext.CurrentUser = base.CurrentUser;
            base.OnActionExecuting(context);
        }

        /// <summary>
        /// 执行完毕后清理缓存
        /// </summary>
        /// <param name="context"></param>
        protected override void OnActionExecuted(ActionExecutedContext context)
        {
            if (context.RequestContext.HttpContext.Request.HttpMethod == "POST")
            {
                CacheHelper.RemoveDbCache(MvcContext.Table);
            }
            base.OnActionExecuted(context);
        }


        [HttpGet]
        public virtual ActionResult Index()
        {
            IndexViewExecuting?.Invoke();
            if (MvcContext.IncludeCustomField)//包含自定义字段
            {
                CheckTable();
                LoadField("edit");
            }
            int id;
            lock(_Lock)
            {
               InitData(out id);
            }
            ViewBag.DetailId = id;
            NameValueCollection form = new NameValueCollection();
            form.Add("id", id.ToString());
            MvcContext.Data = form;
            IDetailBLL iDetailBll = new DetailBLL();
            var data= JsonHelper.JsonParse(iDetailBll.Detail(MvcContext));
            return View((object)data);
        }

        /// <summary>
        ///初始化，没有记录则添加数据
        /// </summary>
        /// <returns></returns>
        private void InitData(out int id)
        {
            id = 0;
            string fields = "id";
            dynamic data = DbContext.QueryFirst(MvcContext.Table, fields, GetDataWhere);
            if (data!=null)
            {
                id = data.Id;
            }
            else
            {
                if (AddDbKeyValueList.Count == 0)
                {
                    throw new Exception("请先设置好AddDbKeyValueList集合!");
                }
                id=DbContext.Insert(MvcContext.Table, AddDbKeyValueList);
                InitData(out id);
            }
        }

        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        [AjaxOnly]
        [HttpPost]
        /// <summary>
        /// 提交数据
        /// </summary>
        /// <returns></returns>
        public JsonResult Edit(FormCollection form)
        {
            MvcContext.Data = form;
            EditExecuting?.Invoke();//更新前的委托

            TipsInfo tipsInfo = MvcContext.TipsInfo;
            if (tipsInfo.State == 0)
            {
                return Json(tipsInfo);
            }
            if (IEditBll == null)
            {
                IEditBll = new EditBLL();
            }
            tipsInfo = IEditBll.Edit(MvcContext);
            if (tipsInfo.State == 1)
            {
                EditExecuted?.Invoke();//提交成功后的委托
            }
            return Json(tipsInfo);
        }


        private void LoadField(string pageType)
        {
            ViewBag.FieldData = new FieldBLL().GetFieldList(MvcContext.Table, pageType,MvcContext.CurrentUser);
        }


        [NonAction]
        protected void CheckTable()
        {
            string table = MvcContext.Table;
            TableTypeEnum tableType = MvcContext.TableType;
            string saveTable = "";
            if (tableType == TableTypeEnum.EntityTable)
            {
                ViewBag.Table = table;
                return;
            }
            if (tableType == TableTypeEnum.CustomInfoTable)
            {
                saveTable = "pa_info_table";
            }
            else if (tableType == TableTypeEnum.CustomCategoryTable)
            {
                saveTable = "pa_category_table";
            }
            else if (tableType == TableTypeEnum.CustomSubTable)
            {
                saveTable = "pa_sub_table";
            }
            else
            {
                return;
            }
            DbContext.SetDbParamter(new {name= table});
            dynamic data= DbContext.QueryFirst(saveTable, "remark,id", "name=@name");
            if (data!=null)
            {
                ViewBag.TableRemark = data.Remark;
                ViewBag.Table = table;
            }
            else
            {
                throw new Exception("表" + table + "不存在!");
            }
        }

    }
}