using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PushPlatform.Data;
using PushPlatform.Data.Bll;
using PushPlatform.Data.Criteria;
using PushPlatform.Data.MvcModels;
using PushPlatform.Common.Model;
using PushInfo.Act.BLL;
using PushInfo.Act.Models.QueryResults;
using DapperORM.Common.Models;
using PushPlatform.Common.Enumerate;
using System.Data;
using PushPlatform.Data.Blls;
using PushPlatform.Background.DropDown;
using PushInfo.Act.Models.Tables;
using PushPlatform.Common.Util;
using Newtonsoft.Json.Linq;
using PushPlatform.Background.Models;

namespace PushPlatform.Background.Areas.BackGround.Controllers
{
    public class ChildProjectController : BaseController
    {
        BllProjectInfo bllProInfo = new BllProjectInfo();
        BllSelectItemDetail bllsetItem = new BllSelectItemDetail();
        // GET: BackGround/ChildProject
        #region 当前系统内的子系统的列表
        public ActionResult Index(string TextValue)
        {
            List<ChildProject> modelList = new List<ChildProject>();
            try
            {
                CurrentUserModel user = BllSysUser.GetCurrentUser();
                ProjectInfo pModel = bllProInfo.Get(user.CurrentProjectId);
                if (!string.IsNullOrEmpty(pModel.Child_ProjectInfo) && !string.IsNullOrEmpty(pModel.Db_ConnectId))
                {
                    if (pModel.Child_ProjectInfo.IndexOf("@projectName") > -1)
                    {
                        if (!string.IsNullOrEmpty(TextValue))
                        {
                            pModel.Child_ProjectInfo = pModel.Child_ProjectInfo.Replace("@projectName", string.Concat("'%", TextValue, "%'"));
                        }
                        else
                        {
                            pModel.Child_ProjectInfo = pModel.Child_ProjectInfo.Replace("@projectName", "NULL");
                        }
                    }
                    DataTable table = DbHelpBll.FetchSql(pModel.Child_ProjectInfo, pModel.Db_ConnectId);
                    foreach (DataRow row in table.Rows)
                    {
                        ChildProject model = new ChildProject();
                        model.Id = row["Id"].ToString();
                        model.ProjectName = row["Project_Name"].ToString();
                        modelList.Add(model);
                    }
                    modelList.Add(new ChildProject { Id = "generalproject", ProjectName = "通用配置" });
                }
                if (modelList.Count == 0)
                {
                    ChildProject model = new ChildProject();
                    model.Id = user.CurrentProjectId;
                    model.ProjectName = user.CurrentProjectName;
                    modelList.Add(model);
                }
            }
            catch(Exception ex)
            {
                LogHelper.Error(ex);
            }
            return View(modelList);
        }
        #endregion

        #region 配置推送
        #region 用户推送配置列表
        /// <summary>
        /// 用户推送配置列表
        /// </summary>
        /// <param name="projId"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        public ActionResult ConfigList(string projId, int page = 1)
        {
            try
            {
                PushConfigBLL bll = new PushConfigBLL();
                CurrentUserModel user = BllSysUser.GetCurrentUser();
                PageListModel<PushConfigResult> pageList = bll.GetPushConfigByPage(page, projId, user.CurrentProjectId);
                ViewData["IS_ADMIN"] = false;
                ViewData["PAGE_LIST"] = pageList.Data;
                ViewData["PAGE_COUNT"] = pageList.TotalPageCount + 1;
                ViewData["CURRENT_PAGE"] = pageList.CurrentPage;
                ViewData["PROJ_ID"] = projId;
            }
            catch(Exception ex)
            {
                LogHelper.Error(ex);
            }
            return View();
        }
        #endregion

        #region 修改配置页面
        public ActionResult EditConfig(string projId, string id, bool isNew = true)
        {
            if (isNew && string.IsNullOrEmpty(projId))
                throw new Exception("没有项目id，将无法绑定推送任务到项目");
            PushConfigBLL bll = new PushConfigBLL();

            SetDataSource(isNew, projId);
            PushConfigResult pushConfig = new PushConfigResult() { Project_Id = projId,PushSys_ProId = BllSysUser.GetCurrentUser().CurrentProjectId };
            if (!isNew)
            {
                if (string.IsNullOrEmpty(id)) throw new Exception("未提供推送任务Id");
                pushConfig = bll.GetConfigById(id);
            }
            else
            {
                id = Guid.NewGuid().ToString();
                pushConfig.Id = id;
            }
            ViewBag.proCfgId = id;
            ViewBag.projId = projId;
            return View(pushConfig);
        }

        public ActionResult FillConfig(string pushId, bool isNew,string projId)
        {
            PushConfigBLL bll = new PushConfigBLL();
            PushConfigResult pushConfig = new PushConfigResult();
            SetDataSource(isNew, projId);
            if(!string.IsNullOrEmpty(pushId))
            {
                pushConfig = bll.GetPushTempletById(pushId);
            }
            return PartialView("EditCfgPartial", pushConfig);
        }
        #endregion 
        #endregion

        /// <summary>
        /// 获取下拉
        /// </summary>
        /// <param name="isNew">是否新增</param>
        /// <param name="projId">子系统的项目Id</param>
        [NonAction]
        private void SetDataSource(bool isNew,string projId)
        {
            PushConfigBLL bll = new PushConfigBLL();
            CurrentUserModel user = BllSysUser.GetCurrentUser();
            string roldSql = "";
            ProjectInfo pModel = bllProInfo.Get(user.CurrentProjectId);
            roldSql = pModel.Object_Sql;
            List<PushInfo.Act.Models.QueryResults.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_NEW"] = isNew;
            ViewData["PUSH_LIST"] = bll.GetAllSysPush(user.CurrentProjectId).ToList();
            ViewData["role_List"] = DropDownManager.DbRoleDDL(roldSql, projId, pModel.Db_ConnectId);
            ViewData["wechatTem_List"] = DropDownManager.WechatTemListDDL(user.CurrentProjectId);
        }

        #region 保存配置
        /// <summary>
        /// 保存配置
        /// </summary>
        /// <param name="pushConfig"></param>
        /// <param name="isNew"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult SaveConfig(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);
                string user = Convert.ToString(ViewData["LoginName"]);
                ResultModel result = new ResultModel();
                PushConfigBLL bll = new PushConfigBLL();

                Map_Project_Push mapProjectPush = new Map_Project_Push();
                ObjectHelper.CopyProperties(pushConfig, mapProjectPush);
                if (isNew)
                {
                    mapProjectPush.Id = pushConfig.Id;
                    mapProjectPush.Create_User = user;
                    if (mapProjectPush.Push_Type == 0)
                    {
                        mapProjectPush.Exec_Status = (int)ExecuteStatus.启用;
                    }
                    else
                        mapProjectPush.Exec_Status = (int)ExecuteStatus.新建未安排触发器;
                    mapProjectPush.Create_Time = DateTime.Now;
                    result = bll.SaveMapProjectPush(mapProjectPush);
                }
                else
                {
                    mapProjectPush.Update_User = user;
                    mapProjectPush.Update_Time = DateTime.Now;
                    if (mapProjectPush.Push_Type == 0)
                    {
                        mapProjectPush.Exec_Status = (int)ExecuteStatus.启用;
                    }
                    else
                        mapProjectPush.Exec_Status = (int)ExecuteStatus.修改后未安排触发器;
                    result = bll.UpdateMapProjectPush(mapProjectPush);
                }

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

            return jr;
        }
        #endregion

        #region 修改任务状态
        public JsonResult SoptTask(string Id)
        {
            JsonResult jr = new JsonResult();
            jr.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            try
            {
                BllMapProjectPush bllmap = new BllMapProjectPush();
                var upModel = bllmap.Get(Id);
                if(upModel == null)
                {
                    jr.Data = new { result = 0, msg = "查询任务为空，请刷新重试。" };
                    return jr;
                }
                upModel.Exec_Status = 5;
                bllmap.Update(upModel);
                jr.Data = new { result = 1, msg = "修改成功！" };
            }
            catch (System.Exception ex)
            {
                LogHelper.Error(ex);
                jr.Data = new { result = 0, msg = "操作失败" };
            }
            return jr;
        }
        #endregion

        #region 授权该角色下的用户
        /// <summary>
        /// 用户列表
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <param name="roleId">角色ID</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult GetRoleUserInfo(string projId,string proCfgId, string roleId)
        {
            string isAllCheck = "0";
            BllMappushUserRole bllMURole = new BllMappushUserRole();
            PushConfigBLL bll = new PushConfigBLL();
            CurrentUserModel user = BllSysUser.GetCurrentUser();
            string userSql = "";
            ProjectInfo pModel = bllProInfo.Get(user.CurrentProjectId);
            userSql = pModel.User_Sql;
            List<PushInfo.Act.Models.QueryResults.SelectItemDetail> list = bll.GetCycleDetailList().ToList();
            userSql = userSql.Replace("@projectId", "'" + projId + "'").Replace("@roleId", "'" + roleId + "'");
            DataTable table = DbHelpBll.FetchSql(userSql, pModel.Db_ConnectId);
            table.Columns.Add("Checked");
            var roleList = roleId.Split(',');
            CriteriaMappushUserRole cri = new CriteriaMappushUserRole {EqMapProjectPushId = proCfgId,EqProjectId = projId ,EqIsDeleted = 0};
            //foreach (var roleIdStr in roleList)
            //{
            //    cri.InRoleId.Add(roleIdStr);
            //}
            cri.UsePage = false;
            var oldList = bllMURole.Fetch(cri);
            if(oldList.Count == 1 && oldList.FirstOrDefault().User_Id == "allUserId")
            {
                isAllCheck = "1";
            }
            else
            {
                if (table.Rows.Count > 0 && oldList != null && oldList.Count > 0)
                {
                    foreach (DataRow row in table.Rows)
                    {
                        if (oldList.Where(x => x.Role_Id == row["Role_Id"].ToString() && x.User_Id == row["userId"].ToString()).Count() > 0)
                        {
                            row["Checked"] = 1;
                        }
                        else
                        {
                            row["Checked"] = 0;
                        }
                    }
                }
            }
            ViewBag.isAllCheck = isAllCheck;
            return PartialView(table);
        }

        [HttpPost]
        public JsonResult SaveMapPushRoleUser(string jsonData)
        {
            JsonResult jr = new JsonResult();
            CurrentUserModel userInfo = BllSysUser.GetCurrentUser();
            try
            {
                BllMappushUserRole bllMURole = new BllMappushUserRole();
                var param = JsonHelper.ToObject<MapPushUserRoleParam>(jsonData);
                if(string.IsNullOrEmpty(param.ProjectId) || string.IsNullOrEmpty(param.RoleIdList) || (param.IsCheckAll !=1 && (param.DataList == null || param.DataList.Count == 0)))
                {
                    jr.Data = new { result = 0, msg = "数据传输异常，刷新重试！" };
                    return jr;
                }
                List<MappushUserRole> roleModel = new List<MappushUserRole>();
                var roleList = param.RoleIdList.Split(',');
                CriteriaMappushUserRole cri = new CriteriaMappushUserRole {EqMapProjectPushId = param.ProCfgId,EqProjectId = param.ProjectId, EqIsDeleted = 0 };
                //foreach(var roleId in roleList)
                //{
                //    cri.InRoleId.Add(roleId);
                //}
                cri.UsePage = false;
                var oldList = bllMURole.Fetch(cri);
                oldList.ForEach(x =>
                {
                    x.IsEdit = true;
                    x.Update_Time = DateTime.Now;
                    x.Is_Deleted = 1;
                });
                roleModel.AddRange(oldList);
                if(param.IsCheckAll == 1)
                {
                    MappushUserRole model = new MappushUserRole();
                    model.Id = Guid.NewGuid().ToString();
                    model.Map_Project_Push_Id = param.ProCfgId;
                    model.Project_Id = param.ProjectId;
                    model.User_Id = "allUserId";
                    model.Role_Id = "allUserId";
                    model.Create_User = userInfo.UserId;
                    model.Create_Time = DateTime.Now;
                    model.Is_Deleted = 0;
                    model.Timestamp = DateTimeHelper.GetCurrentTimestamp();
                    model.IsEdit = false;
                    roleModel.Add(model);
                }
                else
                {
                    foreach (var item in param.DataList)
                    {
                        MappushUserRole model = new MappushUserRole();
                        model.Id = Guid.NewGuid().ToString();
                        model.Map_Project_Push_Id = param.ProCfgId;
                        model.Project_Id = param.ProjectId;
                        model.User_Id = item.User_Id;
                        model.Role_Id = item.Role_Id;
                        model.Create_User = userInfo.UserId;
                        model.Create_Time = DateTime.Now;
                        model.Is_Deleted = 0;
                        model.Timestamp = DateTimeHelper.GetCurrentTimestamp();
                        model.IsEdit = false;
                        roleModel.Add(model);
                    }
                }
                bllMURole.SaveOrUpdateTran(roleModel);
            }
            catch(Exception ex)
            {
                LogHelper.Error(ex);
                jr.Data = new { result = 0, msg = "操作失败" };
            }
            jr.Data = new { result = 1, msg = "提交成功" };
            return jr;
        }
        #endregion

    }
}