/*
 * 创客预设职级
 */

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

            return View();
        }

        #endregion

        #region 根据条件查询创客预设职级列表

        /// <summary>
        /// 创客预设职级列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(UserRankWhite data, string MakerCode, string RealName, string StatusSelect, string TopMakerCode, string UpdateDateData, int page = 1, int limit = 30)
        {

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

            string condition = " and Status>-1";
            //创客编号
            if (!string.IsNullOrEmpty(MakerCode))
            {
                condition += " and UserId in (select UserId from UserForMakerCode where MakerCode='" + MakerCode + "')";
            }
            //创客名称
            if (!string.IsNullOrEmpty(RealName))
            {
                condition += " and UserId in (select UserId from UserForRealName where RealName='" + RealName + "')";
            }
            //状态
            if (!string.IsNullOrEmpty(StatusSelect))
            {
                condition += " and Status=" + StatusSelect;
            }
            //顶级创客编号
            if (!string.IsNullOrEmpty(TopMakerCode))
            {
                var topUser = db.Users.FirstOrDefault(m => m.MakerCode == TopMakerCode) ?? new Users();
                var childIds = "";
                // if (!string.IsNullOrEmpty(topUser.ParentNav))
                // {
                //     string[] ParentNavList = topUser.ParentNav.Trim(',').Replace(",,", ",").Split(',');
                //     var topUserId = "," + topUser.Id + ",";
                //     if (ParentNavList.Length > 1)
                //     {
                //         var childUser = db.Users.Where(m => m.ParentNav.Contains(topUserId)).ToList();
                //         foreach (var item in childUser)
                //         {
                //             childIds = item.Id + ",";
                //         }
                //         childIds = childIds.TrimEnd(',');
                //     }
                // }
                var topUserId = "," + topUser.Id + ",";
                var childUser = db.Users.Where(m => m.ParentNav.Contains(topUserId)).ToList();
                foreach (var item in childUser)
                {
                    childIds += item.Id + ",";
                }
                childIds = childIds.TrimEnd(',');
                condition += " and UserId in (" + childIds + ")";
            }
            //到期时间
            if (!string.IsNullOrEmpty(UpdateDateData))
            {
                string[] datelist = UpdateDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                string start = datelist[0];
                string end = datelist[1];
                condition += " and UpdateDate>='" + start + " 00:00:00' and UpdateDate<='" + end + " 23:59:59'";
            }

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("UserRankWhite", 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["Rank"] = RelationClass.GetUserLevelSetInfo(int.Parse(dic["Rank"].ToString()));
                int UserId = int.Parse(dic["UserId"].ToString());
                Users user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                dic["MakerCode"] = user.MakerCode;
                dic["RealName"] = user.RealName;
                if (user.ParentUserId > 0)
                {
                    Users puser = db.Users.FirstOrDefault(m => m.Id == user.ParentUserId) ?? new Users();
                    dic["ParentMakerCode"] = puser.MakerCode;
                    dic["ParentRealName"] = puser.RealName;
                }
                if (!string.IsNullOrEmpty(user.ParentNav))
                {
                    string[] ParentNavList = user.ParentNav.Trim(',').Replace(",,", ",").Split(',');
                    if (ParentNavList.Length > 1)
                    {
                        int TopId = int.Parse(user.ParentNav.Trim(',').Replace(",,", ",").Split(',')[1]);
                        Users tuser = db.Users.FirstOrDefault(m => m.Id == TopId) ?? new Users();
                        dic["TopMakerCode"] = tuser.MakerCode;
                        dic["TopRealName"] = tuser.RealName;
                    }
                    else
                    {
                        int TopId = int.Parse(user.ParentNav.Trim(',').Replace(",,", ",").Split(',')[0]);
                        Users tuser = db.Users.FirstOrDefault(m => m.Id == TopId) ?? new Users();
                        dic["TopMakerCode"] = tuser.MakerCode;
                        dic["TopRealName"] = tuser.RealName;
                    }
                }
                dic["Status"] = dic["Status"].ToString() == "1" ? "有效" : "无效";
            }
            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(UserRankWhite data, string MakerCode)
        {
            bool check = db.UserForMakerCode.Any(m => m.MakerCode == MakerCode);
            if (!check)
            {
                return "创客编号不存在";
            }
            Dictionary<string, object> Fields = new Dictionary<string, object>();
            UserForMakerCode user = db.UserForMakerCode.FirstOrDefault(m => m.MakerCode == MakerCode) ?? new UserForMakerCode();
            check = db.UserRankWhite.Any(m => m.UserId == user.UserId);
            if (check)
            {
                return "已添加过此创客编号，请勿重复添加";
            }
            Fields.Add("UserId", user.UserId);
            Fields.Add("Rank", data.Rank);
            Fields.Add("Status", data.Status);

            Fields.Add("SeoTitle", data.SeoTitle);
            Fields.Add("SeoKeyword", data.SeoKeyword);
            Fields.Add("SeoDescription", data.SeoDescription);
            int Id = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Add("UserRankWhite", Fields, 0);
            AddSysLog(data.Id.ToString(), "UserRankWhite", "add");
            db.SaveChanges();

            UserRank rank = RedisDbconn.Instance.Get<UserRank>("UserRank:" + user.UserId);
            if (rank != null)
            {
                rank.WhiteRank = data.Rank;
                RedisDbconn.Instance.Set("UserRank:" + user.UserId, rank);
            }

            return "success";
        }

        #endregion

        #region 修改创客预设职级

        /// <summary>
        /// 增加或修改创客预设职级信息
        /// </summary>
        /// <returns></returns>
        public IActionResult Edit(string right, int Id = 0)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;

            UserRankWhite editData = db.UserRankWhite.FirstOrDefault(m => m.Id == Id) ?? new UserRankWhite();
            ViewBag.data = editData;

            Users user = db.Users.FirstOrDefault(m => m.Id == editData.UserId) ?? new Users();
            ViewBag.MakerCode = user.MakerCode;
            ViewBag.RealName = user.RealName;

            return View();
        }

        #endregion

        #region 修改创客预设职级

        /// <summary>
        /// 增加或修改创客预设职级信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Edit(UserRankWhite data, string MakerCode)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();
            Fields.Add("Rank", data.Rank);
            Fields.Add("Status", data.Status);
            new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("UserRankWhite", Fields, data.Id);
            AddSysLog(data.Id.ToString(), "UserRankWhite", "update");
            db.SaveChanges();

            UserRankWhite white = db.UserRankWhite.FirstOrDefault(m => m.Id == data.Id);
            if (white != null)
            {
                UserRank rank = RedisDbconn.Instance.Get<UserRank>("UserRank:" + white.UserId);
                if (rank != null)
                {
                    rank.WhiteRank = data.Rank;
                    RedisDbconn.Instance.Set("UserRank:" + white.UserId, rank);
                }
            }

            return "success";
        }

        #endregion

        #region 删除创客预设职级信息

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

            return "success";
        }

        #endregion

        #region 开启

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

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

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

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(UserRankWhite data, string MakerCode, string RealName, string StatusSelect, string TopMakerCode, string UpdateDateData)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();

            string condition = " and Status>-1";
            //创客编号
            if (!string.IsNullOrEmpty(MakerCode))
            {
                condition += " and UserId in (select UserId from UserForMakerCode where MakerCode='" + MakerCode + "')";
            }
            //创客名称
            if (!string.IsNullOrEmpty(RealName))
            {
                condition += " and UserId in (select UserId from UserForRealName where RealName='" + RealName + "')";
            }
            //状态
            if (!string.IsNullOrEmpty(StatusSelect))
            {
                condition += " and Status=" + StatusSelect;
            }
            //顶级创客编号
            if (!string.IsNullOrEmpty(TopMakerCode))
            {
                var topUser = db.Users.FirstOrDefault(m => m.MakerCode == TopMakerCode) ?? new Users();
                var childIds = "";
                // if (!string.IsNullOrEmpty(topUser.ParentNav))
                // {
                //     string[] ParentNavList = topUser.ParentNav.Trim(',').Replace(",,", ",").Split(',');
                //     var topUserId = "," + topUser.Id + ",";
                //     if (ParentNavList.Length > 1)
                //     {
                //         var childUser = db.Users.Where(m => m.ParentNav.Contains(topUserId)).ToList();
                //         foreach (var item in childUser)
                //         {
                //             childIds = item.Id + ",";
                //         }
                //         childIds = childIds.TrimEnd(',');
                //     }
                // }
                var topUserId = "," + topUser.Id + ",";
                var childUser = db.Users.Where(m => m.ParentNav.Contains(topUserId)).ToList();
                foreach (var item in childUser)
                {
                    childIds += item.Id + ",";
                }
                childIds = childIds.TrimEnd(',');
                condition += " and UserId in (" + childIds + ")";
            }
            //到期时间
            if (!string.IsNullOrEmpty(UpdateDateData))
            {
                string[] datelist = UpdateDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                string start = datelist[0];
                string end = datelist[1];
                condition += " and UpdateDate>='" + start + " 00:00:00' and UpdateDate<='" + end + " 23:59:59'";
            }

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("UserRankWhite", Fields, "Id desc", "0", 1, 20000, condition, "UserId,Rank,Status,CreateDate", false);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                dic["Rank"] = RelationClass.GetUserLevelSetInfo(int.Parse(dic["Rank"].ToString()));
                int UserId = int.Parse(dic["UserId"].ToString());
                Users user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                dic["MakerCode"] = user.MakerCode;
                dic["RealName"] = user.RealName;
                if (user.ParentUserId > 0)
                {
                    Users puser = db.Users.FirstOrDefault(m => m.Id == user.ParentUserId) ?? new Users();
                    dic["ParentMakerCode"] = puser.MakerCode;
                    dic["ParentRealName"] = puser.RealName;
                }
                if (!string.IsNullOrEmpty(user.ParentNav))
                {
                    int TopId = int.Parse(user.ParentNav.Trim(',').Replace(",,", ",").Split(',')[0]);
                    Users tuser = db.Users.FirstOrDefault(m => m.Id == TopId) ?? new Users();
                    dic["TopMakerCode"] = tuser.MakerCode;
                    dic["TopRealName"] = tuser.RealName;
                }
                dic["Status"] = dic["Status"].ToString() == "1" ? "有效" : "无效";
                dic.Remove("UserId");
            }

            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>();
            ReturnFields.Add("MakerCode", "创客编号");
            ReturnFields.Add("RealName", "创客姓名");
            ReturnFields.Add("ParentMakerCode", "上级创客编号");
            ReturnFields.Add("ParentRealName", "上级创客名称");
            ReturnFields.Add("TopMakerCode", "顶级创客编号");
            ReturnFields.Add("TopRealName", "顶级创客名称");
            ReturnFields.Add("Rank", "等级名称");
            ReturnFields.Add("Status", "有效状态");
            ReturnFields.Add("CreateDate", "创建时间");
            ReturnFields.Add("UpdateDate", "过期时间");
            result.Add("Fields", ReturnFields);
            AddSysLog("0", "UserRankWhite", "ExportExcel");
            return Json(result);
        }

        #endregion



        #region 快捷导出Excel
        public IActionResult QuickExportExcel(string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;

            return View();
        }

        [HttpPost]
        public string QuickExportExcelDo(string MakerCode, string RealName, string StatusSelect, string TopMakerCode, string UpdateDateData)
        {

            string condition = " where 1=1 and a.Status>-1";
            //创客编号
            if (!string.IsNullOrEmpty(MakerCode))
            {
                condition += " and a.UserId in (select UserId from UserForMakerCode where MakerCode='" + MakerCode + "')";
            }
            //创客名称
            if (!string.IsNullOrEmpty(RealName))
            {
                condition += " and a.UserId in (select UserId from UserForRealName where RealName='" + RealName + "')";
            }
            //状态
            if (!string.IsNullOrEmpty(StatusSelect))
            {
                condition += " and a.Status=" + StatusSelect;
            }
            //顶级创客编号
            if (!string.IsNullOrEmpty(TopMakerCode))
            {
                var topUser = db.Users.FirstOrDefault(m => m.MakerCode == TopMakerCode) ?? new Users();
                var childIds = "";
                // if (!string.IsNullOrEmpty(topUser.ParentNav))
                // {
                //     string[] ParentNavList = topUser.ParentNav.Trim(',').Replace(",,", ",").Split(',');
                //     var topUserId = "," + topUser.Id + ",";
                //     if (ParentNavList.Length > 1)
                //     {
                //         var childUser = db.Users.Where(m => m.ParentNav.Contains(topUserId)).ToList();
                //         foreach (var item in childUser)
                //         {
                //             childIds = item.Id + ",";
                //         }
                //         childIds = childIds.TrimEnd(',');
                //     }
                // }
                var topUserId = "," + topUser.Id + ",";
                var childUser = db.Users.Where(m => m.ParentNav.Contains(topUserId)).ToList();
                foreach (var item in childUser)
                {
                    childIds += item.Id + ",";
                }
                childIds = childIds.TrimEnd(',');
                condition += " and a.UserId in (" + childIds + ")";
            }
            //到期时间
            if (!string.IsNullOrEmpty(UpdateDateData))
            {
                string[] datelist = UpdateDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                string start = datelist[0];
                string end = datelist[1];
                condition += " and a.UpdateDate>='" + start + " 00:00:00' and a.UpdateDate<='" + end + " 23:59:59'";
            }
            var Sql = "SELECT b.MakerCode '创客编号',b.RealName '创客姓名',b.UserLevel '创客职级',c.MakerCode '上级创客编号',c.RealName ' 上级创客姓名',d.MakerCode '顶级创客编号',d.RealName '顶级创客姓名',DATE_FORMAT(a.CreateDate,'%Y-%m-%d %H:%i:%s') '创建时间',DATE_FORMAT(a.UpdateDate,'%Y-%m-%d %H:%i:%s') '到期时间',a.Rank '预设职级' FROM UserRankWhite a LEFT JOIN Users b ON a.UserId=b.Id LEFT JOIN Users c ON b.ParentUserId=c.Id LEFT JOIN Users d ON SUBSTRING_INDEX(SUBSTRING_INDEX(b.ParentNav,',',4),',',-1)=d.Id" + condition;
            var sysAdmin = bsdb.SysAdmin.FirstOrDefault(m => m.AdminName == SysUserName && m.Status > -1);
            var FileName = "创客预设职级记录" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string SendData = "{\"Operater\":\"" + sysAdmin.Id + "\",\"SqlString\":\"" + Sql + "\",\"FileName\":\"" + FileName + "\",\"MaxCount\":\"0\"}";
            RedisDbconn.Instance.AddList("ExportQueue", SendData);
            return "success";
        }
        #endregion

    }
}
