using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Authorization;

using System.Web;
using MySystem.MainModels;
using LitJson;
using Library;

namespace MySystem.Areas.Api.Controllers.v1
{
    [Area("Api")]
    [Route("Api/v1/[controller]/[action]")]
    public class MsgPlacardController : BaseController
    {
        public MsgPlacardController(IHttpContextAccessor accessor, ILogger<BaseController> logger, IOptions<Setting> setting) : base(accessor, logger, setting)
        {
        }



        #region 商户-未读消息数
        [Authorize]
        public JsonResult NotRead(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = NotReadDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        public Dictionary<string, object> NotReadDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            string UserIdString = data["UserId"].ToString();
            int UserId = int.Parse(function.CheckInt(data["UserId"].ToString()));
            int PlacardCount = maindb.MsgPlacard.Where(m => m.Status > -1).Count() - maindb.MsgPlacardRead.Where(m => m.UserId == UserIdString).Count();
            int PersonalCount = maindb.MsgPersonal.Where(m => m.UserId == UserId && m.ReadFlag == 0).Count();
            if (PlacardCount < 0) PlacardCount = 0;
            Obj.Add("PlacardCount", PlacardCount); //系统消息
            Obj.Add("PersonalCount", PersonalCount); //个人消息
            return Obj;
        }
        #endregion



        #region 商户-系统消息列表
        [Authorize]
        public JsonResult List(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            List<Dictionary<string, object>> dataList = ListDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = dataList });
        }
        public List<Dictionary<string, object>> ListDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            string UserId = data["UserId"].ToString(); //创客Id
            int PageSize = int.Parse(function.CheckInt(data["PageSize"].ToString()));
            int PageNum = int.Parse(function.CheckInt(data["PageNum"].ToString()));
            List<Dictionary<string, object>> dataList = new List<Dictionary<string, object>>();
            IQueryable<MsgPlacard> query = maindb.MsgPlacard.Where(m => m.Status > -1).OrderByDescending(m => m.Id);
            if (PageNum == 1)
            {
                query = query.Take(PageSize);
            }
            else
            {
                int skipNum = PageSize * (PageNum - 1);
                query = query.Skip(skipNum).Take(PageSize);
            }
            foreach (MsgPlacard subdata in query.ToList())
            {
                Dictionary<string, object> curData = new Dictionary<string, object>();
                curData.Add("Title", subdata.Title); //标题
                curData.Add("Summary", subdata.Summary); //简介
                curData.Add("BgPic", !string.IsNullOrEmpty(subdata.BgPic) ? DefaultPic(subdata.BgPic) : ""); //背景图片
                curData.Add("Url", subdata.Url); //跳转Url
                curData.Add("Id", subdata.Id); //Id
                curData.Add("MsgType", subdata.MsgType);
                if (subdata.Title.Contains("补录成功通知"))
                {
                    curData.Add("CreateDate", subdata.CreateDate == null ? "" : subdata.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss")); //CreateDate
                }
                else
                {
                    curData.Add("CreateDate", subdata.CreateDate == null ? "" : subdata.CreateDate.Value.ToString("yyyy-MM-dd")); //CreateDate
                }
                curData.Add("ReadFlag", maindb.MsgPlacardRead.Any(m => m.PlacardId == subdata.Id && m.UserId == UserId) ? 1 : 0); //已读标记
                dataList.Add(curData);
            }
            return dataList;
        }
        #endregion



        #region 商户-系统消息已读
        [Authorize]
        public JsonResult Read(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = ReadDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        public AppResultJson ReadDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            string UserId = data["UserId"].ToString();
            bool check = maindb.MsgPlacardRead.Any(m => m.PlacardId == Id && m.UserId == UserId);
            if(!check)
            {
                MsgPlacardRead read = maindb.MsgPlacardRead.Add(new MsgPlacardRead()
                {
                    CreateDate = DateTime.Now,
                    UserId = UserId,
                    PlacardId = Id,
                    ReadFlag = 1,
                }).Entity;
                maindb.SaveChanges();
            }
            return new AppResultJson() { Status = "1", Info = "", Data = Obj };
        }
        #endregion



        #region 商户-系统消息详情
        [Authorize]
        public JsonResult Detail(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = DetailDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        public Dictionary<string, object> DetailDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            MsgPlacard query = maindb.MsgPlacard.FirstOrDefault(m => m.Id == Id) ?? new MsgPlacard();
            Obj.Add("Title", query.Title); //标题
            Obj.Add("Content", CheckContentImage(query.Content)); //内容
            return Obj;
        }
        #endregion



        #region 检查签名是否合法，合法返回1，不合法返回提示信息

        /// <summary>
        /// 检查签名是否合法，合法返回1，不合法返回提示信息
        /// </summary>
        /// <param name="value">请求的参数(json字符串)</param>
        /// <param name="signField">要签名的字段</param>
        /// <returns></returns>
        private string CheckSign(string value, string[] signField)
        {
            JsonData json = JsonMapper.ToObject(value);
            Dictionary<string, string> dic = new Dictionary<string, string>();
            for (int i = 0; i < signField.Length; i++)
            {
                dic.Add(signField[i], json[signField[i]].ToString());
            }
            string sign = json["sign"].ToString(); //客户端签名字符串
            return new Sign().sign(dic, sign);
        }

        #endregion

    }
}
