using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using EKETEAM.Data;
using EKETEAM.FrameWork;
using LitJson;

namespace eFrameWork.Customs.Base
{
    public partial class AppUserPower : System.Web.UI.Page
    {
        public string AppItem = "";
        public string userid = "";
        public string act = "";
        string sql = "";
        private string parentModelID = "";

        /// <summary>
        /// 主库
        /// </summary>
        private eDataBase _database;
        private eDataBase DataBase
        {
            get
            {
                if (_database == null)
                {
                    _database = eConfig.DefaultDataBase;
                }
                return _database;
            }
        }
        private DataTable _checkups;
        public DataTable CheckUps
        {
            get
            {
                if (_checkups == null)
                {
                    sql = "SELECT ModelID,CheckMC as text,LOWER(CheckCode) as value,px,addTime FROM a_eke_sysCheckUps where delTag=0 and CheckCode not in ('Submit','HandoverConfirm') and LEN(CheckMC)>0 and LEN(CheckCode)>0";
                    _checkups = DataBase.getDataTable(sql);
                }
                return _checkups;
            }
        }
        private DataTable _applications;
        public DataTable Applications
        {
            get
            {
                if (_applications == null)
                {
                    string sql = "select ApplicationID,MC from a_eke_sysApplications where delTag=0";
                    if (eItems.Get("eUser") != null)
                    {
                        eUser user = eItems.Get("eUser");
                        string siteid = user["siteid"].ToString();
                        if (siteid.Length > 0 && siteid != "0")
                        {
                            sql += " and ApplicationID in (select ApplicationID from a_eke_sysSiteItems where deltag=0 and SiteID=" + siteid + ")";
                        }
                    }
                    sql += " order by isnull(px,999999),addTime";
                    _applications = DataBase.getDataTable(sql);
                }
                return _applications;
            }
        }
        private DataTable _applicationitems;
        public DataTable ApplitionItems
        {
            get
            {
                if (_applicationitems == null)
                {
                    sql = "select a.ApplicationItemID,a.ParentID,a.ApplicationID,a.ModelID,a.MC,b.Power,'' as " + DataBase.StartNameSplitChar + "Condition" + DataBase.EndNameSplitChar + ",a.PX,a.addTime from a_eke_sysApplicationItems a";
                    sql += " left join a_eke_sysModels b on a.ModelID=b.ModelID ";
                    sql += " where a.delTag=0 ";
                    //sql += " and (a.PackID is null or (a.PackID is not null and a.show=1 and b.Auto=1))";
                    _applicationitems = DataBase.getDataTable(sql);
                }
                return _applicationitems;
            }
        }

        private DataTable _a_eke_sysPowers;
        public DataTable a_eke_sysPowers
        {
            get
            {
                if (_a_eke_sysPowers == null)
                {
                    sql = "select * from a_eke_sysPowers where delTag=0 ";
                    _a_eke_sysPowers = eBase.UserInfoDB.getDataTable(sql);
                }
                return _a_eke_sysPowers;
            }
        }
        public string filename = "";
        public eUser user;
        public eModel model;
        public string UserArea = "Application";
        private DataTable _userpower;
        /// <summary>
        /// 当前登录用户的权限
        /// </summary>
        private DataTable UserPower
        {
            get
            {
                if (_userpower == null)
                {
                    string user_Roles = eBase.UserInfoDB.getValue("SELECT RoleID FROM a_eke_sysUsers where UserID='" + user.ID + "'");//当前登录用户的角色
                    _userpower = eBase.getUserPower(user_Roles, user.ID);
                }
                return _userpower;
            }
        }
        private List<string> _userpowerids;
        private List<string> UserPowerIDS
        {
            get
            {
                if (_userpowerids == null)
                {
                    //仅仅模块，多层级有BUG
                    //_userpowerids = (from row in UserPower.AsEnumerable() where row["URL"].ToString().Length == 0 && row["list"].ToString()=="true"  select row["ApplicationItemID"].ToString()).ToList();
                    _userpowerids = (from row in UserPower.AsEnumerable()  select row["ApplicationItemID"].ToString()).ToList();//模块级目录
                }
                return _userpowerids;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            user = new eUser(UserArea);
            model = new eModel(user);
            filename = eBase.getAspxFileName().ToLower();
            userid = eParameters.Request("id");
            act = eParameters.Request("act").ToLower();
            AppItem = eParameters.Request("AppItem");

            //eBase.Print(model.Power);
            //eBase.Writeln(AppItem);
            
            if (AppItem.Length > 0)
            {
                DataRow[] appRows = eBase.a_eke_sysApplicationItems.Select("ApplicationItemID='" + AppItem + "'");
                if (appRows.Length == 0) return;
                parentModelID = appRows[0]["ModelID"].ToString();
            }


            switch (act)
            {
                case "del":
                    sql = "update a_eke_sysPowers set delTag=1 where UserId='" + userid + "' and ApplicationID is not null";
                    eBase.UserInfoDB.Execute(sql);
                    break;
                case "save":
                    save();
                    runtimeCache.Remove();
                    HttpRuntime.Cache.Remove("DataCache_AppTopModelURL");
                    eBase.clearDataCache("a_eke_sysPowers");
                    break;
                default:
                    string roleid = "";
                    if (userid.Length > 0) roleid = eBase.UserInfoDB.getValue("select roleid from a_eke_sysUsers where userid='" + userid + "'");
                    LitBody.Text = getAppUserPower(roleid);
                    break;
            }

           
        }
        private void save()
        {
            if (userid.Length == 0)
            {
                if (HttpContext.Current.Items["ID"] != null) userid = HttpContext.Current.Items["ID"].ToString();
            }
            JsonData json = null;
            string jsonstr = eParameters.Form("eformdata_" + parentModelID);
            if (jsonstr.Length > 0)
            {
                json = JsonMapper.ToObject(jsonstr);
                json = json.GetCollection("eformdata_" + parentModelID).GetCollection()[0];
            }


            string Roles = json == null ? eParameters.Form("Roles") : json.getValue("Roles");

            sql = "update a_eke_sysUsers set RoleID='" + Roles + "' where UserId='" + userid + "'";
            eBase.UserInfoDB.Execute(sql);

            DataTable rolePower = eBase.getUserPower(Roles, "");

            string name = "";
            string value = "";

            foreach (DataRow dr in Applications.Rows) //所有应用 
            {

                DataRow[] rs = ApplitionItems.Select("ApplicationID='" + dr["ApplicationID"].ToString() + "'", "px,addTime");
                string appitems = "";
                string modelids = "";
                foreach (DataRow _dr in rs) //应用下所有模块
                {
                    //string rolePowerString = eBase.DataBase.getValue("select Power from a_eke_sysPowers where delTag=0 and ApplicationID='" + dr["ApplicationID"].ToString() + "' and ModelID='" + _dr["ModelID"].ToString() + "' and RoleID='' and UserID is null");
                    DataRow row = rolePower.NewRow();
                    row["ApplicationItemID"] = _dr["ApplicationItemID"].ToString();
                    row["ApplicationID"] = _dr["ApplicationID"].ToString();
                    row["ModelID"] = _dr["ModelID"].ToString();
                    for (int i = 0; i < row.Table.Columns.Count; i++)
                    {
                        if (row.Table.Columns[i].ColumnName.ToLower() != "applicationitemid" && row.Table.Columns[i].ColumnName.ToLower() != "applicationid" && row.Table.Columns[i].ColumnName.ToLower() != "modelid")
                        {
                            row[row.Table.Columns[i].ColumnName] = "false";
                        }
                    }
                    DataRow[] rows = rolePower.Select("ApplicationItemID='" + _dr["ApplicationItemID"].ToString() + "' and ModelID='" + _dr["ModelID"].ToString() + "'");
                    if (rows.Length > 0) row = rows[0];
 
                    DataTable PowerItems = _dr["Power"].ToString().ToJsonData().toRows();

                    #region 角色的权限
                    JsonData rolePowerJson = JsonMapper.ToObject("[]");
                    #region 基本权限
                    foreach (DataRow dr1 in PowerItems.Rows)
                    {
                        if (row.Table.Columns.Contains(dr1["value"].ToString()))
                        {
                            value = row[dr1["value"].ToString()].ToString();
                            JsonData _power = new JsonData();
                            _power.Add(dr1["value"].ToString(), value);
                            rolePowerJson.Add(_power);
                        }
                    }
                    #endregion
                    #region 审批权限
                    DataRow[] _rs = CheckUps.Select("ModelID='" + _dr["ModelID"].ToString() + "'", "px,addTime");
                    foreach (DataRow dr1 in _rs)
                    {
                        value = row[dr1["value"].ToString()].ToString();
                        JsonData _power = new JsonData();
                        _power.Add(dr1["value"].ToString(), value);
                        rolePowerJson.Add(_power);
                    }
                    #endregion
                    //eBase.Writeln(rolePowerJson.ToString());
                    #endregion

                    string canList = "0";
                    string cond = "";
                    string prop = "";

                    #region 用户自定义权限
                    JsonData selPower = JsonMapper.ToObject("[]");
                    #region 基本权限
                    foreach (DataRow dr1 in PowerItems.Rows)
                    {
                        name = "model_" + dr1["value"].ToString() + "_" + _dr["ApplicationItemID"].ToString().Replace("-", "") + "_" + _dr["ModelID"].ToString().Replace("-", "");
                        value = json == null ? eParameters.Form(name) : json.getValue(name);

                        if (value.Length == 0) value = "false";
                        JsonData _power = new JsonData();
                        _power.Add(dr1["value"].ToString(), value);
                        selPower.Add(_power);
                        if (dr1["value"].ToString().ToLower() == "list") canList = value;
                        // eBase.Writeln(dr1["value"].ToString() + "::" +  value);
                    }
                    #endregion
                    #region 审批权限
                    foreach (DataRow dr1 in _rs)
                    {
                        name = "model_" + dr1["value"].ToString() + "_" + _dr["ApplicationItemID"].ToString().Replace("-", "") + "_" + _dr["ModelID"].ToString().Replace("-", "");
                        value = json == null ? eParameters.Form(name) : json.getValue(name);
                        if (value.Length == 0) value = "false";
                        JsonData _power = new JsonData();
                        _power.Add(dr1["value"].ToString(), value);
                        selPower.Add(_power);
                    }
                    #endregion
                    // eBase.Writeln(selPower.ToString());
                    #endregion


                    name = "model_cond_" + _dr["ApplicationItemID"].ToString().Replace("-", "") + "_" + _dr["ModelID"].ToString().Replace("-", "");
                    cond = json == null ? eParameters.Form(name) : json.getValue(name);
                    if (cond.Length == 0 && userid.Length > 0 && _dr["ModelID"].ToString().Length > 10)
                    {
                        if ((json != null && json.Contains(name) == false) || (json == null && Request.Form[name] == null))
                        {
                            //cond = eBase.UserInfoDB.getValue("select Condition from a_eke_sysPowers where RoleID is Null and ApplicationItemID='" + _dr["ApplicationItemID"].ToString() + "' and ModelID='" + _dr["ModelID"].ToString() + "'  and UserID='" + userid + "' and delTag=0");
                            cond = eBase.UserInfoDB.eList("a_eke_sysPowers")
                               .Where.Add("RoleID is Null")
                               .Where.Add("ApplicationItemID='" + _dr["ApplicationItemID"].ToString() + "'")
                               .Where.Add("ModelID='" + _dr["ModelID"].ToString() + "'")
                               .Where.Add("UserID='" + userid + "'")
                               .Where.Add("delTag=0")
                               .getValue("Condition");
                        }
                    }
                    //cond = cond.Replace("'", "''");

                    name = "model_prop_" + _dr["ApplicationItemID"].ToString().Replace("-", "") + "_" + _dr["ModelID"].ToString().Replace("-", "");
                    prop = json == null ? eParameters.Form(name) : json.getValue(name);
                    if (prop.Length == 0 && userid.Length > 0)
                    {
                        if ((json != null && json.Contains(name) == false) || (json == null && Request.Form[name] == null))
                        {
                            prop = eBase.UserInfoDB.getValue("select Propertys from a_eke_sysPowers where RoleID is Null and ApplicationItemID='" + _dr["ApplicationItemID"].ToString() + "' and ModelID='" + _dr["ModelID"].ToString() + "'  and UserID='" + userid + "' and delTag=0");
                        }
                    }
                    //prop = prop.Replace("'", "''");
                    if (prop.Length == 0) prop = "{}";

                    if (selPower.ToJson() == rolePowerJson.ToJson() && cond.Length == 0) //与角色的相同
                    {
                        sql = " delete from a_eke_sysPowers where RoleID is Null and ApplicationItemID='" + _dr["ApplicationItemID"].ToString() + "' and ModelID" + (_dr["ModelID"].ToString().Length > 0 ? "='" + _dr["ModelID"].ToString() + "'" : " is null") + " and UserID='" + userid + "'";
                        eBase.UserInfoDB.Execute(sql);
                        //eBase.Writeln( _dr["ModelID"].ToString() + "::" +  ":::" + cond.Length.ToString());
                    }
                    else
                    {
                        /*
                        sql = "if exists (select * from a_eke_sysPowers Where RoleID is Null and ApplicationItemID='" + _dr["ApplicationItemID"].ToString() + "' and ModelID='" + _dr["ModelID"].ToString() + "'  and UserID='" + userid + "')";
                        sql += " update a_eke_sysPowers set delTag=0,canList='" + canList + "',Condition='" + cond + "',Propertys='" + prop + "',power='" + selPower.ToJson() + "' where RoleID is Null and ApplicationID='" + _dr["ApplicationID"].ToString() + "' and ModelID='" + _dr["ModelID"].ToString() + "' and UserID='" + userid + "'";
                        sql += " else ";
                        sql += "insert into a_eke_sysPowers (PowerID,ApplicationItemID,ApplicationID,ModelID,UserID,canList,Condition,Propertys,Power) ";
                        sql += " values ('" + Guid.NewGuid().ToString() + "','" + _dr["ApplicationItemID"].ToString() + "','" + _dr["ApplicationID"].ToString() + "','" + _dr["ModelID"].ToString() + "','" + userid + "','" + canList + "','" + cond + "','" + prop + "','" + selPower.ToJson() + "')";
                        */
                        string ct = eBase.UserInfoDB.getValue("select count(1) from a_eke_sysPowers Where RoleID is Null and ApplicationItemID='" + _dr["ApplicationItemID"].ToString() + "' and ModelID='" + _dr["ModelID"].ToString() + "'  and UserID='" + userid + "'");
                        if (ct == "0")
                        {
                            sql = "insert into a_eke_sysPowers (PowerID,ApplicationItemID,ApplicationID,ModelID,UserID,canList,Condition,Propertys,Power) ";
                            sql += " values ('" + Guid.NewGuid().ToString() + "','" + _dr["ApplicationItemID"].ToString() + "','" + _dr["ApplicationID"].ToString() + "','" + _dr["ModelID"].ToString() + "','" + userid + "','" + canList + "','" + cond + "','" + prop + "','" + selPower.ToJson() + "')";

                            eBase.UserInfoDB.eTable("a_eke_sysPowers")
                               .Fields.Add("PowerID", Guid.NewGuid().ToString())
                               .Fields.Add("ApplicationItemID", _dr["ApplicationItemID"].ToString())
                               .Fields.Add("ApplicationID", _dr["ApplicationID"].ToString())
                               .Fields.Add("ModelID", _dr["ModelID"].ToString())
                               .Fields.Add("UserID", userid)
                               .Fields.Add("canList", canList)
                               .Fields.Add("Condition", cond)
                               .Fields.Add("Propertys", prop)
                               .Fields.Add("Power", selPower.ToJson())
                               .Add();
                        }
                        else
                        {
                            //sql = " update a_eke_sysPowers set delTag=0,canList='" + canList + "',Condition='" + cond + "',Propertys='" + prop + "',power='" + selPower.ToJson() + "' where RoleID is Null and ApplicationID='" + _dr["ApplicationID"].ToString() + "' and ModelID='" + _dr["ModelID"].ToString() + "' and UserID='" + userid + "'";
                            eBase.UserInfoDB.eTable("a_eke_sysPowers")
                               .Fields.Add("delTag", 0)
                               .Fields.Add("canList", canList)
                               .Fields.Add("Condition", cond)
                               .Fields.Add("Propertys", prop)
                               .Fields.Add("Power", selPower.ToJson())
                               .Where.Add("ApplicationItemID='" + _dr["ApplicationItemID"].ToString() + "'")
                               .Where.Add("ModelID='" + _dr["ModelID"].ToString() + "'")
                               .Where.Add("UserID='" + userid + "'")
                               .Update();
                        }
                       // eBase.UserInfoDB.Execute(sql);

                    }
                    if (_dr["ApplicationItemID"].ToString().Length > 0) appitems += (appitems.Length == 0 ? "" : ",") + "'" + _dr["ApplicationItemID"].ToString() + "'";
                    if( _dr["ModelID"].ToString().Length > 0)  modelids += (modelids.Length == 0 ? "" : ",") + "'" + _dr["ModelID"].ToString() + "'";
                }
                #region 清理应用里不存在的权限
                if (appitems.Length > 0)
                {
                    sql = "delete from a_eke_sysPowers where RoleID is Null and UserID='" + userid + "' and ApplicationID='" + dr["ApplicationID"].ToString() + "' and ApplicationItemID not in (" + appitems + ")";
                    eBase.UserInfoDB.Execute(sql);
                }
                if (modelids.Length > 0)
                {
                    sql = "delete from a_eke_sysPowers where RoleID is Null and UserID='" + userid + "' and ApplicationID='" + dr["ApplicationID"].ToString() + "' and ModelID not in (" + modelids + ")";
                    eBase.UserInfoDB.Execute(sql);
                }
                #endregion
            }
            
        }
        private string getmodels(DataTable rolePower, string appid, string parentid)
        {

            StringBuilder sb = new StringBuilder();
            DataRow[] rs = ApplitionItems.Select("ApplicationID='" + appid + "' and " + (parentid.Length > 0 ? "ParentID='" + parentid + "'" : "ParentID is null"),"px,addTime");         
            foreach (DataRow _dr in rs) //应用下所有模块
            {
                string cond = "";
                string prop = "";
                string name = "";
                if (_dr["ModelID"].ToString().Length > 0) //模块
                {
                    DataRow[] rss = UserPower.Select("ApplicationID='" + appid + "' and ApplicationItemID='" + _dr["ApplicationItemID"].ToString() + "'");//新增加                 
                    if (!model.Power["allpower"])
                    {
                        if (rss.Length == 0) continue;//新增加
                    }
                    #region 模块
                    sb.Append("<div class=\"powerModel\">");
                    DataRow row = rolePower.NewRow();
                    row["ApplicationItemID"] = _dr["ApplicationItemID"].ToString();
                    row["ApplicationID"] = _dr["ApplicationID"].ToString();
                    row["ModelID"] = _dr["ModelID"].ToString();
                    for (int i = 0; i < row.Table.Columns.Count; i++)
                    {
                        if (row.Table.Columns[i].ColumnName.ToLower() != "applicationitemid" && row.Table.Columns[i].ColumnName.ToLower() != "applicationid" && row.Table.Columns[i].ColumnName.ToLower() != "modelid")
                        {
                            row[row.Table.Columns[i].ColumnName] = "false";
                        }
                    }
                    DataRow[] rows = rolePower.Select("ApplicationItemID='" + _dr["ApplicationItemID"].ToString() + "' and ApplicationID='" + _dr["ApplicationID"].ToString() + "' and ModelID='" + _dr["ModelID"].ToString() + "'");
                    if (rows.Length > 0) row = rows[0];

                    sb.Append("<span class=\"modelname\">");
                    name = "model_" + _dr["ApplicationItemID"].ToString().Replace("-", "") + "_" + _dr["ModelID"].ToString().Replace("-", "");
                    sb.Append("<input type=\"checkbox\" name=\"" + name + "\" id=\"" + name + "\" value=\"true\" onclick=\"userSelectAll(this);\"" + (row["List"].ToString() == "true" ? " checked" : "") + (act == "view" ? " disabled" : "") + " />");
                    sb.Append("<label for=\"" + name + "\">" + _dr["mc"].ToString() + "</label>");
                    sb.Append("</span>");
                    #region 开发平台
                    if (filename.StartsWith("app"))
                    {
                        if (userid.Length > 0)
                        {
                            //sql = "select Condition from a_eke_sysPowers where ModelID='" + _dr["ModelID"].ToString() + "' and UserID='" + userid + "' and RoleID is Null and ApplicationItemID='" + _dr["ApplicationItemID"].ToString() + "' and delTag=0";
                            //cond = eBase.DataBase.getValue(sql);
                            DataRow[] conds = a_eke_sysPowers.Select("ModelID='" + _dr["ModelID"].ToString() + "' and UserID='" + userid + "' and RoleID is Null and ApplicationItemID='" + _dr["ApplicationItemID"].ToString() + "'");
                            if (conds.Length > 0)
                            {
                                cond = conds[0]["Condition"].ToString();
                                prop = conds[0]["Propertys"].ToString();
                            }
                        }

                        name = "model_cond_" + _dr["ApplicationItemID"].ToString().Replace("-", "") + "_" + _dr["ModelID"].ToString().Replace("-", "");
                        sb.Append("<span class=\"cond\">");
                        sb.Append("条件：<input type=\"text\" class=\"text\" name=\"" + name + "\" value=\"" + cond + "\"" + (act == "view" ? " disabled" : "") + " />");
                        sb.Append("</span>");

                        if (prop.Length == 0) prop = "{}";
                        name = "model_prop_" + _dr["ApplicationItemID"].ToString().Replace("-", "") + "_" + _dr["ModelID"].ToString().Replace("-", "");
                        sb.Append("<span class=\"cond\">");
                        sb.Append("扩展：<textarea style=\"height:20px;vertical-align:middle;\" name=\"" + name + "\" value=\"" + prop + "\"" + (act == "view" ? " disabled" : "") + ">" + prop + "</textarea>");
                        sb.Append("</span>");
                    }
                    #endregion

                    DataTable Power = _dr["Power"].ToString().ToJsonData().toRows();

                    #region 基本权限
                    foreach (DataRow dr1 in Power.Rows)
                    {
                        if (rss.Length > 0 && !rss[0].Table.Columns.Contains(dr1["value"].ToString())) continue;//新增加
                        //if (rss.Length > 0 && rss[0][dr1["value"].ToString()].ToString().ToLower() != "true") continue;//新增加(本人无权限，则退出)
                        name = "model_" + dr1["value"].ToString() + "_" + _dr["ApplicationItemID"].ToString().Replace("-", "") + "_" + _dr["ModelID"].ToString().Replace("-", "");
                        sb.Append("<span class=\"poweritem\">");
                        sb.Append("<input type=\"checkbox\" name=\"" + name + "\" id=\"" + name + "\" value=\"true\"" + (row.Contains(dr1["value"].ToString()) && row[dr1["value"].ToString()].ToString() == "true" ? " checked" : "") + (act == "view" ? " disabled" : ""));
                        if (dr1["value"].ToString().ToLower() == "list") sb.Append(" onclick=\"userCanelAll(this);\"");
                        sb.Append(" />");
                        sb.Append("<label for=\"" + name + "\">" + dr1["text"].ToString() + "</label>");
                        sb.Append("</span>");
                    }
                    #endregion
                    #region 审批权限
                    DataRow[] _rs = CheckUps.Select("ModelID='" + _dr["ModelID"].ToString() + "'", "px,addTime"); 
                    foreach (DataRow dr1 in _rs)
                    {
                        if (!row.Table.Columns.Contains(dr1["value"].ToString()))
                        {
                            row.Table.Columns.Add(dr1["value"].ToString(), typeof(string));
                            row[dr1["value"].ToString()] = "false";
                        }
                    }
                    foreach (DataRow dr1 in _rs)
                    {
                        if (rss.Length > 0 && !rss[0].Table.Columns.Contains(dr1["value"].ToString())) continue;//新增加
                        //if (rss.Length > 0 && rss[0][dr1["value"].ToString()].ToString().ToLower() != "true") continue;//新增加(本人无权限，则退出)
                        name = "model_" + dr1["value"].ToString() + "_" + _dr["ApplicationItemID"].ToString().Replace("-", "") + "_" + _dr["ModelID"].ToString().Replace("-", "");
                        sb.Append("<span class=\"powercheckupitem\">");
                        sb.Append("<input type=\"checkbox\" name=\"" + name + "\" id=\"" + name + "\" value=\"true\"" + (row[dr1["value"].ToString()].ToString() == "true" ? " checked" : "") + (act == "view" ? " disabled" : "") + " />");
                        sb.Append("<label for=\"" + name + "\">" + dr1["text"].ToString() + "</label>");
                        sb.Append("</span>");

                    }
                    #endregion
                    sb.Append("</div>");
                    #endregion
                    if (_dr["ApplicationItemID"].ToString() == "6d396879-e05f-4063-97f0-40474c3c0fed")
                    {
                    }
                }
                else //目录
                {
                    DataRow[] subrows = ApplitionItems.Select("ApplicationID='" + _dr["ApplicationID"].ToString() + "' and ParentID='" + _dr["ApplicationItemID"].ToString() + "'");
                    if (subrows.Length == 0) continue;
                    if (!model.Power["allpower"])
                    {
                        DataRow[] _rows = (from row in subrows.AsEnumerable()
                                          where
                                          UserPowerIDS.Any(p => row["ApplicationItemID"].ToString().Contains(p))
                                          select row).ToArray();
                        if (_rows.Length == 0) continue;
                    }

                    sb.Append("<div class=\"powerico\">\r\n");
                    sb.Append("<a href=\"javascript:;\" class=\"close\" onclick=\"showPower(this);\">" + _dr["MC"].ToString() + "</a>");
                    sb.Append("</div>\r\n");

                    sb.Append("<div class=\"powerContent\" style=\"display:none;\">\r\n");
                    sb.Append("<label style=\"margin-left:27px;\"><input type=\"checkbox\" onclick=\"SelectContent(this);\"" + (act == "view" ? " disabled" : "") + ">全选</label>");
                    sb.Append(getmodels(rolePower, _dr["ApplicationID"].ToString(), _dr["ApplicationItemID"].ToString()));
                    sb.Append("</div>\r\n");
                }
            }
            return sb.ToString();
        }
        private string getAppUserPower(string selRoles)
        {
            //eBase.PrintDataTable(UserPower);
            //eBase.Writeln(string.Join(",", UserPowerIDS));
            string userRoles = eBase.UserInfoDB.getValue("SELECT RoleID FROM a_eke_sysUsers where UserID='" + userid + "'");//当前编辑用户的角色
            string user_Roles = eBase.UserInfoDB.getValue("SELECT RoleID FROM a_eke_sysUsers where UserID='" + user.ID + "'");//当前登录用户的角色
            sql = "select a.RoleID,a.MC from a_eke_sysRoles a where a.delTag=0 and (a.SiteID in (0," + user["SiteID"] + ") or a.SiteID is null)";
            if (!model.Power["allpower"] && user["usertype"].ToString() != "1") sql += " and a.RoleID in ('" + user_Roles.Replace(",", "','") + "')";
            sql += " order by a.addTime";

            DataTable tb = eBase.UserInfoDB.getDataTable(sql);
            StringBuilder sb = new StringBuilder();
            #region 角色OK
            sb.Append("<div>\r\n");
            foreach (DataRow dr in tb.Rows)
            {
                sb.Append("<span class=\"rolename\">");
                sb.Append("<input type=\"checkbox\" name=\"Roles\" id=\"Roles_" + dr["RoleID"].ToString() + "\" value=\"" + dr["RoleID"].ToString() + "\"" + (userRoles.IndexOf(dr["RoleID"].ToString()) > -1 ? " checked" : "") + " onclick=\"selectRoles(this);\"" + (act == "view" ? " disabled" : "") + " />");
                sb.Append("<label for=\"Roles_" + dr["RoleID"].ToString() + "\">" + dr["MC"].ToString() + "</label>");
                sb.Append("</span>");
            }
            sb.Append("</div>\r\n");
            #endregion
            #region 权限
            DataTable rolePower = eBase.getUserPower(selRoles, userid);//当前用户的权限
            //eBase.Writeln("<hr>");
            //eBase.PrintDataTable(rolePower);
            //eBase.Writeln("<hr>");
            //eBase.PrintDataTable(rolePower2);
            /*
            foreach (DataRow dr in rolePower2.Rows)
            {
                if (dr["ApplicationItemID"].ToString() == "178db2d2-9a74-4dc0-a1cb-f5ebedc253b3")
                {
                    eBase.PrintDataRow(dr);
                }
            }
            */

            sb.Append("<div class=\"powerico\">\r\n");
            sb.Append("<a href=\"javascript:;\" class=\"close\" onclick=\"showPower(this);\">详细权限</a>");
            sb.Append("</div>\r\n");
            sb.Append("<div class=\"powerContent\" style=\"display:none;\">\r\n");
            foreach (DataRow dr in Applications.Rows) //所有应用
            {
                DataRow[] rows = ApplitionItems.Select("ApplicationID='" + dr["ApplicationID"].ToString() + "' and ParentID is null", "px,addTime");
                if (rows.Length == 0) continue;
                DataRow[] rss = UserPower.Select("ApplicationID='" + dr["ApplicationID"].ToString() + "' and list='true'");
                if (rss.Length == 0) continue;//新增加

                sb.Append("<div class=\"powerico\">\r\n");
                sb.Append("<a href=\"javascript:;\" class=\"close\" onclick=\"showPower(this);\">" + dr["MC"].ToString() + "</a>");
                sb.Append("</div>\r\n");
                sb.Append("<div class=\"powerContent\" style=\"display:none;\">\r\n");
                sb.Append("<label style=\"margin-left:27px;\"><input type=\"checkbox\" onclick=\"SelectContent(this);\"" + (act == "view" ? " disabled" : "") + ">全选</label>");
                sb.Append(getmodels(rolePower, dr["ApplicationID"].ToString(), ""));
                sb.Append("</div>\r\n");
            }
            sb.Append("</div>\r\n");
            #endregion
            return sb.ToString();
        }
    }
}