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 AppRolePower : System.Web.UI.Page
    {
        public string AppItem = "";
        public string roleid = "";
        public string act = "";
        private string parentModelID = "";
        string sql = "";
        /// <summary>
        /// 主库
        /// </summary>
        private eDataBase _database;
        private eDataBase DataBase
        {
            get
            {
                if (_database == null) _database = eOleDB.DataBase; 
                return _database;
            }
        }
        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.ApplicationID,a.ModelID,a.ParentID,a.MC,b.Power,c.Power as userPower,c.canList,c.Condition,c.RoleID,a.PX,a.addTime";
                    sql += " from a_eke_sysApplicationItems a";
                    sql += " left join a_eke_sysModels b on a.ModelID=b.ModelID";
                    sql += " left join a_eke_sysPowers c on a.ApplicationItemID=c.ApplicationItemID and a.ModelID=c.ModelID and c.delTag=0 and c.UserID is null and c.RoleID " + (roleid.Length == 0 ? "is null" : "='" + roleid + "'"); 
                    sql += " where a.delTag=0";
                    _applicationitems = DataBase.getDataTable(sql);
                }
                return _applicationitems;
            }
        }
        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;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            roleid = 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 RoleID='" + roleid + "' and UserId is null and ApplicationID is not null";
                    eOleDB.Execute(sql);
                    break;
                case "save":
                    save();
                    break;
                default:
                    LitBody.Text = getAppRolePower();
                    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];
            }          
            foreach (DataRow dr in Applications.Rows)
            {
                DataRow[] rows = ApplitionItems.Select("ApplicationID='" + dr["ApplicationID"].ToString() + "'", "px,addTime");
                foreach (DataRow _dr in rows)
                {
                    string name = "model_list_" + _dr["ApplicationItemID"].ToString().Replace("-", "") + "_" + _dr["ModelID"].ToString().Replace("-", "");
                    string value = json == null ? eParameters.Form(name) : json.GetValue(name); 

                    if (value.Length > 0) //有权限
                    {
                        string canList = "0";
                        string cond = "";
                        string power = "";
                        eJson uPower = new eJson();
                        uPower.Convert = true;
                        #region 基本权限
                        DataTable Power = new eJson(_dr["Power"].ToString()).toRows();
                        foreach (DataRow dr1 in Power.Rows)
                        {
                            name = "model_" + dr1["value"].ToString() + "_" + _dr["ApplicationItemID"].ToString().Replace("-", "") + "_" + _dr["ModelID"].ToString().Replace("-", "");
                            value = json == null ? eParameters.Form(name) : json.GetValue(name); 
                            eJson _power = new eJson();
                            if (value.Length == 0)
                            {
                                _power.Add(dr1["value"].ToString(), "false");
                                if (dr1["value"].ToString().ToLower() == "list") canList = "0";
                            }
                            else
                            {
                                _power.Add(dr1["value"].ToString(), "true");
                                if (dr1["value"].ToString().ToLower() == "list") canList = "1";
                            }
                            uPower.Add(_power);
                        }
                        #endregion
                        #region 审批权限
                        DataRow[] _rs = CheckUps.Select("ModelID='" + _dr["ModelID"].ToString() + "'", "px,addTime");
                        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); 
                            eJson _power = new eJson();
                            if (value.Length == 0)
                            {
                                _power.Add(dr1["value"].ToString(), "false");
                                if (dr1["value"].ToString().ToLower() == "list") canList = "0";
                            }
                            else
                            {
                                _power.Add(dr1["value"].ToString(), "true");
                                if (dr1["value"].ToString().ToLower() == "list") canList = "1";
                            }
                            uPower.Add(_power);
                        }
                        power = uPower.ToString();

                        //eBase.Writeln(canList + "::" + power);
                        #endregion
                        name = "model_cond_" + _dr["ApplicationItemID"].ToString().Replace("-", "") + "_" + _dr["ModelID"].ToString().Replace("-", "");
                        cond = json == null ? eParameters.Form(name) : json.GetValue(name);
                        cond = cond.Replace("'", "''");

                        sql = "if exists (select * from a_eke_sysPowers where UserID is Null and ApplicationItemID='" + _dr["ApplicationItemID"].ToString() + "' and ModelID='" + _dr["ModelID"].ToString() + "'  and RoleID='" + roleid + "')";
                        sql += " update a_eke_sysPowers set delTag=0,canList='" + canList + "',Condition='" + cond + "',power='" + power + "' where UserID is Null and ApplicationItemID='" + _dr["ApplicationItemID"].ToString() + "' and ModelID='" + _dr["ModelID"].ToString() + "'  and RoleID='" + roleid + "'";
                        sql += " else ";
                        sql += "insert into a_eke_sysPowers (ApplicationItemID,ApplicationID,ModelID,UserID,RoleID,canList,Condition,Power) ";
                        sql += " values ('" + _dr["ApplicationItemID"].ToString() + "','" + _dr["ApplicationID"].ToString() + "','" + _dr["ModelID"].ToString() + "',NULL,'" + roleid + "','" + canList + "','" + cond + "','" + power + "')";

                        DataBase.Execute(sql);
                    }
                    else //无权限
                    {
                        sql = "update a_eke_sysPowers set canList=0,Power='',Condition='',delTag=1 where userID is Null and ApplicationItemID='" + _dr["ApplicationItemID"].ToString() + "' and ModelID='" + _dr["ModelID"].ToString() + "' and RoleID='" + roleid + "'";
                        sql = "delete from a_eke_sysPowers where userID is Null and ApplicationItemID='" + _dr["ApplicationItemID"].ToString() + "' and ModelID='" + _dr["ModelID"].ToString() + "' and RoleID='" + roleid + "'";
                        DataBase.Execute(sql);
                    }
                }
            }
            eBase.clearDataCache("a_eke_sysPowers");
        }


        private string getmodels(string appid, string parentid)
        {
            StringBuilder sb = new StringBuilder();  
            DataRow[] rows = ApplitionItems.Select("ApplicationID='" + appid + "' and " + (parentid.Length > 0 ? "ParentID='" + parentid + "'" : "ParentID is null"), "px,addTime");
            foreach (DataRow _dr in rows)
            {
                if (_dr["ModelID"].ToString().Length > 0)
                {
                    #region 模块
                    sb.Append("<div class=\"powerModel\">");
                    sb.Append("<span class=\"modelname\">");
                    sb.Append("<input type=\"checkbox\" name=\"model_" + _dr["ApplicationItemID"].ToString().Replace("-", "") + "_" + _dr["ModelID"].ToString().Replace("-", "") + "\" id=\"model_" + _dr["ApplicationItemID"].ToString().Replace("-", "") + "_" + _dr["ModelID"].ToString().Replace("-", "") + "\" value=\"true\" onclick=\"userSelectAll(this);\"" + (_dr["canList"].ToString() == "True" ? " checked" : "") + (act == "view" ? " disabled" : "") + " />");
                    sb.Append("<label for=\"model_" + _dr["ApplicationItemID"].ToString().Replace("-", "") + "_" + _dr["ModelID"].ToString().Replace("-", "") + "\">" + _dr["mc"].ToString() + "</label>");
                    sb.Append("</span>");

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

                    DataTable Power = new eJson(_dr["Power"].ToString()).toRows();
                    DataTable UPower = new eJson(_dr["UserPower"].ToString()).toColumn();

                    #region 基本权限
                    foreach (DataRow dr1 in Power.Rows)
                    {
                        bool has = false;
                        if (UPower.Rows.Count > 0 && UPower.Columns.Contains(dr1["value"].ToString()))
                        {
                            has = Convert.ToBoolean(UPower.Rows[0][dr1["value"].ToString()].ToString());
                        }
                        sb.Append("<span class=\"poweritem\">");
                        sb.Append("<input type=\"checkbox\" name=\"model_" + dr1["value"].ToString() + "_" + _dr["ApplicationItemID"].ToString().Replace("-", "") + "_" + _dr["ModelID"].ToString().Replace("-", "") + "\" id=\"model_" + dr1["value"].ToString() + "_" + _dr["ApplicationItemID"].ToString().Replace("-", "") + "_" + _dr["ModelID"].ToString().Replace("-", "") + "\" value=\"true\"" + (has == true ? " checked" : "") + (act == "view" ? " disabled" : ""));
                        if (dr1["value"].ToString().ToLower() == "list") sb.Append(" onclick=\"userCanelAll(this);\"");
                        sb.Append(" />");
                        sb.Append("<label for=\"model_" + dr1["value"].ToString() + "_" + _dr["ApplicationItemID"].ToString().Replace("-", "") + "_" + _dr["ModelID"].ToString().Replace("-", "") + "\">" + dr1["text"].ToString() + "</label>");
                        sb.Append("</span>");
                    }
                    #endregion
                    #region 审批权限

                    DataRow[] _rs = CheckUps.Select("ModelID='" + _dr["ModelID"].ToString() + "'", "px,addTime"); 
                    foreach (DataRow dr1 in _rs)
                    {
                        bool has = false;
                        if (UPower.Rows.Count > 0 && UPower.Columns.Contains(dr1["value"].ToString()))
                        {
                            has = Convert.ToBoolean(UPower.Rows[0][dr1["value"].ToString()].ToString());
                        }
                        sb.Append("<span class=\"powercheckupitem\">");
                        sb.Append("<input type=\"checkbox\" name=\"model_" + dr1["value"].ToString() + "_" + _dr["ApplicationItemID"].ToString().Replace("-", "") + "_" + _dr["ModelID"].ToString().Replace("-", "") + "\" id=\"model_" + dr1["value"].ToString() + "_" + _dr["ApplicationItemID"].ToString().Replace("-", "") + "_" + _dr["ModelID"].ToString().Replace("-", "") + "\" value=\"true\"" + (has == true ? " checked" : "") + (act == "view" ? " disabled" : "") + " />");
                        sb.Append("<label for=\"model_" + dr1["value"].ToString() + "_" + _dr["ApplicationItemID"].ToString().Replace("-", "") + "_" + _dr["ModelID"].ToString().Replace("-", "") + "\">" + dr1["text"].ToString() + "</label>");
                        sb.Append("</span>");
                    }
                    #endregion
                    sb.Append("</div>");
                    #endregion
                }
                else
                {
                    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(_dr["ApplicationID"].ToString(), _dr["ApplicationItemID"].ToString()));
                    sb.Append("</div>\r\n");
                }

            }
            return sb.ToString();
        }
        private string getAppRolePower()
        {
            StringBuilder sb = new StringBuilder();
            foreach (DataRow dr in Applications.Rows)
            {
                
                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(dr["ApplicationID"].ToString(), ""));
                sb.Append("</div>");
            }
            return sb.ToString();
        }
    }
}