using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using OneMore.Models;
using OneMore.Areas.Admin.Models;
using System.Data.SqlClient;
using System.Data;
using System.ComponentModel;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Microsoft.EntityFrameworkCore;
using System.Text.RegularExpressions;
using System.DrawingCore;
using System.IO;
using System.DrawingCore.Imaging;

/// <summary>
/// 本框架所有后台操作都放在这里面
/// 
/// </summary>

namespace OneMore.Areas.Admin.Controllers
{
    [Description("系统主后台")]
    public class FoController : Controller
    {
        private readonly mydbContext db;
        public FoController(mydbContext context)
        {
            db = context;
        }

        //登录页面
        public IActionResult Index()
        {
            //如果已经登录，则跳转到后台界面
            var mems = HttpContext.Session.GetObj<Memlogin>("mems");
            if (mems != null)
            {
                return RedirectToAction("Platform");
            }

            return View();
        }

        [HttpPost]
        public IActionResult Index(IFormCollection s)
        {
            if (s["yzm"]!="1983") { //这里方便演示，正式发布时去掉
                var yzm = HttpContext.Session.GetString("yzm");
                if (yzm != s["yzm"])
                {
                    ViewBag.err = "<script>alert('验证码错误！')</script>";
                    return View();
                }
            }

            var mem = Dbfohelper.SqlQuery<Memlogin>(db, "select top 1 pid,lgm,xm,lx,zuids from Admin_mem where lgm=@lgm and pwd=@pwd",
                new SqlParameter[]{
                    new SqlParameter("@lgm",s["username"].ToString()),
                    new SqlParameter("@pwd",s["password"].ToString())
                }
                );


            if (mem.Count() == 0)
            {
                //{AFTER}增加登录次数限制
                ViewBag.err = "<script>alert('用户名或密码错误！')</script>";

                return View();
            }
            else
            {
                var mems = new Memlogin();
                mems.ustop = new List<Mqxlist>();

                var allqx = new List<Mqxlist>();
                var delqx = new List<Mqxlist>();

                var gp = mem.First();
                mems.pid = gp.pid;
                mems.lgm = gp.lgm;
                mems.xm = gp.xm;
                mems.lx = gp.lx;
                mems.zuids = "," + gp.zuids + ",";


                //读取权限 +用户权限 -禁用的权限 =组里的权限
                var Uqx = Dbfohelper.SqlQuery<Qxlist>(db, "select Distinct c,a,v,sta from Admin_qxs where charindex(','+scid+',','" + mems.zuids + "')>0 or scid='" + mems.pid + "' ");

                Mqxlist m_liqx;
                foreach (Qxlist p in Uqx)
                {
                    m_liqx = new Mqxlist();

                    m_liqx.c = p.c;
                    m_liqx.a = p.a;
                    m_liqx.v = p.v;

                    switch (p.sta) {
                        case "+":
                            allqx.Add(m_liqx);
                            break;
                        case "=":
                            allqx.Add(m_liqx);
                            break;
                        case "-":
                            delqx.Add(m_liqx);
                            break;
                    }
                }

                var temp = allqx.Where(x => !delqx.Where(y => y.c == x.c && y.a == x.a).Any()).ToList();

                allqx.Clear();
                allqx.AddRange(temp);


                //遍历权限
                var Sysallqx = GlistCAmenus.GetALLMenuByReflection();
                foreach (var SgetM in Sysallqx)
                {
                    foreach (var SgetA in SgetM.MenuMx)
                    {
                        m_liqx = new Mqxlist();
                        m_liqx.c = SgetM.MenuAC;
                        m_liqx.a = SgetA.ActionCode;
                        m_liqx.v = SgetA.ActioniCode;
                        m_liqx.s = SgetA.ActionSuper ? "1" : "0";

                        mems.ustop.Add(m_liqx);
                    }
                }

                temp = mems.ustop.Where(x => !allqx.Where(y => y.c == x.c && y.a == x.a && x.s == "0").Any()).ToList();
                mems.ustop.Clear();
                mems.ustop.AddRange(temp);


                HttpContext.Session.SetObj("mems", mems);



                return RedirectToAction("Platform");

            }

        }

        // 没有授权
        public IActionResult noPemit()
        {
            return View();
        }
        //退出登录
        public IActionResult Logout()
        {
            HttpContext.Session.Clear();
            return View("Index");
        }

        [Descriper(Name = "账户首页", Memo = "登录后的账户首页")]
        public IActionResult MyIndex()
        {
            return View();
        }

        //后台菜单自动生成
        public string GetMenuTreesLi(string jb, List<Amenu> Treels,List<Qxlist> Mqxs,bool ck)
        {//遍历后台菜单 jb 级别，Treels 数据列表

            var TreeLis = "";
            var Mtree = Treels.Where(fo => fo.mjb == jb).OrderBy(fo => fo.px).ToList();

            //var surl = "";

            foreach (var item in Mtree)
            {
                //判断此用户是否有此菜单权限
                if (ck)
                {
                    if (Mqxs.Where(q => q.v == item.muid).Count() == 0) { continue; }
                }

                if (Treels.Where(s => s.mjb == item.muid).Count() > 0)
                {
                    TreeLis = TreeLis + "<li>";
                    TreeLis = TreeLis + "<a>" + item.mname + "</a>";
                    TreeLis = TreeLis + "<ul>" + GetMenuTreesLi(item.muid, Treels, Mqxs,ck) + "</ul>";
                    TreeLis = TreeLis + "</li>";

                }
                else
                {
                    TreeLis = TreeLis + "<li>";
                    if (item.mlx == "action")
                    {
                        TreeLis = TreeLis + "<a href=\"" + Url.RouteUrl(item.mroute, new { Controller = item.mcontroller, Action = item.maction }) + "\"  target=\"navTab\" external=\"true\" rel=\"" +item.muid + "\" />" + item.mname + "</a>";
                    }
                    else
                    {
                        TreeLis = TreeLis + "<a href=\"" + item.murl + "\"  target=\"navTab\" external=\"true\" rel=\"" + item.muid + "\" />" + item.mname + "</a>";
                    }

                    TreeLis = TreeLis + "</li>";

                }

            }

            return TreeLis;
        }


        [Descriper(Name = "后台界面", Memo = "登录后的主界面")]
        public IActionResult Platform()
        {
            var Mtree = db.Amenus.ToList();
            //获取用户的菜单权限
            var p = HttpContext.Session.GetObj<Memlogin>("mems");
            var pmenuqx = db.Qxlists.Where(q => q.scid == p.pid && q.sta == "m").ToList();

            var ck = true;
            if(p.lx=="S" || p.lx == "A") { ck = false; }

            if (Mtree.Count() > 0) { 
            ViewBag.MenuTreeLis = GetMenuTreesLi("$", Mtree, pmenuqx, ck);
            }

            return View();
        }


        #region 管理菜单配置
        //●皈依佛·皈依法·皈依僧●皈依佛·皈依法·皈依僧●皈依佛·皈依法·皈依僧●皈依佛·皈依法·皈依僧●皈依佛·皈依法·皈依僧●
        [Descriper(Name = "管理菜单配置", Memo = "由超级管理员配置菜单", Super = true)]
        public IActionResult sys_menu()
        {
            var Mtree = db.Amenus.ToList();
            var Ado = new AdminWorks();
            ViewBag.MenuTreeNodes = Ado.GetMenuTrees("$", Mtree);

            

            return View();
        }

        [Descriper(Name = "编辑管理菜单", Memo = "由超级管理员操作", Super = true)]
        public IActionResult sys_menu_edit(string muid)
        {
            var pm = db.Amenus.FirstOrDefault(x => x.muid == muid);

            if (pm != null) { return View(pm); } else
            {
                return View(new Amenu());
            }

        }

        [HttpPost]
        [Descriper(Name = "编辑管理菜单.执行", Memo = "由超级管理员操作", Super = true)]
        public IActionResult sys_menu_edit(IFormCollection mda)
        {
            if (mda["mname"] == "")
            {
                ViewBag.result0 = "{\"sta\":\"no\",\"pid\":\"1\",\"myid\":\"2\",\"myname\":\"菜单名不可为空！\"}";
                return View("result0");
            }

            var getdata = new Amenu();
            getdata.mjb = mda["mjb"];
            getdata.mname = mda["mname"];
            getdata.mlx = mda["mlx"];
            getdata.mroute = mda["mroute"];
            getdata.mcontroller = mda["mcontroller"];
            getdata.maction = mda["maction"];
            getdata.murl = mda["murl"];

            if (mda["dolx"] == "add")
            {
                var myid = db.Amenus.OrderByDescending(sl => sl.Id).FirstOrDefault();
                var myidval = "1";
                if (myid != null) {
                    myidval = Convert.ToString(Convert.ToInt32(myid.muid) + 1);
                }
                getdata.muid = myidval;
                getdata.px = Convert.ToInt32(myidval) * 10;
                db.Amenus.Add(getdata);
                db.SaveChanges();


                //var Mtree = db.Amenus.ToList();
                //var Ado = new AdminWorks();//从数据库获取最新全部node，加载出来。

                ViewBag.result0 = "{\"lx\":\"add\",\"sta\":\"ok\",\"pid\":\"" + getdata.mjb + "\",\"myid\":\"" + myidval + "\",\"myname\":\"" + getdata.mname + "\"}";//,\"treejson\":[" + Ado.GetMenuTrees("$", Mtree) + "]

                return View("result0");
            }

            if (mda["dolx"] == "edit")
            {
                var edmenu = db.Amenus.FirstOrDefault(x => x.muid == (string)mda["doid"]);

                edmenu.mname = getdata.mname;
                edmenu.mlx = getdata.mlx;
                edmenu.mroute = getdata.mroute;
                edmenu.mcontroller = getdata.mcontroller;
                edmenu.maction = getdata.maction;
                edmenu.murl = getdata.murl;

                db.SaveChanges();


                ViewBag.result0 = "{\"lx\":\"edit\",\"sta\":\"ok\",\"pid\":\"" + getdata.mjb + "\",\"myid\":\"" + mda["doid"] + "\",\"myname\":\"" + getdata.mname + "\"}";

                return View("result0");
            }


            return View("result0");

        }

        [HttpGet]
        [Descriper(Name = "编辑管理菜单.排序", Memo = "由超级管理员操作", Super = true)]
        public IActionResult sys_menu_paixu(string Tjson)
        {
            Tjson = Tjson.Replace(",]", "]");
            Tjson = Tjson.Replace(",end", "");
            Tjson = Tjson.Replace("end", "");

            Tjson = Tjson.Replace("children:[", "");
            Tjson = Tjson.Replace("]", "");
            Tjson = Tjson.Replace("{", "");
            Tjson = Tjson.Replace("}", "");
            Tjson = Tjson.Replace(",id", "},{id");
            Tjson = "[{" + Tjson + "}]";

            var Awk = new AdminWorks();
            var tallpx = Awk.GetMenuTreespx(Tjson);


            var edmenu = new Amenu();
            foreach (var item in tallpx)
            {
                edmenu = db.Amenus.FirstOrDefault(x => x.muid == item.mtid);

                if (edmenu != null)
                {
                    edmenu.px = item.mtpx;
                }

            }
            db.SaveChanges();



            //ViewBag.result0 = jo.;

            return View("result0");
        }

        [Descriper(Name = "删除管理菜单", Memo = "由超级管理员操作", Super = true)]
        public IActionResult sys_menu_del(string muid)
        {
            var Awk = new AdminWorks();

            var Mtree = db.Amenus.ToList();

            var getjson = Awk.GetMenuTrees(muid, Mtree);

            getjson = getjson.Replace(",]", "]");
            getjson = getjson.Replace(",end", "");
            getjson = getjson.Replace("end", "");

            getjson = getjson.Replace(",\"open\": \"true\"", "}");
            getjson = getjson.Replace("\"childOuter\": false,", "");
            getjson = getjson.Replace("\"children\":[", "");
            getjson = getjson.Replace("]},", ",");
            getjson = getjson.Replace("]}", "");

            getjson = "[" + getjson + "]";

            var tallpx = Awk.GetMenuTreespx(getjson);

            var edmenu = new Amenu();
            edmenu = db.Amenus.FirstOrDefault(x => x.muid == muid);
            db.Amenus.Remove(edmenu);
            foreach (var item in tallpx)
            {
                edmenu = db.Amenus.FirstOrDefault(x => x.muid == item.mtid);

                db.Amenus.Remove(edmenu);

            }
            db.SaveChanges();


            return View("result0");

        }

        #endregion
        //南无阿弥陀佛·南无阿弥陀佛·南无阿弥陀佛·南无阿弥陀佛·南无阿弥陀佛·南无阿弥陀佛·南无阿弥陀佛·南无阿弥陀佛

        #region 权限分组管理
        //●皈依佛·皈依法·皈依僧●皈依佛·皈依法·皈依僧●皈依佛·皈依法·皈依僧●皈依佛·皈依法·皈依僧●皈依佛·皈依法·皈依僧●
        [Descriper(Name = "权限分组管理", Memo = "对系统权限进行分组，以便设置权限时脉络清晰", Super = true)]
        public IActionResult sys_qxgroup()
        {
            return View();
        }

        //权限分组管理·分组列表
        public IActionResult sys_qxgroup_list()
        {
            var zlist = db.QAzus.Where(h => h.lx == "s").OrderBy(h => h.zm).ToList();

            return PartialView(zlist);
        }

        //权限分组管理·已分组的权限
        public IActionResult sys_qxgroup_p1(string zuid, string Canck)
        {
            var hadqx = GlistCAmenus.GetALLhadqx(db.Qxlists.Where(h => h.sta == "s" && h.scid == zuid).ToList());
            if (Canck == "yes") { ViewBag.ck = true; } else { ViewBag.ck = false; }

            return PartialView(hadqx);
        }

        //权限分组管理·未分组的权限
        public IActionResult sys_qxgroup_p2(string Canck)
        {
            var weiqx = GlistCAmenus.GetALLweiqx(db.Qxlists.Where(h => h.sta == "s").ToList());
            if (Canck == "yes") { ViewBag.ck = true; } else { ViewBag.ck = false; }

            return PartialView(weiqx);
        }

        //编辑分组·读出数据
        public IActionResult sys_qxgroup_edit(string zuid)
        {
            var pm = db.QAzus.FirstOrDefault(x => x.zuid == zuid);

            if (pm != null) { return View(pm); }
            else
            {
                return View(new QAzu());
            }

        }

        [HttpPost]
        [Descriper(Name = "编辑分组·提交", Memo = "由超级管理员操作", Super = true)]
        public IActionResult sys_qxgroup_edit(IFormCollection zda)
        {
            if (zda["zname"] == "")
            {
                ViewBag.result0 = "{\"sta\":\"no\",\"pid\":\"1\",\"myid\":\"2\",\"myname\":\"组名不可为空！\"}";
                return View("result0");
            }

            var getdata = new QAzu();
            getdata.zm = zda["zname"];
            getdata.lx = "s";
            getdata.px = 1;
            getdata.sm = "系统权限规划组";

            if (zda["dolx"] == "add")
            {
                var myid = db.QAzus.OrderByDescending(sl => sl.Id).FirstOrDefault();
                var myidval = "1";
                if (myid != null)
                {
                    myidval = Convert.ToString(Convert.ToInt32(myid.zuid) + 1);
                }
                getdata.zuid = myidval;
                getdata.px = Convert.ToInt32(myidval) * 10;
                db.QAzus.Add(getdata);


                //这里添加提交过来的权限到权限明细表
                var getqxmx = new Qxlist();
                foreach (var item in zda["ckadd"]) {
                    getqxmx = new Qxlist();
                    var getitem = Regex.Split(item.ToString(), "。", RegexOptions.IgnoreCase);
                    getqxmx.scid = myidval;
                    getqxmx.c = getitem[0];
                    getqxmx.a = getitem[1];
                    getqxmx.v = getitem[2];
                    getqxmx.sta = "s";

                    db.Qxlists.Add(getqxmx);
                }

                db.SaveChanges();

                ViewBag.result0 = "{\"lx\":\"add\",\"sta\":\"ok\",\"pid\":\"0\",\"myid\":\"" + myidval + "\",\"myname\":\"" + getdata.zm + "\"}";

                return View("result0");
            }

            if (zda["dolx"] == "edit")
            {
                var edzu = db.QAzus.FirstOrDefault(x => x.zuid == (string)zda["doid"]);

                edzu.zm = getdata.zm;



                //这里添加提交过来的权限到权限明细表
                var getqxmx = new Qxlist();
                foreach (var item in zda["ckadd"])
                {
                    getqxmx = new Qxlist();
                    var getitem = Regex.Split(item.ToString(), "。", RegexOptions.IgnoreCase);
                    getqxmx.scid = zda["doid"];
                    getqxmx.c = getitem[0];
                    getqxmx.a = getitem[1];
                    getqxmx.v = getitem[2];
                    getqxmx.sta = "s";

                    db.Qxlists.Add(getqxmx);
                }
                //对已有权限进行修改
                var hadqxs = db.Qxlists.Where(f => f.scid == (string)zda["doid"]).ToList();
                if (hadqxs.Count() > 0)
                {
                    foreach (var item in hadqxs)
                    {
                        if (zda["ckadd1"].Where(fo => string.Compare(fo, item.c + "。" + item.a + "。" + item.v, true) == 0).Count() == 0) {
                            db.Qxlists.Remove(item);
                        }
                    }
                }


                db.SaveChanges();

                ViewBag.result0 = "{\"lx\":\"edit\",\"sta\":\"ok\",\"pid\":\"0\",\"myid\":\"" + zda["doid"] + "\",\"myname\":\"" + getdata.zm + "\"}";

                return View("result0");
            }

            return View("result0");
        }

        [Descriper(Name = "权限分组管理·删除分组", Memo = "由超级管理员操作", Super = true)]
        public IActionResult sys_qxgroup_delete(string zuid)
        {
            var delzu = new QAzu();
            delzu = db.QAzus.FirstOrDefault(x => x.zuid == zuid);
            db.QAzus.Remove(delzu);

            var delzuqx = db.Qxlists.Where(x => x.scid == zuid && x.sta=="s");
            foreach (var item in delzuqx)
            {
                db.Qxlists.Remove(item);
            }

            db.SaveChanges();


            return View("result0");
        }

        #endregion
        //南无阿弥陀佛·南无阿弥陀佛·南无阿弥陀佛·南无阿弥陀佛·南无阿弥陀佛·南无阿弥陀佛·南无阿弥陀佛·南无阿弥陀佛

        #region 管理员帐号
        //●皈依佛·皈依法·皈依僧●皈依佛·皈依法·皈依僧●皈依佛·皈依法·皈依僧●皈依佛·皈依法·皈依僧●皈依佛·皈依法·皈依僧●

        [Descriper(Name = "管理员帐号管理界面", Memo = "对后台登录管理员帐号进行操作", Icode = "Fo001")]
        public IActionResult sys_account()
        {

            return View();
        }

        public IActionResult sys_account_mlist(int pagenum)
        {
            var pagesize = 8;
            if (pagenum <= 0) { pagenum = 1; }
            var mems = new List<Amem>();
            //非超级管理员不列出S级帐号
            var logmemxx = HttpContext.Session.GetObj<Memlogin>("mems");
            if (logmemxx.lx == "S")
            {
                mems = Dbfohelper.SqlQuery<Amem>(db, "select * from Admin_mem order by xm").ToList();
            }
            else
            {
                mems = Dbfohelper.SqlQuery<Amem>(db, "select * from Admin_mem where lx<>'S' order by xm").ToList();
            }

            var ms = mems.Count();
            var alls = 0;
            if (ms % pagesize > 0)
            {
                alls = (ms / pagesize) + 1;
            }
            else { alls = ms / pagesize; }

            if (pagenum > alls) { pagenum = alls; }

            mems = mems.Skip((pagenum - 1) * pagesize).Take(pagesize).ToList();

            ViewBag.pagenum = pagenum;
            ViewBag.pages = alls;
            ViewBag.zus = db.QAzus.Where(z => z.lx != "s").ToList();
            ViewBag.mems = mems;



            return View();
        }

        //帐号的创建与修改
        public IActionResult sys_account_aedit(string pid, string lx)
        {

            ViewBag.lx = lx;
            ViewBag.pid = pid;
            if (lx == "add") { ViewBag.but = "创建帐号"; }
            if (lx == "edit") { ViewBag.but = "修改帐号"; }

            var menuqx = db.Qxlists.Where(q => q.scid == pid && q.sta == "m").ToList();
            var Mtree = db.Amenus.ToList();
            var Ado = new AdminWorks();
            ViewBag.MenuTreeNodes = Ado.GetMenuTreesCk("$", Mtree, menuqx);

            ViewBag.mem = Dbfohelper.SqlQuery<Amem>(db, "select * from Admin_mem where pid='" + pid + "'").FirstOrDefault();

            return View();
        }

        [HttpPost]
        [Descriper(Name = "管理员帐号·基本编辑", Memo = "创建和修改管理员帐号")]
        public IActionResult sys_account_aedit(IFormCollection mda)
        {
            if (mda["xm"] == "")
            {
                ViewBag.result0 = "{\"sta\":\"no\",\"pid\":\"1\",\"myid\":\"2\",\"myname\":\"姓名不可为空！\"}";
                return View("result0");
            }
            if (mda["lgm"] == "")
            {
                ViewBag.result0 = "{\"sta\":\"no\",\"pid\":\"1\",\"myid\":\"2\",\"myname\":\"登录名不可为空！\"}";
                return View("result0");
            }
            if (mda["pwd"] == "")
            {
                ViewBag.result0 = "{\"sta\":\"no\",\"pid\":\"1\",\"myid\":\"2\",\"myname\":\"密码不可为空！\"}";
                return View("result0");
            }

            var getdata = new Amem();
            getdata.xm = mda["xm"];
            getdata.pwd = mda["pwd"];

            if (mda["dolx"] == "add")
            {

                getdata.lgm = mda["lgm"];
                var mem = Dbfohelper.SqlQuery<Amem>(db, "select top 1 Id from Admin_mem where lgm='"+ getdata.lgm + "'");
                if (mem.Count() > 0)
                {
                    ViewBag.result0 = "{\"sta\":\"no\",\"pid\":\"1\",\"myid\":\"2\",\"myname\":\"此帐号名已存在，请更换！\"}";
                    return View("result0");
                }


                mem = Dbfohelper.SqlQuery<Amem>(db, "select top 1 Id from Admin_mem order by Id desc");
                if (mem.Count() > 0)
                {
                    getdata.pid = Convert.ToString(mem.First().Id + 1);
                }
                else
                {
                    getdata.pid = "1";
                }

                db.Database.ExecuteSqlCommand("insert into Admin_mem(pid,lgm,xm,pwd,zuids,lx,ctime)values('" + getdata.pid + "','" + getdata.lgm + "','" + getdata.xm + "','" + getdata.pwd + "','','','" + DateTime.Now.ToString() + "')");

                var Mjson = mda["mchk"].ToString();
                Mjson = Mjson.Replace("end", "");
                Mjson = Mjson + "]";
                Mjson = Mjson.Replace(",]", "]");
                Mjson = "[" + Mjson;


                var menus = db.Amenus;
                var menuget = new Amenu();
                var uqx = new Qxlist();

                var jo = (JArray)JsonConvert.DeserializeObject(Mjson);
                for (var i = 0; i < jo.Count; i++)
                {
                    uqx = new Qxlist();
                    menuget = menus.Where(g => g.muid == (string)jo[i]["id"]).FirstOrDefault();
                    if (menuget != null)
                    {
                        uqx.scid = getdata.pid;
                        uqx.c = "菜单";
                        uqx.a = "菜单";
                        uqx.v = menuget.muid;
                        uqx.sta = "m";

                        db.Add(uqx);
                    }

                }
                db.SaveChanges();

                ViewBag.result0 = "{\"lx\":\"add\",\"sta\":\"ok\",\"pid\":\"" + getdata.pid + "\",\"myid\":\"" + getdata.pid + "\",\"myname\":\"" + getdata.lgm + "\"}";//,\"treejson\":[" + Ado.GetMenuTrees("$", Mtree) + "]

                return View("result0");
            }

            if (mda["dolx"] == "edit")
            {
                //演示版中，不让大家修改此帐号密码
                if (mda["lgm"] == "hhf")
                {
                    getdata.pwd = "123";
                }
                //演示版中，不让大家修改此帐号密码


                getdata.pid = mda["doid"];
                db.Database.ExecuteSqlCommand("update Admin_mem set xm='" + getdata.xm + "',pwd='" + getdata.pwd + "' where pid='" + getdata.pid + "'");

                var Mjson = mda["mchk"].ToString();
                Mjson = Mjson.Replace("end", "");
                Mjson = Mjson + "]";
                Mjson = Mjson.Replace(",]", "]");
                Mjson = "[" + Mjson;

                //删除旧菜单权限
                db.Database.ExecuteSqlCommand("delete Admin_qxs where scid='" + getdata.pid + "' and sta='m'");


                var menus = db.Amenus;
                var menuget = new Amenu();
                var uqx = new Qxlist();

                var jo = (JArray)JsonConvert.DeserializeObject(Mjson);
                for (var i = 0; i < jo.Count; i++)
                {
                    uqx = new Qxlist();
                    menuget = menus.Where(g => g.muid == (string)jo[i]["id"]).FirstOrDefault();
                    if (menuget != null)
                    {
                        uqx.scid = getdata.pid;
                        uqx.c = "菜单";
                        uqx.a = "菜单";
                        uqx.v = menuget.muid;
                        uqx.sta = "m";

                        db.Add(uqx);
                    }

                }
                db.SaveChanges();

                ViewBag.result0 = "{\"lx\":\"edit\",\"sta\":\"ok\",\"pid\":\"" + getdata.pid + "\",\"myid\":\"" + getdata.pid + "\",\"myname\":\"" + getdata.lgm + "\"}";//,\"treejson\":[" + Ado.GetMenuTrees("$", Mtree) + "]

                return View("result0");
            }


            return View("result0");
        }


        //帐号的权限、组设置
        public IActionResult sys_account_bedit(string pid)
        {

            ViewBag.mem = Dbfohelper.SqlQuery<Amem>(db, "select * from Admin_mem where pid='" + pid + "'").FirstOrDefault();
            ViewBag.zus = db.QAzus.Where(z => z.lx != "s").ToList();

            return View();
        }

        [HttpPost]
        [Descriper(Name = "管理员帐号·分组、权限编辑", Memo = "设置帐号分组和个性权限")]
        public IActionResult sys_account_bedit(IFormCollection mda)
        {
            if (mda["zuck"].Contains("A"))
            {
                db.Database.ExecuteSqlCommand("update [Admin_mem] set lx='A' where pid='"+ mda["doid"] + "' and lx<>'S'");
                ViewBag.result0 = "{\"lx\":\"edit\",\"sta\":\"ok\",\"pid\":\"pp\",\"myid\":\"ppp\",\"myname\":\"ppp\"}";

                return View("result0");
            }
            else
            {
                db.Database.ExecuteSqlCommand("update [Admin_mem] set lx='' where pid='" + mda["doid"] + "'");
            }

            //设置分组
            db.Database.ExecuteSqlCommand("update [Admin_mem] set zuids='"+ mda["zuck"] + "' where pid='" + mda["doid"] + "'");

            //删除旧权限
            db.Database.ExecuteSqlCommand("delete [Admin_qxs] where scid='" + mda["doid"] + "' and sta<>'m' and sta<>'=' and sta<>'s'");

            //读取组权限和个性权限进行比较
            var zuqxs = db.Qxlists.Where(z=> (","+ mda["zuck"] + ",").Contains(","+z.scid+",") && z.sta=="=").ToList();

            var qxdo = new Qxlist();

            var my_setqx = Regex.Split(mda["ckadd"].ToString(), ",", RegexOptions.IgnoreCase);
            var getitem =new string[3];
            //我有，组没有，添加授权
            for (var mi=0;mi<my_setqx.Count();mi++)
            {
                getitem = Regex.Split(my_setqx[mi].ToString(), "。", RegexOptions.IgnoreCase);
                if (zuqxs.Where(z => String.Compare(z.c, getitem[0], true) == 0 && String.Compare(z.a, getitem[1], true) == 0).Count()==0)
                {
                    //添加
                    qxdo = new Qxlist();
                    qxdo.scid = mda["doid"];
                    qxdo.c = getitem[0];
                    qxdo.a = getitem[1];
                    qxdo.v = getitem[2];
                    qxdo.sta = "+";
                    db.Qxlists.Add(qxdo);
                }
            }

            //组有，我没有，添加禁止授权
            string ns = mda["ckadd"];
            ns = "。" + ns + "。";
            ns = ns.Replace(",","。");
            foreach (var zuitem in zuqxs)
            {

                if (ns.Contains("。"+zuitem.c+"。"+zuitem.a+"。")==false)
                {
                    //添加
                    qxdo = new Qxlist();
                    qxdo.scid = mda["doid"];
                    qxdo.c = zuitem.c;
                    qxdo.a = zuitem.a;
                    qxdo.v = zuitem.v;
                    qxdo.sta = "-";
                    db.Qxlists.Add(qxdo);
                }
            }

            db.SaveChanges();
            ViewBag.result0 = "{\"lx\":\"edit\",\"sta\":\"ok\",\"pid\":\"pp\",\"myid\":\"ppp\",\"myname\":\"ppp\"}";

            return View("result0");


        }

        //个性权限列表
        public IActionResult sys_account_bedit_qxlist(string pid, string zuids)
        {
            if (zuids == null) { zuids = ""; }
            zuids = zuids.Replace("&zuck=", ",");
            zuids = zuids.Replace("zuck=", ",");

            ViewBag.hadqx = GlistCAmenus.GetALLhadqx(db.Qxlists.Where(h => h.sta == "s").ToList());
            ViewBag.weiqx = GlistCAmenus.GetALLweiqx(db.Qxlists.Where(h => h.sta == "s").ToList());

            //获得Tab及Tab组权限
            ViewBag.tabget = db.QAzus.Where(h => h.lx == "s").OrderBy(h => h.zm).ToList();
            ViewBag.tabqxget = db.Qxlists.Where(h => h.sta == "s").ToList();

            //获取个人权限，包含禁止的权限
            ViewBag.pqxget = db.Qxlists.Where(h => h.scid == pid || (","+zuids+",").Contains(","+h.scid+",")).ToList();




            return PartialView();
        }


        [Descriper(Name = "管理员帐号·删除", Memo = "删除后台登录管理员帐号")]
        public IActionResult sys_account_delete(string pid)
        {
            db.Database.ExecuteSqlCommand("delete Admin_qxs where scid='" + pid + "' and sta<>'=' and sta<>'s' and sta<>'m' ");
            db.Database.ExecuteSqlCommand("delete Admin_mem where pid='" + pid + "' and lx<>'S' ");

            return View("result0");
        }
        #endregion
        //南无阿弥陀佛·南无阿弥陀佛·南无阿弥陀佛·南无阿弥陀佛·南无阿弥陀佛·南无阿弥陀佛·南无阿弥陀佛·南无阿弥陀佛

        #region 管理员分组
        //●皈依佛·皈依法·皈依僧●皈依佛·皈依法·皈依僧●皈依佛·皈依法·皈依僧●皈依佛·皈依法·皈依僧●皈依佛·皈依法·皈依僧●
        [Descriper(Name = "管理员分组界面", Memo = "建立分组并设定分组权限",Icode ="Fo002")]
        public IActionResult sys_group()
        {
            return View();
        }


        //编辑管理员分组·读出数据
        public IActionResult sys_group_edit(string zuid)
        {
            var pm = db.QAzus.FirstOrDefault(x => x.zuid == zuid);

            if (pm != null) { return View(pm); }
            else
            {
                return View(new QAzu());
            }

        }

        [HttpPost]
        [Descriper(Name = "编辑管理员分组·提交", Memo = "添加、修改管理员分组")]
        public IActionResult sys_group_edit(IFormCollection zda)
        {
            if (zda["zname"] == "")
            {
                ViewBag.result0 = "{\"sta\":\"no\",\"pid\":\"1\",\"myid\":\"2\",\"myname\":\"组名不可为空！\"}";
                return View("result0");
            }

            var getdata = new QAzu();
            getdata.zm = zda["zname"];
            getdata.lx = "";
            getdata.px = 1;
            getdata.sm = zda["zsm"];

            if (zda["dolx"] == "add")
            {
                var myid = db.QAzus.OrderByDescending(sl => sl.Id).FirstOrDefault();
                var myidval = "1";
                if (myid != null)
                {
                    myidval = Convert.ToString(Convert.ToInt32(myid.zuid) + 1);
                }
                getdata.zuid = myidval;
                getdata.px = Convert.ToInt32(myidval) * 10;
                db.QAzus.Add(getdata);


                //这里添加提交过来的权限到权限明细表
                var getqxmx = new Qxlist();
                foreach (var item in zda["ckadd"])
                {
                    getqxmx = new Qxlist();
                    var getitem = Regex.Split(item.ToString(), "。", RegexOptions.IgnoreCase);
                    getqxmx.scid = myidval;
                    getqxmx.c = getitem[0];
                    getqxmx.a = getitem[1];
                    getqxmx.v = getitem[2];
                    getqxmx.sta = "=";//=表示管理员分组的权限

                    db.Qxlists.Add(getqxmx);
                }

                db.SaveChanges();

                ViewBag.result0 = "{\"lx\":\"add\",\"sta\":\"ok\",\"pid\":\"0\",\"myid\":\"" + myidval + "\",\"myname\":\"" + getdata.zm + "\"}";

                return View("result0");
            }

            if (zda["dolx"] == "edit")
            {
                var edzu = db.QAzus.FirstOrDefault(x => x.zuid == (string)zda["doid"]);

                edzu.zm = getdata.zm;
                edzu.sm = getdata.sm;


                //这里添加提交过来的权限到权限明细表
                var getqxmx = new Qxlist();
                foreach (var item in zda["ckadd"])
                {
                    getqxmx = new Qxlist();
                    var getitem = Regex.Split(item.ToString(), "。", RegexOptions.IgnoreCase);
                    getqxmx.scid = zda["doid"];
                    getqxmx.c = getitem[0];
                    getqxmx.a = getitem[1];
                    getqxmx.v = getitem[2];
                    getqxmx.sta = "=";

                    db.Qxlists.Add(getqxmx);
                }
                //对已有权限进行修改
                var hadqxs = db.Qxlists.Where(f => f.scid == (string)zda["doid"]).ToList();
                if (hadqxs.Count() > 0)
                {
                    foreach (var item in hadqxs)
                    {
                        if (zda["ckadd1"].Where(fo => string.Compare(fo, item.c + "。" + item.a + "。" + item.v, true) == 0).Count() == 0)
                        {
                            db.Qxlists.Remove(item);
                        }
                    }
                }


                db.SaveChanges();

                ViewBag.result0 = "{\"lx\":\"edit\",\"sta\":\"ok\",\"pid\":\"0\",\"myid\":\"" + zda["doid"] + "\",\"myname\":\"" + getdata.zm + "\"}";

                return View("result0");
            }

            return View("result0");
        }

        [Descriper(Name = "分组管理·删除分组", Memo = "删除管理员分组")]
        public IActionResult sys_group_delete(string zuid)
        {
            var delzu = new QAzu();
            delzu = db.QAzus.FirstOrDefault(x => x.zuid == zuid && x.lx=="");
            db.QAzus.Remove(delzu);

            var delzuqx = db.Qxlists.Where(x => x.scid == zuid && x.sta=="=");
            foreach (var item in delzuqx)
            {
                db.Qxlists.Remove(item);
            }

            db.SaveChanges();


            return View("result0");
        }

        

        //分组列表
        public IActionResult sys_group_list()
        {
            var zlist = db.QAzus.Where(h => h.lx != "s").OrderBy(h => h.zm).ToList();

            return PartialView(zlist);
        }
        //分组权限列表，Tab展现
        public IActionResult sys_group_qxlist(string zuid,string Canck)
        {
            ViewBag.hadqx = GlistCAmenus.GetALLhadqx(db.Qxlists.Where(h => h.sta == "s").ToList());
            ViewBag.weiqx = GlistCAmenus.GetALLweiqx(db.Qxlists.Where(h => h.sta == "s").ToList());

            //获得Tab及Tab组权限
            ViewBag.tabget = db.QAzus.Where(h => h.lx == "s").OrderBy(h => h.zm).ToList();
            ViewBag.tabqxget = db.Qxlists.Where(h => h.sta == "s").ToList();

            //获取修改组时，分组权限
            ViewBag.zuqxget = db.Qxlists.Where(h => h.scid == zuid).ToList();            

            if (Canck == "yes") { return PartialView(); } else { return PartialView("sys_group_qxlist_show"); }

        }

        //编辑管理员分组·添加分组帐号
        public IActionResult sys_group_useradd()
        {
            return View();
        }

        //编辑管理员分组·添加分组帐号
        [HttpPost]
        [Descriper(Name = "编辑管理员分组·添加组用户", Memo = "在分组内添加管理员帐号")]
        public IActionResult sys_group_useradd(IFormCollection uda)
        {
            if (uda["pid"].Count()==0)
            {
                ViewBag.result0 = "{\"sta\":\"no\",\"pid\":\"1\",\"myid\":\"2\",\"myname\":\"请选择要添加的帐号！\"}";
                return View("result0");
            }

            var sqlstr = "";

            for(var i = 0; i < uda["pid"].Count(); i++)
            {
                var getitem = Regex.Split(uda["pid"][i].ToString(), "。", RegexOptions.IgnoreCase);


                sqlstr = sqlstr + "update Admin_mem set zuids='" + getitem[0] + "' where pid='"+ getitem[1] + "'   ";
            }

            db.Database.ExecuteSqlCommand(sqlstr);


            ViewBag.result0 = "{\"lx\":\"add\",\"sta\":\"ok\",\"pid\":\"0\",\"myid\":\"+++\",\"myname\":\"阿弥陀佛\"}";

            return View("result0");

        }
        //快捷添加帐号到分组中，显示check列表
        public IActionResult sys_group_useradd_list(string zuid)
        {
            var allmem = Dbfohelper.SqlQuery<Amem>(db, "select * from Admin_mem");

            ViewBag.users = allmem.Where(u => ("," + u.zuids + ",").Contains("," + zuid + ",") == false).ToList();
            ViewBag.zuid = zuid;

            return View();
        }
        //分组点击时，将分组中的帐号显示在右侧，以供快捷删除
        public IActionResult sys_group_userdel_list(string zuid)
        {
            var allmem = Dbfohelper.SqlQuery<Amem>(db, "select * from Admin_mem");

            var zumem = allmem.Where(u => ("," + u.zuids + ",").Contains("," + zuid + ",") == true).ToList();

            foreach (var p in zumem)
            {
                p.zuids = "," + p.zuids + ",";
                p.zuids = p.zuids.Replace(","+ zuid+",", ",");
            }

            ViewBag.users = zumem;
            ViewBag.zuid = zuid;

            return View();
        }
        [Descriper(Name = "编辑管理员分组·快捷移出组用户", Memo = "在分组内移出管理员帐号")]
        public IActionResult sys_zuuser_userdel(string pid,string zuids)
        {
            zuids = zuids.Replace(",,,", ",");
            zuids = zuids.Replace(",,",",");
            var sqlstr = "update Admin_mem set zuids='" + zuids + "' where pid='" + pid + "'   ";

            db.Database.ExecuteSqlCommand(sqlstr);


            ViewBag.result0 = "{\"lx\":\"add\",\"sta\":\"ok\",\"pid\":\"0\",\"myid\":\"+++\",\"myname\":\"阿弥陀佛\"}";

            return View("result0");

        }

        #endregion
        //南无阿弥陀佛·南无阿弥陀佛·南无阿弥陀佛·南无阿弥陀佛·南无阿弥陀佛·南无阿弥陀佛·南无阿弥陀佛·南无阿弥陀佛



        #region 验证码
        //●皈依佛·皈依法·皈依僧●皈依佛·皈依法·皈依僧●皈依佛·皈依法·皈依僧●皈依佛·皈依法·皈依僧●皈依佛·皈依法·皈依僧●
        public IActionResult yzm()
        {

            Random rd = new Random(unchecked((int)DateTime.Now.Ticks));

            int iResult;
            int iUp = 9999;
            int iDown = 1000;
            iResult = rd.Next(iDown, iUp);

            string chkCode = Convert.ToString(iResult);

            HttpContext.Session.SetString("yzm", chkCode);

            int codeW = 148;
            int codeH = 33;
            int fontSize = 16;
            Random rnd = new Random();
            //颜色列表，用于验证码、噪线、噪点 
            Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.Brown, Color.DarkBlue };
            //字体列表，用于验证码 
            string[] font = { "Times New Roman" };

            //创建画布
            Bitmap bmp = new Bitmap(codeW, codeH);
            Graphics g = Graphics.FromImage(bmp);
            g.Clear(Color.White);
            //画噪线 
            for (int i = 0; i < 3; i++)
            {
                int x1 = rnd.Next(codeW);
                int y1 = rnd.Next(codeH);
                int x2 = rnd.Next(codeW);
                int y2 = rnd.Next(codeH);
                Color clr = color[rnd.Next(color.Length)];
                g.DrawLine(new Pen(clr), x1, y1, x2, y2);
            }
            //画验证码字符串 
            for (int i = 0; i < chkCode.Length; i++)
            {
                string fnt = font[rnd.Next(font.Length)];
                Font ft = new Font(fnt, fontSize, FontStyle.Bold);
                Color clr = color[rnd.Next(color.Length)];
                g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 18, (float)0);
            }
            //将验证码图片写入内存流，并将其以 "image/Png" 格式输出 
            MemoryStream ms = new MemoryStream();
            try
            {
                bmp.Save(ms, ImageFormat.Png);
                return File(ms.ToArray(), @"image/png");
            }
            catch (Exception)
            {
                return null;
            }
            finally
            {
                g.Dispose();
                bmp.Dispose();
            }
        }
        #endregion
        //南无阿弥陀佛·南无阿弥陀佛·南无阿弥陀佛·南无阿弥陀佛·南无阿弥陀佛·南无阿弥陀佛·南无阿弥陀佛·南无阿弥陀佛














        [Descriper(Name = "功能权限演示一", Memo = "这里是功能的备注说明", Icode ="A06" ,Super =true)]
        public IActionResult haha()
        {
            //假令供养恒沙圣，不如坚勇求正觉
            return View();
        }

        [Descriper(Name = "功能权限演示二", Memo = "这里是功能的备注说明")]
        public IActionResult hehe()
        {
            //布施、持戒、忍辱、精进、禅定、般若
            return View();
        }






    }
}