using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RFramework.SQLServer;
using RFrameGenerate.Common;
using RFrameGenerate.DAL;
using RFrameGenerate.DAL.Interface;
using RFrameGenerate.Model;

namespace RFrameGenerate.BLL
{
    public class RoleManage
    {
        public List<T_ST_Role> GetRolePageList(GridModel gridModel)
        {
            using (var query = Factory.CreateT_ST_Role())
            {
                return query.GetPageList(gridModel, a => a.MerchantGuid == CurrentManage.MerchantGuid, false, b => b.RoleCode);
            }
        }

        public Result UpdateRole(T_ST_Role model)
        {
            try
            {
                using (var query = Factory.CreateT_ST_Role())
                {
                    query.Update(a => new object[]
                    {
                        //a.RoleCode==model.RoleCode,//自动生成
                        a.RoleName==model.RoleName, 
                        a.RoleRemark==model.RoleRemark,                         
                    }, b => b.RoleGuid == model.RoleGuid);
                }
                return new Result(true);
            }
            catch (Exception ex)
            {
                return new Result(false, ex.Message);
            }
        }
        public Result SaveRole(T_ST_Role model)
        {
            try
            {
                using (var query = Factory.CreateT_ST_Role())
                {
                    model.RoleCode = AutoCodeBLL.GetAutoRoleCode();
                    model.MerchantGuid = CurrentManage.MerchantGuid;
                    query.Add(model);
                }
                return new Result(true);
            }
            catch (Exception ex)
            {
                return new Result(false, ex.Message);
            }
        }
        public Result DeleteRole(Guid roleGuid)
        {
            try
            {
                using (SqlRTransaction tran = new SqlRTransaction())
                {
                    var userRoleQuery = Factory.CreateT_ST_User_Role(tran);
                    if (userRoleQuery.IsExist(a => a.RoleGuid == roleGuid && a.MerchantGuid == CurrentManage.MerchantGuid) == true)
                        return new Result(false, "用户有使用该权限,无法删除!");

                    tran.BeginTransaction();
                    var query = Factory.CreateT_ST_Role(tran);
                    query.Delete(b => b.RoleGuid == roleGuid && b.MerchantGuid == CurrentManage.MerchantGuid);
                    var qeuryRP = Factory.CreateT_ST_Role_Permission(tran);
                    qeuryRP.Delete(a => a.RoleGuid == roleGuid && a.MerchantGuid == CurrentManage.MerchantGuid);
                    tran.Commit();
                }
                return new Result(true);
            }
            catch (Exception ex)
            {
                return new Result(false, ex.Message);
            }
        }

        public string GetUserPermission(Guid roleGuid)
        {
            List<T_ST_Permission> permissionList;
            List<Guid?> rplist;

            using (SqlRTransaction tran = new SqlRTransaction())
            {
                var queryPer = Factory.CreateT_ST_Permission(tran);
                permissionList = queryPer.GetList(null,orderExpression:b=>b.PermissionCode,orderMethod:DAL.Enums.OrderMethods.ASC);

                var query = Factory.CreateT_ST_Role_Permission(tran);
                rplist = query.GetList(a => a.RoleGuid == roleGuid && a.MerchantGuid == CurrentManage.MerchantGuid).Select(a => a.PermissionGuid).ToList();
            }

            string treeData = "[";
            var parent = permissionList.Where(a => a.ParentPermissionCode == "0").OrderBy(a => a.PermissionCode);
            foreach (var per in parent)
            {
                if (rplist.Contains(per.PermissionGuid) == true)
                    treeData += "{ id:" + per.PermissionCode + ", pId:" + per.ParentPermissionCode + ", name:\"" + per.PermissionName + "\",icon:\"../../Images/tree1.png\",iconOpen:\"../../Images/open.png\",iconClose:\"../../Images/close.png\",checked:true , open:true },";
                else
                    treeData += "{ id:" + per.PermissionCode + ", pId:" + per.ParentPermissionCode + ", name:\"" + per.PermissionName + "\",icon:\"../../Images/tree1.png\",iconOpen:\"../../Images/open.png\",iconClose:\"../../Images/close.png\",checked:false , open:true },";
                ForeachTree(permissionList, rplist, per.PermissionCode, ref treeData);
            }

            if (treeData.Length > 1)
                treeData = treeData.Substring(0, treeData.Length - 1) + "]";
            else
                treeData = "[]";

            return treeData;

        }

        /// <summary>
        /// 是否存在多个级
        /// </summary>
        /// <param name="list"></param>
        /// <param name="parentPermissionCode"></param>
        /// <param name="treeData"></param>
        private void ForeachTree(List<T_ST_Permission> list, List<Guid?> rpList, string parentPermissionCode, ref string treeData)
        {
            var child = list.Where(a => a.ParentPermissionCode == parentPermissionCode).OrderBy(a => a.PermissionCode);

            foreach (var permission in child)
            {
                if (rpList.Contains(permission.PermissionGuid) == true)
                    treeData += "{ id:" + permission.PermissionCode + ", pId:" + permission.ParentPermissionCode + ", name:\"" + permission.PermissionName + "\",icon:\"../../Images/tree1.png\",iconOpen:\"../../Images/open.png\",iconClose:\"../../Images/close.png\",checked:true , open:true },";
                else
                    treeData += "{ id:" + permission.PermissionCode + ", pId:" + permission.ParentPermissionCode + ", name:\"" + permission.PermissionName + "\",icon:\"../../Images/tree1.png\",iconOpen:\"../../Images/open.png\",iconClose:\"../../Images/close.png\",checked:false , open:true },";
                ForeachTree(list, rpList, permission.PermissionCode, ref treeData);
            }
        }
        public Result UpdateRolePermission(Guid roleGuid, string[] checkNodesPCode)
        {
            try
            {
                using (SqlRTransaction tan = new SqlRTransaction())
                {
                    if (checkNodesPCode == null)
                    {
                        var qeuryRP0 = Factory.CreateT_ST_Role_Permission(tan);
                        qeuryRP0.Delete(a => a.RoleGuid == roleGuid && a.MerchantGuid == CurrentManage.MerchantGuid);
                        return new Result(true);
                    }

                    var queryPer = Factory.CreateT_ST_Permission(tan);
                    var perList = queryPer.GetList();
                    List<T_ST_Role_Permission> addList = new List<T_ST_Role_Permission>();
                    foreach (var v in checkNodesPCode)
                    {
                        var per = perList.Where(a => a.PermissionCode == v.Trim()).FirstOrDefault();
                        T_ST_Role_Permission rp = new T_ST_Role_Permission()
                        {
                            Role_PermissionGuid = Guid.NewGuid(),
                            RoleGuid = roleGuid,
                            PermissionGuid = per.PermissionGuid,
                            PermissionCode = per.PermissionCode,
                            MerchantGuid = CurrentManage.MerchantGuid,
                        };
                        addList.Add(rp);
                    }
                    tan.BeginTransaction();
                    var qeuryRP = Factory.CreateT_ST_Role_Permission(tan);
                    qeuryRP.Delete(a => a.RoleGuid == roleGuid && a.MerchantGuid == CurrentManage.MerchantGuid);
                    qeuryRP.AddList(addList);
                    tan.Commit();
                }

                return new Result(true);
            }
            catch (Exception e)
            {
                return new Result(false, e.Message);
            }
        }
    }
}
