/*
 * 活动信息
 */

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

            return View();
        }

        #endregion

        #region 根据条件查询活动信息列表

        /// <summary>
        /// 活动信息列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(ActivityInfo data, string ActTypeSelect, string IsTopSelect, int page = 1, int limit = 30)
        {

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

            Fields.Add("ActName", "1"); //活动名称
            Fields.Add("EffectStartDate", "3"); //活动开始时间


            string condition = " and Status>-1";
            //活动类型
            if (!string.IsNullOrEmpty(ActTypeSelect))
            {
                condition += " and ActType=" + ActTypeSelect;
            }
            //是否置顶
            if (!string.IsNullOrEmpty(IsTopSelect))
            {
                condition += " and IsTop=" + IsTopSelect;
            }


            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("ActivityInfo", 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 ActType = int.Parse(dic["ActType"].ToString());
                if (ActType == 0) dic["ActType"] = "html页面";
                if (ActType == 1) dic["ActType"] = "指定url";
                //产品类型
                dic["BrandId"] = RelationClass.GetKqProductBrandList(dic["BrandId"].ToString());
                //是否置顶
                int IsTop = int.Parse(dic["IsTop"].ToString());
                if (IsTop == 1) dic["IsTop"] = "是";
                if (IsTop == 0) dic["IsTop"] = "否";

            }
            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(ActivityInfo data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();

            Fields.Add("ActCode", "ACT_" + DateTime.Now.ToString("yyyyMMddHHmmss")); //活动编号
            Fields.Add("ActType", data.ActType); //活动类型
            Fields.Add("ActName", data.ActName); //活动名称
            Fields.Add("BrandId", data.BrandId); //产品类型
            Fields.Add("LimitTopBuddy", data.LimitTopBuddy); //顶级创客设置
            Fields.Add("IsTop", data.IsTop); //是否置顶
            Fields.Add("EffectStartDate", data.EffectStartDate); //活动开始时间
            Fields.Add("EffectEndDate", data.EffectEndDate); //活动结束时间
            Fields.Add("ActReferUrl", data.ActReferUrl); //链接地址
            Fields.Add("ActBanner", data.ActBanner); //活动Banner图片
            Fields.Add("ActContent", data.ActContent); //活动详情
            Fields.Add("Remark", data.Remark); //备注
            Fields.Add("CreateMan", SysUserName);
            int Id = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Add("ActivityInfo", Fields, 0);
            AddSysLog(Id.ToString(), "ActivityInfo", "add");
            db.SaveChanges();

            SetRedis(Id, true);

            return "success";
        }

        #endregion

        #region 修改活动信息

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


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

        #endregion

        #region 修改活动信息

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

            Fields.Add("ActType", data.ActType); //活动类型
            Fields.Add("ActName", data.ActName); //活动名称
            Fields.Add("BrandId", data.BrandId); //产品类型
            Fields.Add("LimitTopBuddy", data.LimitTopBuddy); //顶级创客设置
            Fields.Add("IsTop", data.IsTop); //是否置顶
            Fields.Add("EffectStartDate", data.EffectStartDate); //活动开始时间
            Fields.Add("EffectEndDate", data.EffectEndDate); //活动结束时间
            Fields.Add("ActReferUrl", data.ActReferUrl); //链接地址
            Fields.Add("ActBanner", data.ActBanner); //活动Banner图片
            Fields.Add("ActContent", data.ActContent); //活动详情
            Fields.Add("Remark", data.Remark); //备注
            Fields.Add("UpdateMan", SysUserName);
            new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("ActivityInfo", Fields, data.Id);
            AddSysLog(data.Id.ToString(), "ActivityInfo", "update");
            db.SaveChanges();

            SetRedis(data.Id, false);

            return "success";
        }

        #endregion
        
        #region 详情

        public IActionResult Detail(string right, int Id = 0)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;

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

        #endregion

        #region 删除活动信息信息

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

            SetRedis(0, true);

            return "success";
        }

        #endregion

        #region 开启

        /// <summary>
        /// 开启
        /// </summary>
        /// <returns></returns>
        public string Open(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "ActivityInfo", "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("ActivityInfo", 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, "ActivityInfo", "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("ActivityInfo", 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("ActivityInfo", Sort, Id);

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

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

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(ActivityInfo data, string ActTypeSelect, string IsTopSelect)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("ActName", "1"); //活动名称
            Fields.Add("EffectStartDate", "3"); //活动开始时间


            string condition = " and Status>-1";
            //活动类型
            if (!string.IsNullOrEmpty(ActTypeSelect))
            {
                condition += " and ActType=" + ActTypeSelect;
            }
            //是否置顶
            if (!string.IsNullOrEmpty(IsTopSelect))
            {
                condition += " and IsTop=" + IsTopSelect;
            }


            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("ActivityInfo", 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 ActType = int.Parse(dic["ActType"].ToString());
                if (ActType == 0) dic["ActType"] = "html页面";
                if (ActType == 1) dic["ActType"] = "指定url";
                //产品类型
                dic["BrandId"] = RelationClass.GetKqProductBrandList(dic["BrandId"].ToString());
                //是否置顶
                int IsTop = int.Parse(dic["IsTop"].ToString());
                if (IsTop == 1) dic["IsTop"] = "是";
                if (IsTop == 0) dic["IsTop"] = "否";

            }

            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", "ActivityInfo", "ExportExcel");
            return Json(result);
        }

        #endregion



        #region 设置缓存

        private void SetRedis(int Id, bool All)
        {
            if (All)
            {
                RedisDbconn.Instance.Clear("ActivityInfoList");
                var msgs = db.ActivityInfo.Select(m => new { m.Id, m.Status, m.Sort }).Where(m => m.Status > -1).OrderByDescending(m => m.Sort).ThenByDescending(m => m.Id).ToList();
                foreach (var msg in msgs)
                {
                    RedisDbconn.Instance.AddList("ActivityInfoList", msg.Id);
                }
            }
            if (Id > 0)
            {
                ActivityInfo edit = db.ActivityInfo.FirstOrDefault(m => m.Id == Id);
                if (edit != null)
                {
                    RedisDbconn.Instance.Set("ActivityInfo:" + Id, edit);
                }
            }
        }

        #endregion
    }
}
