/*
 * 分类设置
 */

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.Models;
using Library;
using LitJson;
using MySystemLib;

namespace MySystem.Areas.Admin.Controllers
{
    [Area("Admin")]
    [Route("Admin/[controller]/[action]")]
    public class MerchantColController : BaseController
    {
        public MerchantColController(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(MerchantCol data, string right, string MerchantId)
        {
            ViewBag.SysUserName = SysUserName;
            ViewBag.RightInfo = RightInfo;
            ViewBag.MerchantId = MerchantId;
            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(MerchantCol data, string MerchantId, 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 MerchantId=" + MerchantId;
            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("MerchantCol", Fields, "ColId asc", "False", page, limit, condition);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                string ColId = dic["ColId"].ToString();
                string kg = "";
                for (int i = 1; i < ColId.Length / 3; i++)
                {
                    kg += "　　";
                }
                dic["ColName"] = kg + dic["ColName"].ToString();
                dic["Status"] = dic["Status"].ToString() == "1" ? "正常" : "关闭";
            }
            return Json(obj);
        }

        #endregion

        #region 增加分类设置

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

        #endregion

        #region 增加分类设置

        /// <summary>
        /// 增加或修改分类设置信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Add(MerchantCol col, string PColId, int MerchantId = 0)
        {
			//构造ColId
			string code = "";
			PColId = function.CheckNull(PColId);
			int len = PColId.Length + 3;
            MerchantCol model = db.MerchantCol.Where(m => m.MerchantId == MerchantId && 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";
            }

            //获取父级数据
            MerchantCol parentcol = db.MerchantCol.FirstOrDefault(m => m.MerchantId == MerchantId && m.ColId == PColId) ?? new MerchantCol();
            //获取父级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();
            }
            //判断中文名是否存在
            MerchantCol check = db.MerchantCol.FirstOrDefault(m => m.MerchantId == MerchantId && m.ColName == col.ColName);
            if (check != null)
            {
                return "中文名已存在";
            }
            //构造英文名路径，用于url地址
            string ColEnNav = EnName;
            if (!string.IsNullOrEmpty(PColId))
            {
                string ColIdNav = PColId;
                while (ColIdNav.Length >= 6)
                {
                    MerchantCol pcol = db.MerchantCol.FirstOrDefault(m => m.MerchantId == MerchantId && m.ColId == ColIdNav) ?? new MerchantCol();
                    ColEnNav = pcol.ColEnName + "/" + ColEnNav;
                    ColIdNav = ColIdNav.Substring(0, ColIdNav.Length - 3);
                }
            }
            MerchantCol add = db.MerchantCol.Add(new MerchantCol()
            {
                MerchantId = MerchantId,
                ColId = code,
                ColName = col.ColName,
                ColEnName = EnName,
                ColPicPath = col.ColPicPath,
                ColDetail = col.ColDetail,  //简介
                Recommend = col.Recommend,
                CreateDate = DateTime.Now,
                SeoTitle = col.SeoTitle,
                SeoKeyword = col.SeoKeyword,
                SeoDescription = col.SeoDescription,
                ParentId = ParentId,
                Status = 1,
            }).Entity;
            db.SaveChanges();
            

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

            return "success";
        }

        #endregion

        #region 修改分类设置

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

            MerchantCol editData = db.MerchantCol.FirstOrDefault(m => m.MerchantId == MerchantId && m.ColId == ColId) ?? new MerchantCol();
            ViewBag.data = editData;
            return View();
        }

        #endregion

        #region 修改分类设置

        /// <summary>
        /// 增加或修改分类设置信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Edit(MerchantCol col, string OldEnName, string PColId, int MerchantId = 0)
        {
            //构造ColId
            string code = "";
			PColId = function.CheckNull(PColId);
			int len = PColId.Length + 3;
            MerchantCol model = db.MerchantCol.Where(m => m.MerchantId == MerchantId && 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();
            }
            // //判断英文名是否存在
            // MerchantCol check = db.MerchantCol.FirstOrDefault(m => m.MerchantId == MerchantId && m.ColEnName == EnName && m.ColEnName != OldEnName);
            // if (check != null)
            // {
            //     return "英文名已存在";
            // }
            //构造英文名路径，用于url地址
            string ColEnNav = EnName;
            if (!string.IsNullOrEmpty(PColId))
            {
                string ColIdNav = PColId;
                while (ColIdNav.Length >= 6)
                {
                    MerchantCol pcol = db.MerchantCol.FirstOrDefault(m => m.MerchantId == MerchantId && m.ColId == ColIdNav) ?? new MerchantCol();
                    ColEnNav = pcol.ColEnName + "/" + ColEnNav;
                    ColIdNav = ColIdNav.Substring(0, ColIdNav.Length - 3);
                }
            }
            MerchantCol editData = db.MerchantCol.FirstOrDefault(m => m.MerchantId == MerchantId && m.ColId == col.ColId);
            if (editData != null)
            {
                //修改时，上级有变更，则同步更新同步更新数据表相关的ColId
                if (PColId != col.ColId.Substring(0, PColId.Length))
                {
                    editData.ColId = code;
                    if (!string.IsNullOrEmpty(PColId))
                    {
                        MerchantCol parentcol = db.MerchantCol.FirstOrDefault(m => m.MerchantId == MerchantId && m.ColId == PColId) ?? new MerchantCol();
                        editData.ParentId = parentcol.Id;
                    }
                }
                editData.ColName = col.ColName;
                editData.ColEnName = EnName;
                editData.ColPicPath = col.ColPicPath;
                editData.ColDetail = col.ColDetail;   //简介
                editData.Recommend = col.Recommend;
                editData.UpdateDate = DateTime.Now;
                editData.SeoTitle = col.SeoTitle;
                editData.SeoKeyword = col.SeoKeyword;
                editData.SeoDescription = col.SeoDescription;
                
                db.SaveChanges();
            }
            else
            {
                int ParentId = 0;
                if (!string.IsNullOrEmpty(PColId))
                {
                    MerchantCol parentcol = db.MerchantCol.FirstOrDefault(m => m.MerchantId == MerchantId && m.ColId == PColId) ?? new MerchantCol();
                    ParentId = parentcol.Id;
                }
                MerchantCol add = db.MerchantCol.Add(new MerchantCol()
                {
                    MerchantId = MerchantId,
                    ColId = col.ColId,
                    ColName = col.ColName,
                    ColEnName = EnName,
                    ColPicPath = col.ColPicPath,
                    ColDetail = col.ColDetail,  //简介
                    Recommend = col.Recommend,
                    CreateDate = DateTime.Now,
                    SeoTitle = col.SeoTitle,
                    SeoKeyword = col.SeoKeyword,
                    SeoDescription = col.SeoDescription,
                    ParentId = ParentId,
                    Status = 1,
                }).Entity;
                db.SaveChanges();
            }

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

            return "success";
        }

        #endregion

        #region 删除分类设置信息

        /// <summary>
        /// 删除分类设置信息
        /// </summary>
        /// <returns></returns>
        public string Delete(string Id)
        {
            if (Id.Contains(","))
            {
                string[] idlist = Id.Split(new char[] { ',' });
                AddSysLog(Id, "MerchantCol", "del");
                foreach (string subid in idlist)
                {
                    int id = int.Parse(subid);
                    new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Delete("MerchantCol", id);
                }
                db.SaveChanges();
            }
            else
            {
                int id = int.Parse(Id);
                MerchantCol del = db.MerchantCol.FirstOrDefault(m => m.Id == id);
                if (del != null)
                {
                    int checkcount = db.MerchantCol.Count(m => m.MerchantId == del.MerchantId && m.ColId.StartsWith(del.ColId));
                    if (checkcount > 1)
                    {
                        return "选中包含子栏目，请使用批量删除";
                    }
                    db.MerchantCol.Remove(del);
                    db.SaveChanges();
                }
            }
            return "success";
        }

        #endregion

        #region 开启

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

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

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

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(MerchantCol data, int MerchantId = 0)
        {
            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.MainTables).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", "MerchantCol", "ExportExcel");
            return Json(result);
        }

        #endregion


        public JsonResult GetSelect(int MerchantId)
        {
            List<MerchantCol> list = db.MerchantCol.Where(m => m.MerchantId == MerchantId).OrderBy(m => m.ColId).ToList();
            foreach (MerchantCol sub in list)
            {
                string ColId = sub.ColId;
                string kg = "";
                for (int i = 1; i < ColId.Length / 3; i++)
                {
                    kg += "　　";
                }
                sub.ColName = kg + sub.ColName;
            }
            return Json(list);
        }
    }
}
