/*
 * 弹窗消息
 */

using System;
using System.Web;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MySystem.Models;
using Library;
using LitJson;
using MySystemLib;

namespace MySystem.Areas.Admin.Controllers
{
    [Area("Admin")]
    [Route("Admin/[controller]/[action]")]
    public class MsgAlertController : BaseController
    {
        public MsgAlertController(IHttpContextAccessor accessor, ILogger<BaseController> logger, IOptions<Setting> setting) : base(accessor, logger, setting)
        {
            OtherMySqlConn.connstr = ConfigurationManager.AppSettings["SqlConnStr"].ToString();
        }

        #region 弹窗消息列表

        /// <summary>
        /// 根据条件查询弹窗消息列表
        /// </summary>
        /// <returns></returns>
        public IActionResult Index(MsgAlert data, string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;


            return View();
        }

        #endregion

        #region 根据条件查询弹窗消息列表

        /// <summary>
        /// 弹窗消息列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(MsgAlert data, string MsgTypeSelect, string PushTypeSelect, string PushFlagSelect, string CreateDateData, int page = 1, int limit = 30)
        {

            Dictionary<string, string> Fields = new Dictionary<string, string>();

            Fields.Add("Title", "1"); //标题


            string condition = " and Status>-1";
            //消息类型
            if (!string.IsNullOrEmpty(MsgTypeSelect))
            {
                condition += " and MsgType=" + MsgTypeSelect;
            }
            //推送类型
            if (!string.IsNullOrEmpty(PushTypeSelect))
            {
                condition += " and PushType=" + PushTypeSelect;
            }
            //推送标记
            if (!string.IsNullOrEmpty(PushFlagSelect))
            {
                condition += " and PushFlag=" + PushFlagSelect;
            }
            //创建时间
            if (!string.IsNullOrEmpty(CreateDateData))
            {
                string[] datelist = CreateDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                string start = datelist[0];
                string end = datelist[1];
                condition += " and CreateDate>='" + start + " 00:00:00' and CreateDate<='" + end + " 23:59:59'";
            }


            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("MsgAlert", Fields, "Id desc", "0", page, limit, condition);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                //消息类型
                int MsgType = int.Parse(dic["MsgType"].ToString());
                if (MsgType == 1) dic["MsgType"] = "文本";
                if (MsgType == 2) dic["MsgType"] = "图片";
                if (MsgType == 3) dic["MsgType"] = "动图";
                if (MsgType == 0) dic["MsgType"] = "";
                dic["StatusName"] = dic["Status"].ToString() == "1" ? "使用中" : "已关闭";
                //推送类型
                int PushType = int.Parse(dic["PushType"].ToString());
                if (PushType == 0) dic["PushType"] = "不推送";
                if (PushType == 1) dic["PushType"] = "立即推送";
                if (PushType == 2) dic["PushType"] = "定时推送";
                //推送标记
                int PushFlag = int.Parse(dic["PushFlag"].ToString());
                if (PushFlag == 0) dic["PushFlag"] = "不推送";
                if (PushFlag == 1) dic["PushFlag"] = "未推送";
                if (PushFlag == 2) dic["PushFlag"] = "已推送";
                dic["AlertFlagName"] = dic["AlertFlag"].ToString() == "1" ? "是" : "否";
                dic["IsWeekendName"] = dic["IsWeekend"].ToString() == "1" ? "是" : "否";

            }
            return Json(obj);
        }

        #endregion

        #region 增加弹窗消息

        /// <summary>
        /// 增加或修改弹窗消息信息
        /// </summary>
        /// <returns></returns>
        public IActionResult Add(string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;


            return View();
        }

        #endregion

        #region 增加弹窗消息

        /// <summary>
        /// 增加或修改弹窗消息信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Add(MsgAlert data, string MakerCodes)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();

            Fields.Add("MsgType", data.MsgType); //消息类型
            Fields.Add("Status", 1); //默认开启
            Fields.Add("Title", data.Title); //标题
            Fields.Add("Summary", data.Summary); //简介
            Fields.Add("Content", data.Content); //内容
            Fields.Add("EffectStartDate", data.EffectStartDate); //有效开始时间
            Fields.Add("EffectEndDate", data.EffectEndDate); //有效结束时间
            Fields.Add("BgPic", data.BgPic); //背景图片
            Fields.Add("PushType", data.PushType); //推送类型
            Fields.Add("PushFlag", data.PushFlag); //推送标记
            Fields.Add("PushParam", data.PushParam); //推送参数
            Fields.Add("PushTime", data.PushTime); //推送时间
            Fields.Add("ExtendColumn", data.ExtendColumn); //扩展字段
            Fields.Add("UrlParam", data.UrlParam); //跳转Url参数
            Fields.Add("Url", data.Url); //跳转Url
            Fields.Add("BtnText", data.BtnText); //按钮文字
            Fields.Add("TimeByDay", data.TimeByDay); //每日次数
            Fields.Add("AlertFlag", data.AlertFlag); //弹窗标识
            Fields.Add("IsWeekend", data.IsWeekend); //是否周末

            Fields.Add("SeoTitle", data.SeoTitle);
            Fields.Add("SeoKeyword", DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8));
            Fields.Add("SeoDescription", data.SeoDescription);
            int Id = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Add("MsgAlert", Fields, 0);
            string error = "";
            if (!string.IsNullOrEmpty(MakerCodes))
            {
                string[] MakerCodeList = MakerCodes.Replace("\r", "").Replace("\n", ",").Split(',');
                foreach (var item in MakerCodeList)
                {
                    var userForMakerCode = db.UserForMakerCode.FirstOrDefault(m => m.MakerCode == item) ?? new UserForMakerCode();
                    var userSwapWhite = db.UserSwapWhite.FirstOrDefault(m => m.QueryCount == Id && m.UserId == userForMakerCode.UserId) ?? new UserSwapWhite();
                    if (userForMakerCode.UserId > 0 && userSwapWhite.Id == 0)
                    {
                        var userSwapWhiteAdd = db.UserSwapWhite.Add(new UserSwapWhite()
                        {
                            QueryCount = Id,//弹窗Id
                            CreateDate = DateTime.Now,
                            CreateMan = SysUserName + "_" + SysRealName,
                            UserId = userForMakerCode.UserId,
                        }).Entity;
                    }
                    else
                    {
                        new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Delete("MsgAlert", Id);
                        error += "创客" + item + "不存在或者已经添加了相关信息" + '\n';
                    }
                }
            }
            if (!string.IsNullOrEmpty(error))
            {
                return "Warning|" + error;
            }
            AddSysLog(data.Id.ToString(), "MsgAlert", "add");
            db.SaveChanges();

            return "success";
        }

        #endregion

        #region 修改弹窗消息

        /// <summary>
        /// 增加或修改弹窗消息信息
        /// </summary>
        /// <returns></returns>
        public IActionResult Edit(string right, int Id = 0)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;


            MsgAlert editData = db.MsgAlert.FirstOrDefault(m => m.Id == Id) ?? new MsgAlert();
            ViewBag.data = editData;
            var userSwapWhite = db.UserSwapWhite.Where(m => m.QueryCount == Id).ToList();
            var makerInfo = "";
            foreach (var item in userSwapWhite)
            {
                var user = db.Users.FirstOrDefault(m => m.Id == item.UserId) ?? new Users();
                if (user.Id > 0)
                {
                    makerInfo += user.MakerCode + ",";
                }
            }
            ViewBag.makerInfo = makerInfo.TrimEnd(',');
            return View();
        }

        #endregion

        #region 修改弹窗消息

        /// <summary>
        /// 增加或修改弹窗消息信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Edit(MsgAlert data, string MakerCodes)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();

            Fields.Add("MsgType", data.MsgType); //消息类型
            Fields.Add("Title", data.Title); //标题
            Fields.Add("Summary", data.Summary); //简介
            Fields.Add("Content", data.Content); //内容
            Fields.Add("EffectStartDate", data.EffectStartDate); //有效开始时间
            Fields.Add("EffectEndDate", data.EffectEndDate); //有效结束时间
            Fields.Add("BgPic", data.BgPic); //背景图片
            Fields.Add("PushType", data.PushType); //推送类型
            Fields.Add("PushFlag", data.PushFlag); //推送标记
            Fields.Add("PushParam", data.PushParam); //推送参数
            Fields.Add("PushTime", data.PushTime); //推送时间
            Fields.Add("ExtendColumn", data.ExtendColumn); //扩展字段
            Fields.Add("UrlParam", data.UrlParam); //跳转Url参数
            Fields.Add("Url", data.Url); //跳转Url
            Fields.Add("BtnText", data.BtnText); //按钮文字
            Fields.Add("TimeByDay", data.TimeByDay); //每日次数
            Fields.Add("AlertFlag", data.AlertFlag); //弹窗标识
            Fields.Add("IsWeekend", data.IsWeekend); //是否周末

            Fields.Add("SeoTitle", data.SeoTitle);
            Fields.Add("SeoDescription", data.SeoDescription);
            new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("MsgAlert", Fields, data.Id);
            string error = "";
            var duserSwapWhite = db.UserSwapWhite.Where(m => m.QueryCount == data.Id).ToList();
            foreach (var item in duserSwapWhite)
            {
                new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Delete("UserSwapWhite", item.Id);
            }
            if (!string.IsNullOrEmpty(MakerCodes))
            {
                string[] MakerCodeList = MakerCodes.Replace("\r", "").Replace("\n", ",").Split(',');
                foreach (var item in MakerCodeList)
                {
                    var userForMakerCode = db.UserForMakerCode.FirstOrDefault(m => m.MakerCode == item) ?? new UserForMakerCode();
                    var userSwapWhite = db.UserSwapWhite.FirstOrDefault(m => m.QueryCount == data.Id && m.UserId == userForMakerCode.UserId) ?? new UserSwapWhite();
                    if (userForMakerCode.UserId > 0 && userSwapWhite.Id == 0)
                    {
                        var userSwapWhiteAdd = db.UserSwapWhite.Add(new UserSwapWhite()
                        {
                            QueryCount = data.Id,//弹窗Id
                            CreateDate = DateTime.Now,
                            CreateMan = SysUserName + "_" + SysRealName,
                            UserId = userForMakerCode.UserId,
                        }).Entity;
                    }
                    else
                    {
                        error += "创客" + item + "不存在或者已经添加了相关信息" + '\n';
                    }
                }
            }
            if (!string.IsNullOrEmpty(error))
            {
                return "Warning|" + error;
            }
            AddSysLog(data.Id.ToString(), "MsgAlert", "update");
            db.SaveChanges();

            return "success";
        }

        #endregion

        #region 删除弹窗消息信息

        /// <summary>
        /// 删除弹窗消息信息
        /// </summary>
        /// <returns></returns>
        public string Delete(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "MsgAlert", "del");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("Status", -1);
                new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("MsgAlert", Fields, id);
            }
            db.SaveChanges();

            return "success";
        }

        #endregion

        #region 开启

        /// <summary>
        /// 开启
        /// </summary>
        /// <returns></returns>
        public string Open(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "MsgAlert", "open");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("Status", 1);
                new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("MsgAlert", Fields, id);
            }
            db.SaveChanges();
            return "success";
        }

        #endregion

        #region 关闭

        /// <summary>
        /// 关闭
        /// </summary>
        /// <returns></returns>
        public string Close(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "MsgAlert", "close");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("Status", 0);
                new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("MsgAlert", Fields, id);
            }
            db.SaveChanges();
            return "success";
        }

        #endregion

        #region 排序
        /// <summary>
        /// 排序
        /// </summary>
        /// <param name="Id"></param>
        public string Sort(int Id, int Sort)
        {
            new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Sort("MsgAlert", Sort, Id);

            AddSysLog(Id.ToString(), "MsgAlert", "sort");
            return "success";
        }
        #endregion

        #region 导入数据
        /// <summary>
        /// 导入数据
        /// </summary>
        /// <param name="ExcelData"></param>
        public string Import(string ExcelData)
        {
            ExcelData = HttpUtility.UrlDecode(ExcelData);
            JsonData list = JsonMapper.ToObject(ExcelData);
            for (int i = 1; i < list.Count; i++)
            {
                JsonData dr = list[i];

                db.MsgAlert.Add(new MsgAlert()
                {
                    CreateDate = DateTime.Now,
                    UpdateDate = DateTime.Now,

                });
                db.SaveChanges();
            }
            AddSysLog("0", "MsgAlert", "Import");
            return "success";
        }
        #endregion

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(MsgAlert data, string MsgTypeSelect, string PushTypeSelect, string PushFlagSelect)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("CreateDate", "3"); //时间
            Fields.Add("Title", "1"); //标题


            string condition = " and Status>-1";
            //消息类型
            if (!string.IsNullOrEmpty(MsgTypeSelect))
            {
                condition += " and MsgType=" + MsgTypeSelect;
            }
            //推送类型
            if (!string.IsNullOrEmpty(PushTypeSelect))
            {
                condition += " and PushType=" + PushTypeSelect;
            }
            //推送标记
            if (!string.IsNullOrEmpty(PushFlagSelect))
            {
                condition += " and PushFlag=" + PushFlagSelect;
            }


            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("MsgAlert", Fields, "Id desc", "0", 1, 20000, condition, "", false);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                //消息类型
                int MsgType = int.Parse(dic["MsgType"].ToString());
                if (MsgType == 1) dic["MsgType"] = "文本";
                if (MsgType == 2) dic["MsgType"] = "图片";
                if (MsgType == 0) dic["MsgType"] = "";
                dic["StatusName"] = dic["Status"].ToString() == "1" ? "正常" : "关闭";
                //推送类型
                int PushType = int.Parse(dic["PushType"].ToString());
                if (PushType == 0) dic["PushType"] = "不推送";
                if (PushType == 1) dic["PushType"] = "立即推送";
                if (PushType == 2) dic["PushType"] = "定时推送";
                //推送标记
                int PushFlag = int.Parse(dic["PushFlag"].ToString());
                if (PushFlag == 0) dic["PushFlag"] = "不推送";
                if (PushFlag == 1) dic["PushFlag"] = "未推送";
                if (PushFlag == 2) dic["PushFlag"] = "已推送";
                dic["AlertFlagName"] = dic["AlertFlag"].ToString() == "1" ? "是" : "否";
                dic["IsWeekendName"] = dic["IsWeekend"].ToString() == "1" ? "是" : "否";

            }

            Dictionary<string, object> result = new Dictionary<string, object>();
            result.Add("Status", "1");
            result.Add("Info", "Excel报表-" + DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss") + ".xlsx");
            result.Add("Obj", diclist);
            Dictionary<string, object> ReturnFields = new Dictionary<string, object>();

            result.Add("Fields", ReturnFields);
            AddSysLog("0", "MsgAlert", "ExportExcel");
            return Json(result);
        }

        #endregion

    }
}
