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

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 = eOleDB.DataBase; 
                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 LEN(CheckMC)>0 and LEN(CheckCode)>0";
                    _checkups = DataBase.getDataTable(sql);
                }
                return _checkups;
            }
        }
        private DataTable _applications;
        public DataTable Applications
        {
            get
            {
                if (_applications == null)
                {
                    _applications = DataBase.getDataTable("select ApplicationID,MC from a_eke_sysApplications where delTag=0 order by px,addTime");
                }
                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 Condition,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 ";
                    _applicationitems = DataBase.getDataTable(sql);
                }
                return _applicationitems;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            userid = eParameters.Request("id");
            act = eParameters.Request("act").ToLower();
            AppItem = eParameters.Request("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";
                    eOleDB.Execute(sql);
                    break;
                case "save":
                    save();
                    break;
                default:
                    string roleid = "";
                    if (userid.Length > 0) roleid = eOleDB.getValue("select roleid from a_eke_sysUsers where userid='" + userid + "'");
                    LitBody.Text = getAppUserPower(roleid);
                    break;
            }

           
        }
        private void save()
        {
            eJson json = null;
            string jsonstr = eParameters.Form("eformdata_" + parentModelID);
            if (jsonstr.Length > 0)
            {
                json = new eJson(jsonstr);
                json.Convert = true;
                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 + "'";
            eOleDB.Execute(sql);

            DataTable rolePower = eBase.getUserPower(Roles, "");
            //eBase.Writeln("rolePower：角色的权限");
            //eBase.PrintDataTable(rolePower);

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

            //eBase.Writeln("dt：所有应用");
            //eBase.PrintDataTable(dt);

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

                DataRow[] rs = ApplitionItems.Select("ApplicationID='" + dr["ApplicationID"].ToString() + "'", "px,addTime");


                foreach (DataRow _dr in rs) //应用下所有模块
                {
                    //string rolePowerString = eOleDB.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");
                    //eBase.Writeln("角色权限：" + rolePowerString);
                    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];

                    //eBase.Writeln("row");
                    //eBase.PrintDataRow(row);
                    DataTable PowerItems = new eJson(_dr["Power"].ToString()).toRows();
                    //eBase.Writeln("PowerItems");
                    //eBase.PrintDataTable(PowerItems);

                    #region 角色的权限
                    eJson rolePowerJson = new eJson();
                    rolePowerJson.Convert = true;
                    #region 基本权限
                    foreach (DataRow dr1 in PowerItems.Rows)
                    {
                        if (row.Table.Columns.Contains(dr1["value"].ToString()))
                        {
                            value = row[dr1["value"].ToString()].ToString();
                            eJson _power = new eJson();
                            _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();
                        eJson _power = new eJson();
                        _power.Add(dr1["value"].ToString(), value);
                        rolePowerJson.Add(_power);
                    }
                    #endregion
                    //eBase.Writeln(rolePowerJson.ToString());
                    #endregion

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

                    #region 用户自定义权限
                    eJson selPower = new eJson();
                    selPower.Convert = true;
                    #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";
                        eJson _power = new eJson();
                        _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";
                        eJson _power = new eJson();
                        _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);
                    cond = cond.Replace("'", "''");

                    if (selPower.ToString() == rolePowerJson.ToString() && cond.Length == 0) //与角色的相同
                    {
                        sql = " delete from a_eke_sysPowers where RoleID is Null and ApplicationItemID='" + _dr["ApplicationItemID"].ToString() + "' and ModelID='" + _dr["ModelID"].ToString() + "' and UserID='" + userid + "'";
                        eOleDB.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 + "',power='" + selPower.ToString() + "' 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 (ApplicationItemID,ApplicationID,ModelID,UserID,canList,Condition,Power) ";
                        sql += " values ('" + _dr["ApplicationItemID"].ToString() + "','" + _dr["ApplicationID"].ToString() + "','" + _dr["ModelID"].ToString() + "','" + userid + "','" + canList + "','" + cond + "','" + selPower.ToString() + "')";
                        eOleDB.Execute(sql);

                    }



                }
            }
            eBase.clearDataCache("a_eke_sysPowers");
        }
        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");

            //eBase.Writeln("P2:" + appid);
            //eBase.PrintDataRow(rs);


            string cond = "";
            string name = "";
            foreach (DataRow _dr in rs) //应用下所有模块
            {
                if (_dr["ModelID"].ToString().Length > 0)
                {
                    #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 ModelID='" + _dr["ModelID"].ToString() + "'");
                    if (rows.Length > 0) row = rows[0];
                    // eBase.PrintDataRow(row);


                    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>");

                    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 = eOleDB.getValue(sql);
                    }

                    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>");

                    DataTable Power = new eJson(_dr["Power"].ToString()).toRows();
                    //eBase.PrintDataTable(Power);

                    #region 基本权限
                    foreach (DataRow dr1 in Power.Rows)
                    {
                        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[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";
                        }
                    }


                    //eBase.PrintDataRow(row);
                    foreach (DataRow dr1 in _rs)
                    {
                        //eBase.Writeln(dr1["value"].ToString() + "::" + _dr["ModelID"].ToString());

                        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
                }
                else
                {
                    DataRow[] subrows = ApplitionItems.Select("ApplicationID='" + _dr["ApplicationID"].ToString() + "' and ParentID='" + _dr["ApplicationItemID"].ToString() + "'");
                    if (subrows.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(getmodels(rolePower, _dr["ApplicationID"].ToString(), _dr["ApplicationItemID"].ToString()));
                    sb.Append("</div>\r\n");
                }
            }
            return sb.ToString();
        }
        private string getAppUserPower(string selRoles)
        {

            string userRoles = eOleDB.getValue("SELECT RoleID FROM a_eke_sysUsers where UserID='" + userid + "'");
            sql = "select a.RoleID,a.MC from a_eke_sysRoles a where a.delTag=0 order by addTime";
            DataTable tb = eOleDB.getDataTable(sql);
            StringBuilder sb = new StringBuilder();
            #region 角色
            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>");
            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;

                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(getmodels(rolePower, dr["ApplicationID"].ToString(), ""));
                sb.Append("</div>\r\n");
            }
            sb.Append("</div>\r\n");
            #endregion
            return sb.ToString();
        }
    }
}