/*
 * 个人消息
 */

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 MsgPersonalController : BaseController
    {
        public MsgPersonalController(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(MsgPersonal data, string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;

            return View();
        }

        #endregion

        #region 根据条件查询个人消息列表

        /// <summary>
        /// 个人消息列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(MsgPersonal data, string MakerCode, string StatusSelect, string ReadFlagSelect, string CreateDateData, int page = 1, int limit = 30)
        {

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

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

            string condition = " and Status>-1";
            //创客编号
            if (!string.IsNullOrEmpty(MakerCode))
            {
                condition += " and UserId in (select UserId from UserForMakerCode where MakerCode='" + MakerCode + "')";
            }
            //状态
            if(!string.IsNullOrEmpty(StatusSelect))
            {
                condition += " and Status=" + StatusSelect;
            }
            //是否已读
            if(!string.IsNullOrEmpty(ReadFlagSelect))
            {
                condition += " and ReadFlag=" + ReadFlagSelect;
            }
            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("MsgPersonal", 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)
            {
                dic["TemplateId"] = RelationClass.GetMsgTemplateInfo(int.Parse(dic["TemplateId"].ToString()));
                //展示类型
                int MsgType = int.Parse(dic["MsgType"].ToString());
                if(MsgType == 0) dic["MsgType"] = "html页面";
                if(MsgType == 1) dic["MsgType"] = "指定url";
                if(MsgType == 2) dic["MsgType"] = "简单中文描述";
                //状态
                int Status = int.Parse(dic["Status"].ToString());
                if(Status == 1) dic["Status"] = "正常";
                if(Status == 0) dic["Status"] = "已删除";
                //是否已读
                int ReadFlag = int.Parse(dic["ReadFlag"].ToString());
                if(ReadFlag == 1) dic["ReadFlag"] = "是";
                if(ReadFlag == 0) dic["ReadFlag"] = "否";
                //推送标识
                int PushFlag = int.Parse(dic["PushFlag"].ToString());
                if(PushFlag == 1) dic["PushFlag"] = "是";
                if(PushFlag == 0) dic["PushFlag"] = "否";
            }
            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(MsgPersonal data, int AddKind, string MakerCode)
        {
            string[] MakerCodeList = MakerCode.Split(',');
            foreach (string code in MakerCodeList)
            {
                Models.UserForMakerCode codeData = db.UserForMakerCode.FirstOrDefault(m => m.MakerCode == code) ?? new Models.UserForMakerCode();
                if (AddKind == 0)
                {
                    Dictionary<string, object> Fields = new Dictionary<string, object>();
                    Fields.Add("UserId", codeData.UserId); //创客
                    Fields.Add("MsgType", data.MsgType); //消息类型
                    Fields.Add("BgPic", data.BgPic); //背景图片
                    Fields.Add("Title", data.Title); //标题
                    Fields.Add("Content", data.Content); //内容
                    Fields.Add("Url", data.Url); //跳转Url
                    Fields.Add("Summary", data.Summary); //简介
                    Fields.Add("PushFlag", data.PushFlag); //推送标记
                    Fields.Add("Remark", data.Remark); //备注
                    Fields.Add("Status", 1);
                    int Id = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Add("MsgPersonal", Fields, 0);
                    AddSysLog(data.Id.ToString(), "MsgPersonal", "add");
                    bsdb.SaveChanges();
                    SetRedis(Id);
                    MsgNotRead msg = RedisDbconn.Instance.Get<MsgNotRead>("MsgNotRead:" + codeData.UserId) ?? new MsgNotRead();
                    msg.PersonalCount += 1;
                    RedisDbconn.Instance.Set("MsgNotRead:" + codeData.UserId, msg);
                }
                else
                {
                    Models.Users user = db.Users.FirstOrDefault(m => m.Id == codeData.UserId);
                    if (user != null)
                    {
                        string ParentNav = function.CheckNull(user.ParentNav).Trim(',').Replace(",,", ",");
                        if (!string.IsNullOrEmpty(ParentNav))
                        {
                            string[] ParentNavList = ParentNav.Split(',');
                            foreach (string IdString in ParentNavList)
                            {
                                int uid = int.Parse(IdString);
                                Dictionary<string, object> Fields = new Dictionary<string, object>();
                                Fields.Add("UserId", uid); //创客
                                Fields.Add("MsgType", data.MsgType); //消息类型
                                Fields.Add("BgPic", data.BgPic); //背景图片
                                Fields.Add("Title", data.Title); //标题
                                Fields.Add("Content", data.Content); //内容
                                Fields.Add("Url", data.Url); //跳转Url
                                Fields.Add("Summary", data.Summary); //简介
                                Fields.Add("PushFlag", data.PushFlag); //推送标记
                                Fields.Add("Remark", data.Remark); //备注
                                Fields.Add("Status", 1);
                                int Id = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Add("MsgPersonal", Fields, 0);
                                AddSysLog(data.Id.ToString(), "MsgPersonal", "add");
                                bsdb.SaveChanges();
                                SetRedis(Id);

                                MsgNotRead msg = RedisDbconn.Instance.Get<MsgNotRead>("MsgNotRead:" + uid) ?? new MsgNotRead();
                                msg.PersonalCount += 1;
                                RedisDbconn.Instance.Set("MsgNotRead:" + uid, msg);
                            }
                        }
                    }
                }
            }
            
            return "success";
        }

        #endregion

        #region 修改个人消息

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


            MsgPersonal editData = db.MsgPersonal.FirstOrDefault(m => m.Id == Id) ?? new MsgPersonal();
            ViewBag.data = editData;
            return View();
        }

        #endregion

        #region 修改个人消息

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

            Fields.Add("TemplateId", data.TemplateId); //模板
            Fields.Add("UserId", data.UserId); //创客
            Fields.Add("MsgType", data.MsgType); //消息类型
            Fields.Add("BgPic", data.BgPic); //背景图片
            Fields.Add("Title", data.Title); //标题
            Fields.Add("Content", data.Content); //内容
            Fields.Add("Url", data.Url); //跳转Url
            Fields.Add("Summary", data.Summary); //简介
            Fields.Add("PushFlag", data.PushFlag); //推送标记
            Fields.Add("ReadFlag", data.ReadFlag); //已读标记
            Fields.Add("PushParam", data.PushParam); //推送参数
            Fields.Add("ExtendColumn", data.ExtendColumn); //扩展字段
            Fields.Add("Remark", data.Remark); //备注

            Fields.Add("SeoTitle", data.SeoTitle);
            Fields.Add("SeoKeyword", data.SeoKeyword);
            Fields.Add("SeoDescription", data.SeoDescription);
            new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("MsgPersonal", Fields, data.Id);
            AddSysLog(data.Id.ToString(), "MsgPersonal", "update");
            bsdb.SaveChanges();
            SetRedis(data.Id, "edit");

            return "success";
        }

        #endregion

        #region 删除个人消息信息

        /// <summary>
        /// 删除个人消息信息
        /// </summary>
        /// <returns></returns>
        public string Delete(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "MsgPersonal", "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("MsgPersonal", Fields, id);
            }
            bsdb.SaveChanges();

            return "success";
        }

        #endregion

        #region 推送

        /// <summary>
        /// 推送
        /// </summary>
        /// <returns></returns>
        public string Push(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "MsgPersonal", "Push");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("PushFlag", 1);
                new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("MsgPersonal", Fields, id);
            }
            bsdb.SaveChanges();
            return "success";
        }

        #endregion

        #region 开启

        /// <summary>
        /// 开启
        /// </summary>
        /// <returns></returns>
        public string Open(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "MsgPersonal", "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("MsgPersonal", Fields, id);
            }
            bsdb.SaveChanges();
            return "success";
        }

        #endregion

        #region 关闭

        /// <summary>
        /// 关闭
        /// </summary>
        /// <returns></returns>
        public string Close(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "MsgPersonal", "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("MsgPersonal", Fields, id);
            }
            bsdb.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("MsgPersonal", Sort, Id);

            AddSysLog(Id.ToString(), "MsgPersonal", "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.MsgPersonal.Add(new MsgPersonal()
                {
                    CreateDate = DateTime.Now,
                    UpdateDate = DateTime.Now,

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

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(MsgPersonal data)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("CreateDate", "3"); //时间
            Fields.Add("Title", "2"); //标题
            Fields.Add("ReadFlag", "1"); //已读标记

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("MsgPersonal", Fields, "Id desc", "0", 1, 20000, "", "", false);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                dic["TemplateId"] = RelationClass.GetMsgTemplateInfo(int.Parse(dic["TemplateId"].ToString()));
                dic["ReadFlagName"] = dic["ReadFlag"].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", "MsgPersonal", "ExportExcel");
            return Json(result);
        }

        #endregion



        #region 设置缓存

        private void SetRedis(int Id, string EditType = "add")
        {
            MsgPersonal msg = db.MsgPersonal.FirstOrDefault(m => m.Id == Id);
            if (msg != null)
            {
                if (EditType == "add")
                {
                    RedisDbconn.Instance.AddList("MsgPersonalList:" + msg.UserId, Id);
                }
                RedisDbconn.Instance.Set("MsgPersonal:" + Id, msg);
            }
        }

        #endregion
    }
}