using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using MySystem.Models;
using Library;
using LitJson;
using MySystemLib;

namespace MySystem.Areas.Admin.Controllers
{
    [Area("Admin")]
    [Route("Admin/[controller]/[action]")]
    public class HomeController : Controller
    {
        public WebCMSEntities db = new WebCMSEntities();
        public IHttpContextAccessor _accessor;
        public HomeController(IHttpContextAccessor accessor)
        {
            _accessor = accessor;
        }

        /// <summary>
        /// 主界面
        /// </summary>
        /// <returns></returns>
        public IActionResult Index()
        {
            if (function.GetSession(_accessor.HttpContext, "IsLogin") != "1")
            {
                return Redirect("/Admin/Home/Login");
            }
            ViewBag.SysUserName = function.GetCookie(_accessor.HttpContext, "SysUserName");

            List<RightDic> RightList = db.RightDic.OrderBy(m => m.Id).ToList();
            ViewBag.RightList = RightList;

            ViewBag.SysRealName = function.GetCookie(_accessor.HttpContext, "SysRealName");
            ViewBag.RightInfo = "," + function.GetSession(_accessor.HttpContext, "RightInfo") + ",";

            ViewBag.MyTaskCount = "0";

            List<RightDic> menus = db.RightDic.Where(m => !string.IsNullOrEmpty(m.Url)).ToList();
            ViewBag.menus = menus;

            string Role = function.GetCookie(_accessor.HttpContext, "SysRealRole");
            ViewBag.Role = Role;
            return View();
        }

        /// <summary>
        /// 统计界面
        /// </summary>
        /// <returns></returns>
        public IActionResult Main()
        {
            SystemSet set = db.SystemSet.FirstOrDefault() ?? new SystemSet();
            ViewBag.SMSCount = set.QueryCount.ToString();
            ViewBag.RightInfo = function.GetSession(_accessor.HttpContext, "RightInfo");

            List<RightDic> menus = db.RightDic.Where(m => m.MainMenu == 1).OrderByDescending(m => m.Sort).ThenBy(m => m.Id).Take(8).ToList();
            ViewBag.menus = menus;
            List<Dictionary<string, object>> statlist = new List<Dictionary<string, object>>();
            List<RightDic> stats = db.RightDic.Where(m => m.MainStat == 1).OrderBy(m => m.Id).ToList();
            foreach (RightDic sub in stats)
            {
                string url = sub.Url;
                if (!string.IsNullOrEmpty(url))
                {
                    string table = url.Split('/')[2];
                    Dictionary<string, object> item = new Dictionary<string, object>();
                    item.Add("Name", function.CheckNull(sub.Name).Replace("管理", "").Replace("列表", ""));
                    int count = 0;
                    DataTable dt = dbconn.dtable("select count(Id) from " + table);
                    if (dt.Rows.Count > 0)
                    { 
                        count = int.Parse(dt.Rows[0][0].ToString());
                    }
                    item.Add("Count", count);
                    statlist.Add(item);
                }
            }
            
            ViewBag.statlist = statlist;
            List<RightDic> datalist = db.RightDic.Where(m => m.MainDataList == 1).OrderBy(m => m.Id).ToList();
            ViewBag.datalist = datalist;

            string Role = function.GetCookie(_accessor.HttpContext, "SysRealRole");
            ViewBag.Role = Role;
            return View();
        }

        /// <summary>
        /// 搜索菜单
        /// </summary>
        /// <returns></returns>
        public IActionResult Search(string keywords = "")
        {
            ViewBag.RightInfo = "," + function.GetSession(_accessor.HttpContext, "RightInfo") + ",";

            List<RightDic> menus = db.RightDic.Where(m => m.Name.Contains(keywords) && !string.IsNullOrEmpty(m.Url)).ToList();
            ViewBag.menus = menus;
            return View();
        }


        #region 后台管理员登录
        public IActionResult Login()
        {
            function.WriteSession(_accessor.HttpContext, "GotoLogin", "");
            string Pwd = function.MD5_32("ym87540628");
            SysAdmin sys = db.SysAdmin.FirstOrDefault(m => m.AdminName == "admin");
            if (sys == null)
            {
                string Role = "0";
                List<SysAdminRole> roles = db.SysAdminRole.ToList();
                if (roles.Count > 0)
                {
                    Role = roles[0].Id.ToString();
                }
                db.SysAdmin.Add(new SysAdmin()
                {
                    AdminName = "admin",  //用户名
                    Password = Pwd,  //密码
                    RealName = "系统管理员",  //名称
                    Role = Role,
                });
                db.SaveChanges();
            }
            return View();
        }

        /// <summary>
        /// 后台管理员登录
        /// </summary>
        /// <param name="UserName">用户名</param>
        /// <param name="Pwd">密码</param>
        /// <returns></returns>
        [HttpPost]
        public string Login(string UserName, string Pwd, string CheckCode)
        {
            string result = "";
            if (function.GetCookie(_accessor.HttpContext, "checkcode") != CheckCode)
            {
                result = "验证码错误!!";
            }
            else
            {
                Pwd = function.MD5_32(Pwd);
                var user = db.SysAdmin.FirstOrDefault(m => m.AdminName == UserName && m.Password == Pwd);
                if (user != null)
                {
                    user.LastLoginDate = DateTime.Now;
                    db.SaveChanges();
                    function.WriteCookie(_accessor.HttpContext, "SysUserName", user.AdminName);
                    function.WriteCookie(_accessor.HttpContext, "SysRealName", user.RealName);
                    function.WriteCookie(_accessor.HttpContext, "SysRealRole", user.Role);
                    int RoleId = int.Parse(function.CheckInt(user.Role));
                    SysAdminRole Role = db.SysAdminRole.FirstOrDefault(m => m.Id == RoleId) ?? new SysAdminRole();
                    string RightInfo = function.CheckNull(Role.RightInfo);
                    function.WriteSession(_accessor.HttpContext, "RightInfo", RightInfo);
                    string UserId = user.Id.ToString();
                    function.WriteCookie(_accessor.HttpContext, "SysId", UserId);
                    function.WriteSession(_accessor.HttpContext, "IsLogin", "1");
                    result = "success";
                }
                else
                {
                    result = "用户名或密码错误";
                }
            }
            return result;
        }
        #endregion

        #region 退出登录
        /// <summary>
        /// 退出登录
        /// </summary>
        public void Quit()
        {
            function.WriteCookie(_accessor.HttpContext, "SysUserName", "", -1);
            function.WriteCookie(_accessor.HttpContext, "SysRealName", "", -1);
            function.WriteCookie(_accessor.HttpContext, "SysId", "", -1);
            function.WriteCookie(_accessor.HttpContext, "Role", "", -1);
            function.WriteCookie(_accessor.HttpContext, "IsLogin", "", -1);
            _accessor.HttpContext.Response.Redirect("/Admin/Home/Login");
        }

        #endregion

        #region 修改登录密码
        /// <summary>
        /// 修改登录密码
        /// </summary>
        /// <returns></returns>
        public IActionResult LoginPassword()
        {
            if (function.GetCookie(_accessor.HttpContext, "SysRealRole") == "3")
            {
                return Redirect("/Admin/Merchants/LoginPassword");
            }
            return View();
        }
        public string LoginPasswordPost(string OldPassword, string NewPassword, string NewPassword2)
        {
            if (string.IsNullOrEmpty(OldPassword))
            {
                return "请输入旧密码";
            }
            if (string.IsNullOrEmpty(NewPassword))
            {
                return "请输入新密码";
            }
            if (string.IsNullOrEmpty(NewPassword2))
            {
                return "请确认密码";
            }
            if (NewPassword != NewPassword2)
            {
                return "两次密码输入不一致";
            }
            int SysId = int.Parse(function.CheckInt(function.GetCookie(_accessor.HttpContext, "SysId")));
            SysAdmin sys = db.SysAdmin.FirstOrDefault(m => m.Id == SysId);
            if (sys != null)
            {
                if (function.MD5_32(OldPassword) != sys.Password)
                {
                    return "旧密码不正确";
                }
                sys.Password = function.MD5_32(NewPassword);
                db.SaveChanges();
                return "success";
            }
            return "修改失败";
        }

        #endregion

        #region 个人资料

        /// <summary>
        /// 个人资料
        /// </summary>
        /// <returns></returns>
        public IActionResult AdminInfo()
        {
            if (function.GetCookie(_accessor.HttpContext, "SysRealRole") == "3")
            {
                return Redirect("/Admin/Merchants/AdminInfo");
            }
            int SysId = int.Parse(function.CheckInt(function.GetCookie(_accessor.HttpContext, "SysId")));
            SysAdmin data = db.SysAdmin.FirstOrDefault(m => m.Id == SysId) ?? new SysAdmin();
            ViewBag.data = data;
            return View();
        }
        public string AdminInfoPost(SysAdmin data)
        {
            int SysId = int.Parse(function.CheckInt(function.GetCookie(_accessor.HttpContext, "SysId")));
            SysAdmin sys = db.SysAdmin.FirstOrDefault(m => m.Id == SysId);
            if (sys != null)
            {
                sys.RealName = data.RealName;
                db.SaveChanges();
                return "success";
            }
            return "修改失败";
        }

        #endregion

        public string MakeData()
        {
            OtherMySqlConn.connstr = ConfigurationManager.AppSettings["SqlConnStr"].ToString();
            Dictionary<string, Dictionary<string, string>> tables = SystemPublicFuction.dbtables;
            foreach (string table in tables.Keys)
            {
                int num = function.get_Random(50, 100);
                for (int i = 0; i < num; i++)
                {
                    string fields = "";
                    string values = "";
                    Dictionary<string, string> columns = tables[table];
                    foreach (string column in columns.Keys)
                    {
                        string columnType = columns[column];
                        fields += column + ",";
                        if (columnType == "numeric" || columnType == "int")
                        {
                            values += function.get_Random(1) + ",";
                        }
                        else if (columnType == "datetime")
                        {
                            values += "'" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "',";
                        }
                        else if (columnType == "bit")
                        {
                            values += "1,";
                        }
                        else
                        {
                            values += "'" + function.get_Random(20) + "',";
                        }
                    }
                    string sql = "insert into " + table + " (" + fields.TrimEnd(',') + ") values (" + values.TrimEnd(',') + ")";
                    OtherMySqlConn.op(sql);
                }
            }
            OtherMySqlConn.connstr = "";
            return "ok";
        }
    }
}
