using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Bailun.DC.Models;
using Bailun.DC.Models.Api;
using Bailun.ServiceFabric.Authorize;
using Bailun.ServiceFabric.Core.Extension;
using Bailun.ServiceFabric.Core.Extension.HttpContext;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace Bailun.DC.Web.Areas.Users.Controllers
{
    [Area("Users")]
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
        
        #region 角色管理

        public ActionResult UserRoles()
        {
            return View();
        }

        /// <summary>
        /// 返回角色列表
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public string ListUserRoles(BtTableParameter parameter,string name)
        {
            var total = 0;
            var obj = new Services.MenuServices().ListUserRole(parameter, name,ref total);

            var list = obj.Select(a => new
            {
                a.id,
                a.name,
                a.note,
                createtime = a.createtime.ToString("yyyy-MM-dd HH:mm:ss"),
                lastupdatetime = a.lastupdatetime.ToString("yyyy-MM-dd HH:mm:ss"),
                a.lastupdateusername
            });

            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = list,
            });
        }

        /// <summary>
        /// 角色详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult RoleDetail(int? id)
        {
            var m = new Models.Menu.dc_user_role();

            if (id.HasValue && id.Value > 0)
            {
                m = new Services.MenuServices().GetUserRole(id.Value);
                if (m == null)
                {
                    m = new Models.Menu.dc_user_role();
                }
            }

            ViewBag.m = m;
            return View();
        }

        /// <summary>
        /// 保存用户角色信息
        /// </summary>
        /// <param name="id">角色id</param>
        /// <param name="name">角色名称</param>
        /// <param name="note">备注</param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        [HttpPost]
        public JsonResult SaveUserRole(int? id,string name,string note)
        {
            var user = HttpContextHelper.Current?.User;
            var obj = new Services.MenuServices().SaveRole(new Models.Menu.dc_user_role() { id=id??0,name = name,note=note},(user==null?0: user.GetUid()),(user==null?"":user.GetUserName()));

            return Json(new {
                success = string.IsNullOrEmpty(obj),
                msg = obj
            });
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        [HttpPost]
        public JsonResult DelUserRole(int id)
        {
            var user = HttpContextHelper.Current?.User;

            var obj = new Services.MenuServices().DelRole(id, (user == null ? 0 : user.GetUid()), (user == null ? "" : user.GetUserName()));

            return Json(new
            {
                success = string.IsNullOrEmpty(obj),
                msg = obj
            });
        }

        #endregion

        #region 权限设置

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ActionResult UserRoleRelation()
        {
            //公司员工列表
            var listUser = Services.CommonServices.GetListOAUser();

            //获取所有菜单
            //var listMenu = new Services.MenuServices().ListMenu();

            //获取所有角色
            var listrole = new Services.MenuServices().ListUserRole();


            ViewBag.users = listUser;
            ViewBag.roles = listrole;
            
            return View();
        }

        /// <summary>
        /// 获取所有菜单
        /// </summary>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        [HttpPost]
        public JsonResult GetMenus()
        {
            var _service = new Services.MenuServices();
            var menus = _service.ListMenu();

            var userid = HttpContextHelper.Current.User?.GetUid();

            var listRela = _service.GetUserRoleRela(userid ?? 0);

            if (listRela.Where(a => a.role_id == 1).Count() == 0)
            {
                menus = menus.Where(a => a.id != 107 && a.id != 108 && a.id != 109).ToList();
            }

            var list = new List<Models.Api.mSkuCategoryTree>();

            var onelevel = menus.Where(a => a.parentid == 0);
            foreach (var item in onelevel)
            {
                //GetChildrens(menus, item);

                //var chidren = menus.Where(a => a.parentid == item.id);
                var m = new Models.Api.mSkuCategoryTree
                {
                    id = item.id,
                    name = item.name,
                    open = false
                };

                list.Add(m);
            }

            foreach (var item in list)
            {
                GetChildrens(menus, item);
            }


            return Json(list);

        }

        /// <summary>
        /// 获取角色的用户和授权的菜单信息
        /// </summary>
        /// <param name="role_id">角色id</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetRoleInfo(int roleid)
        {
            try
            {
                var _service = new Services.MenuServices();

                //已授权用户
                var listRela = _service.ListUserRoleRelation(roleid);

                //已授权菜单
                var listMenu = _service.GetRoleMenu(roleid);

                return Json(new
                {
                    success = true,
                    msg = "",
                    rela = listRela,
                    menus = listMenu
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    msg = ex.Message
                });
            }
            
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UserRoleRelationJson(int role_id)
        {

            return Json("");
        }

        /// <summary>
        /// 给角色设置用户
        /// </summary>
        /// <param name="userid">用户id</param>
        /// <param name="roleid">角色id</param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        [HttpPost]
        public JsonResult SaveRoleUser(int userid,string username,int roleid)
        {
            var id = 0;
            var user = HttpContextHelper.Current?.User;

            var result = new Services.MenuServices().SaveRoleUser(roleid,userid, username, (user == null ? 0 : user.GetUid()), (user == null ? "" : user.GetUserName()),ref id);

            return Json(new {
                success = string.IsNullOrEmpty(result),
                msg = result,
                dataid = id,
            });
        }

        /// <summary>
        /// 删除角色用户
        /// </summary>
        /// <param name="id">角色用户关系id</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult DelRoleUser(int id)
        {
            if (id == 1)
            {
                return Json(new
                {
                    success = true,
                    msg = ""
                });
            }

            var user = HttpContextHelper.Current?.User;
            var result = new Services.MenuServices().DelRoleUser(id,(user == null ? 0 : user.GetUid()), (user == null ? "" : user.GetUserName()));

            return Json(new
            {
                success = string.IsNullOrEmpty(result),
                msg = result
            });
        }

        /// <summary>
        /// 保存角色菜单
        /// </summary>
        /// <param name="roleid"></param>
        /// <param name="s"></param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        [HttpPost]
        public JsonResult SaveRoleMenus(int roleid, string s,int? isall=0)
        {
            var user = HttpContextHelper.Current?.User;
            var result = new Services.MenuServices().SaveRoleMenus(roleid, s, (user == null ? 0 : user.GetUid()), (user == null ? "" : user.GetUserName()),isall??0);

            return Json(new {
                success = string.IsNullOrEmpty(result),
                msg = result
            });

        }

        #endregion

        #region Private

        /// <summary>
        /// 获取菜单的子菜单
        /// </summary>
        /// <param name="list"></param>
        /// <param name="m"></param>
        private void GetChildrens(List<Models.Menu.dc_menu> list,mSkuCategoryTree m)
        {
            var chidren = list.Where(a => a.parentid == m.id);

            if (chidren.Count() > 0)
            {
                m.children = chidren.Select(a => new mSkuCategoryTree {
                    id = a.id,
                    name = a.name,
                    open = false,
                }).ToList();

                foreach (var item in m.children)
                {
                    GetChildrens(list, item);
                }
            }

        }

        #endregion

    }
}