using DapperORM.Common.Models;
using PushInfo.Act.BLL;
using PushInfo.Act.Models.QueryResults;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PushPlatform.Data.Bll;
using PushInfo.Act.Models.Tables;
using PushPlatform.Common.Util;
using PushPlatform.Common.Enumerate;
using PushPlatform.Data.MvcModels;

namespace PushPlatform.Background.Areas.BackGround.Controllers
{
    public class PushConfigController : BaseController
    {
        // GET: PushConfig
        /// <summary>
        /// 推送模板列表
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public ActionResult TempletList(int page = 1)
        {
            PushConfigBLL bll = new PushConfigBLL();
            CurrentUserModel user = BllSysUser.GetCurrentUser();
            PageListModel<PushConfigResult> pageList = bll.GetPushTempletList(page, user.CurrentProjectId);
            ViewData["IS_ADMIN"] = true;
            ViewData["PAGE_LIST"] = pageList.Data;
            ViewData["PAGE_COUNT"] = pageList.TotalPageCount;
            ViewData["CURRENT_PAGE"] = pageList.CurrentPage;
            ViewData["PROJ_ID"] = "";

            return View("Index");
        }
        
        /// <summary>
        /// 编辑推送配置模板
        /// </summary>
        /// <param name="id"></param>
        /// <param name="isNew"></param>
        /// <returns></returns>
        public ActionResult EditTemplet(string id, bool isNew = true)
        {
            SetDataSource(isNew, true);

            PushConfigResult pushConfig = new PushConfigResult();
            pushConfig.PushSys_ProId = BllSysUser.GetCurrentUser().CurrentProjectId;
            if (!isNew)
            {
                if (string.IsNullOrEmpty(id)) throw new Exception("未提供推送任务Id");
                PushConfigBLL bll = new PushConfigBLL();
                pushConfig = bll.GetPushTempletById(id);
            }
            return View("Edit", pushConfig);
        }
        
        [NonAction]
        private void SetDataSource(bool isNew, bool isAdmin)
        {
            PushConfigBLL bll = new PushConfigBLL();

            List<SelectItemDetail> list = bll.GetCycleDetailList().ToList();
            list.Sort((x, y) => {
                int intx = 0;
                int inty = 0;
                if (int.TryParse(x.Value, out intx) && int.TryParse(y.Value, out inty))
                    return intx - inty;
                else
                    return 0;
            });

            ViewData["MONTH_LIST"] = list.Where(x => x.Select_Type == (int)SelectType.第几月).ToList();
            ViewData["DATE_LIST"] = list.Where(x => x.Select_Type == (int)SelectType.第几号).ToList();
            ViewData["WEEK_LIST"] = list.Where(x => x.Select_Type == (int)SelectType.第几周).ToList();
            ViewData["CONNECTION_LIST"] = list.Where(x => x.Select_Type == (int)SelectType.Mysql连接 || x.Select_Type == (int)SelectType.Sql连接).ToList();
            ViewData["IS_ADMIN"] = isAdmin;
            ViewData["IS_NEW"] = isNew;
            if (!isAdmin)
                ViewData["PUSH_LIST"] = bll.GetAllSysPush(BllSysUser.GetCurrentUser().CurrentProjectId).ToList();
        }

        /// <summary>
        /// 保存模板
        /// </summary>
        /// <param name="pushConfig"></param>
        /// <param name="isNew"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult SaveTemplet(PushConfigResult pushConfig, bool isNew)
        {
            JsonResult jr = new JsonResult();
            jr.JsonRequestBehavior = JsonRequestBehavior.AllowGet;

            if (pushConfig == null) throw new Exception("未返回表单数据");

            try
            {
                pushConfig.Push_Action = Server.UrlDecode(pushConfig.Push_Action);
                if(!string.IsNullOrEmpty(pushConfig.Push_User_Action))
                {
                    pushConfig.Push_User_Action = Server.UrlDecode(pushConfig.Push_User_Action);
                }
                string user = BllSysUser.GetCurrentUser().LoginName;
                ResultModel result = new ResultModel();
                PushConfigBLL bll = new PushConfigBLL();

                Sys_Push sysPush = new Sys_Push();
                ObjectHelper.CopyProperties(pushConfig, sysPush);
                if (isNew)
                {
                    sysPush.Id = Guid.NewGuid().ToString();
                    sysPush.Create_User = user;
                    sysPush.Create_Time = DateTime.Now;
                    result = bll.SaveSysPush(sysPush);
                }
                else
                {
                    sysPush.Update_User = user;
                    sysPush.Update_Time = DateTime.Now;
                    result = bll.UpdateSysPush(sysPush);
                }

                jr.Data = new { result = 1, msg = "操作成功" };
            }
            catch (System.Exception ex)
            {
                LogHelper.Error(ex);
                jr.Data = new { result = 0, msg = "操作失败" };
            }

            return jr;
        }
    }
}