/*
 * 分类设置
 */

using System;
using System.Web;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MySystem.BsModels;
using Library;
using LitJson;
using MySystemLib;

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

        #region 分类设置列表

        /// <summary>
        /// 根据条件查询分类设置列表
        /// </summary>
        /// <returns></returns>
        public IActionResult Index(Col data, string right, string CurColId)
        {
            ViewBag.SysUserName = SysUserName;
            ViewBag.RightInfo = RightInfo;
            ViewBag.CurColId = CurColId;
            ViewBag.right = right;

            string Condition = "";
            Condition += "ColName:\"" + data.ColName + "\",";
            Condition += "ColEnName:\"" + data.ColEnName + "\",";

            if (!string.IsNullOrEmpty(Condition))
            {
                Condition = Condition.TrimEnd(',');
                Condition = ", where: {" + Condition + "}";
            }
            ViewBag.Condition = Condition;
            return View();
        }

        #endregion

        #region 根据条件查询分类设置列表

        /// <summary>
        /// 分类设置列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(Col data, string CurColId, int page = 1, int limit = 30)
        {

            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("ColName", "2"); //名称
            Fields.Add("ColEnName", "2"); //英文名
            string condition = " and ColId like '" + CurColId + "%'";
            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.BsTables).IndexData("Col", Fields, "Sort", "False", page, limit, condition);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            List<Dictionary<string, object>> result = new List<Dictionary<string, object>>();
            foreach (Dictionary<string, object> dic in diclist)
            {
                string ColId = dic["ColId"].ToString();
                string UrlString = dic["Url"].ToString();
                if (string.IsNullOrEmpty(UrlString))
                {
                    UrlString = "";
                    for (int i = ColId.Length; i >= 6; i -= 3)
                    {
                        string subcolid = ColId.Substring(0, i);
                        Col query = bsdb.Col.FirstOrDefault(m => m.ColId == subcolid);
                        if (query != null)
                        {
                            UrlString = "/" + query.ColEnName + UrlString;
                        }
                    }
                }
                Dictionary<string, object> item = new Dictionary<string, object>();
                item.Add("id", int.Parse(dic["Id"].ToString()));
                item.Add("pid", int.Parse(dic["ParentId"].ToString()));
                item.Add("title", dic["ColName"].ToString());
                item.Add("url", UrlString);
                item.Add("ColId", ColId);
                item.Add("Sort", int.Parse(dic["Sort"].ToString()));
                item.Add("Status", dic["Status"].ToString() == "1" ? "正常" : "关闭");
                result.Add(item);
            }
            return Json(result);
        }

        #endregion

        #region 增加分类设置

        /// <summary>
        /// 增加或修改分类设置信息
        /// </summary>
        /// <returns></returns>
        public IActionResult Add(string right, string PColId, string CurColId)
        {
            ViewBag.SysUserName = SysUserName;
            ViewBag.right = right;
            ViewBag.CurColId = CurColId;
            if (string.IsNullOrEmpty(PColId))
            {
                PColId = "001";
            }
            ViewBag.PColId = PColId;
            return View();
        }

        #endregion

        #region 增加分类设置

        /// <summary>
        /// 增加或修改分类设置信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Add(Col col, string PColId = "", string CurColId = "")
        {
            //构造ColId
            if (string.IsNullOrEmpty(PColId) && string.IsNullOrEmpty(CurColId))
            {
                return "请选择上级栏目！";
            }
            string code = "";
            int len = PColId.Length + 3;
            Col model = bsdb.Col.Where(m => m.ColId.StartsWith(PColId) && m.ColId.Length == len).OrderByDescending(m => m.ColId).FirstOrDefault();
            if (model != null)
            {
                string CurCode = model.ColId;
                int num = int.Parse(CurCode.Substring(CurCode.Length - 3)) + 1;
                code = num.ToString();
                for (int i = 0; i < 3 - num.ToString().Length; i++)
                {
                    code = "0" + code;
                }
                code = PColId + code;
            }
            else
            {
                code = PColId + "001";
            }

            //获取父级数据
            Col parentcol = bsdb.Col.FirstOrDefault(m => m.ColId == PColId) ?? new Col();
            //获取父级ID
            int ParentId = 0;
            if (!string.IsNullOrEmpty(PColId))
            {
                ParentId = parentcol.Id;
            }

            //获取英文名，为空则自动翻译
            string EnName = col.ColEnName;
            if (string.IsNullOrEmpty(EnName))
            {
                EnName = new PublicFunction().TranslateZHToEn(col.ColName);
                EnName = EnName.Replace(" ", "").Replace("'", "").ToLower();
            }
            //判断中文名是否存在
            string CheckCol = code.Substring(0, 3);
            Col check = bsdb.Col.FirstOrDefault(m => m.ColId.StartsWith(CheckCol) && m.ColName == col.ColName);
            if (check != null)
            {
                return "中文名已存在";
            }
            Col add = bsdb.Col.Add(new Col()
            {
                ColId = code,
                Sort = col.Sort,
                ColName = col.ColName,
                ColEnName = EnName,
                ColPicPath = col.ColPicPath,
                ColDetail = col.ColDetail,  //简介
                Recommend = col.Recommend,
                Url = col.Url,
                Contents = col.Contents,
                CreateDate = DateTime.Now,
                SeoTitle = col.SeoTitle,
                SeoKeyword = col.SeoKeyword,
                SeoDescription = col.SeoDescription,
                ParentId = ParentId,
                Status = 1,
            }).Entity;
            bsdb.SaveChanges();

            AddSysLog(add.Id.ToString(), "Col", "add");

            SetRedis(PColId);

            return "success";
        }

        #endregion

        #region 修改分类设置

        /// <summary>
        /// 增加或修改分类设置信息
        /// </summary>
        /// <returns></returns>
        public IActionResult Edit(string right, string ColId, string PColId, string CurColId, int Id = 0)
        {
            ViewBag.SysUserName = SysUserName;
            ViewBag.right = right;
            ViewBag.CurColId = CurColId;
            if (string.IsNullOrEmpty(PColId))
            {
                PColId = "001";
            }
            ViewBag.PColId = PColId;

            Col editData = bsdb.Col.FirstOrDefault(m => m.ColId == ColId) ?? new Col();
            ViewBag.data = editData;
            return View();
        }

        #endregion

        #region 修改分类设置

        /// <summary>
        /// 增加或修改分类设置信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Edit(Col col, string OldEnName, string PColId = "", string CurColId = "")
        {
            //构造ColId
            string code = "";
            int len = PColId.Length + 3;
            Col model = bsdb.Col.Where(m => m.ColId.StartsWith(PColId) && m.ColId.Length == len).OrderByDescending(m => m.ColId).FirstOrDefault();
            if (model != null)
            {
                string CurCode = model.ColId;
                int num = int.Parse(CurCode.Substring(CurCode.Length - 3)) + 1;
                code = num.ToString();
                for (int i = 0; i < 3 - num.ToString().Length; i++)
                {
                    code = "0" + code;
                }
                code = PColId + code;
            }
            else
            {
                code = PColId + "001";
            }
            //获取英文名，为空则自动翻译
            string EnName = col.ColEnName;
            if (string.IsNullOrEmpty(EnName))
            {
                EnName = new PublicFunction().TranslateZHToEn(col.ColName);
                EnName = EnName.Replace(" ", "").Replace("'", "").ToLower();
            }
            // //判断英文名是否存在
            // string CheckCol = PColId.Substring(0, 3);
            // Col check = bsdb.Col.FirstOrDefault(m => m.ColId.StartsWith(CheckCol) && m.ColEnName == EnName && m.ColEnName != OldEnName);
            // if (check != null)
            // {
            //     return "英文名已存在";
            // }
            Col editData = bsdb.Col.FirstOrDefault(c => c.ColId == col.ColId);
            if (editData != null)
            {
                //修改时，上级有变更，则同步更新同步更新数据表相关的ColId
                if (PColId != col.ColId.Substring(0, PColId.Length))
                {
                    if (col.ColId.Substring(0, 3) == "001")
                    {
                        dbconn.op("update Articles set ColId='" + code + "' where ColId='" + col.ColId + "'");
                    }
                    else if (col.ColId.Substring(0, 3) == "003")
                    {
                        dbconn.op("update Advertisment set ColId='" + code + "' where ColId='" + col.ColId + "'");
                    }
                    editData.ColId = code;
                    if (!string.IsNullOrEmpty(PColId))
                    {
                        Col parentcol = bsdb.Col.FirstOrDefault(m => m.ColId == PColId) ?? new Col();
                        editData.ParentId = parentcol.Id;
                    }
                }
                editData.ColName = col.ColName;
                editData.Sort = col.Sort;
                editData.ColEnName = EnName;
                editData.ColPicPath = col.ColPicPath;
                editData.ColDetail = col.ColDetail;   //简介
                editData.Recommend = col.Recommend;
                editData.Url = col.Url;
                editData.Contents = col.Contents;
                editData.UpdateDate = DateTime.Now;
                editData.SeoTitle = col.SeoTitle;
                editData.SeoKeyword = col.SeoKeyword;
                editData.SeoDescription = col.SeoDescription;

                bsdb.SaveChanges();
            }
            else
            {
                int ParentId = 0;
                if (!string.IsNullOrEmpty(PColId))
                {
                    Col parentcol = bsdb.Col.FirstOrDefault(m => m.ColId == PColId) ?? new Col();
                    ParentId = parentcol.Id;
                }
                Col add = bsdb.Col.Add(new Col()
                {
                    ColId = col.ColId,
                    ColName = col.ColName,
                    ColEnName = EnName,
                    ColPicPath = col.ColPicPath,
                    ColDetail = col.ColDetail,  //简介
                    Recommend = col.Recommend,
                    Url = col.Url,
                    Contents = col.Contents,
                    CreateDate = DateTime.Now,
                    SeoTitle = col.SeoTitle,
                    SeoKeyword = col.SeoKeyword,
                    SeoDescription = col.SeoDescription,
                    ParentId = ParentId,
                    Status = 1,
                }).Entity;
                bsdb.SaveChanges();
            }

            AddSysLog(col.Id.ToString(), "Col", "update");

            SetRedis(PColId);

            return "success";
        }

        #endregion

        #region 删除分类设置信息

        /// <summary>
        /// 删除分类设置信息
        /// </summary>
        /// <returns></returns>
        public string Delete(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            List<string> ColIds = new List<string>();
            AddSysLog(Id, "Col", "del");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                Col item = bsdb.Col.FirstOrDefault(m => m.Id == id) ?? new Col();
                if (!ColIds.Contains(item.ColId))
                {
                    ColIds.Add(item.ColId);
                }
                var check = bsdb.Col.Any(m => m.ParentId == item.Id);
                if (check)
                {
                    var cols = bsdb.Col.Where(m => m.ParentId == item.Id).ToList();
                    foreach (var col in cols)
                    {
                        var dcol = cols.FirstOrDefault(m => m.Id == col.Id);
                        int colId = int.Parse(dcol.Id.ToString());
                        new AdminContentOther(_accessor.HttpContext, PublicFunction.BsTables).Delete("Col", colId);
                    }
                }
                var studys = db.SchoolMakerStudy.Where(m => m.SeoKeyword.StartsWith(item.ColId)).ToList();
                foreach (var items in studys)
                {
                    var study = studys.FirstOrDefault(m => m.Id == items.Id);
                    study.SeoKeyword = null;
                }
                new AdminContentOther(_accessor.HttpContext, PublicFunction.BsTables).Delete("Col", id);
            }
            db.SaveChanges();
            bsdb.SaveChanges();

            foreach (string CurColId in ColIds)
            {
                SetRedis(CurColId);
            }

            return "success";
        }

        #endregion

        #region 开启

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

            AddSysLog(Id.ToString(), "Col", "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];

                bsdb.Col.Add(new Col()
                {
                    CreateDate = DateTime.Now,
                    UpdateDate = DateTime.Now,

                });
                bsdb.SaveChanges();
            }
            AddSysLog("0", "Col", "Import");
            return "success";
        }
        #endregion

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(Col data)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("ColName", "2"); //名称
            Fields.Add("ColEnName", "2"); //英文名

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.BsTables).IndexData("Col", Fields, "Id desc", "False", 1, 20000, "", "", false);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;

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

        #endregion




        #region 设置缓存

        private void SetRedis(string ColId)
        {
            int len = ColId.Length;
            List<Col> query = bsdb.Col.Where(m => m.ColId.StartsWith(ColId) && m.ColId.Length > len && m.Status == 1).OrderByDescending(m => m.Sort).ThenBy(m => m.Id).ToList();
            RedisDbconn.Instance.Clear("Col:" + ColId);
            RedisDbconn.Instance.AddList("Col:" + ColId, query.ToArray());
        }

        #endregion
    }
}
