using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Diagnostics;
using System.Text;
using EKETEAM.FrameWork;
using EKETEAM.Data;


/// <summary>
/// ApplicationMenu 的摘要说明
/// </summary>
public class ModelMenu
{
    private eUser user;
    private string modelid = "";
    public string ModelID
    {
        get
        {
            return modelid;
        }
        set
        {
            modelid = value;
        }
    }
    private string curmenuids = "";    
    public string curMenuIDS  //当前菜单ID及所有上级
    {
        get
        {
            return curmenuids;
        }
        set
        {
            curmenuids = value;
        }
    }
    private List<string> _allMenuIDS = new List<string>();//所有模块及模块的上级菜单编号
    public List<string> allMenuIDS
    {
        get {
            return _allMenuIDS;
        }
    }
    //当前用户有权限的所有模块
    private DataTable _usermodels;
    public DataTable UserModels
    {
        get
        {
            if (_usermodels == null)
            {
                DataRow[] rows;
                // string roleids = eBase.DataBase.getValue("select roleid from a_eke_sysUsers where UserID='" + user["ID"].ToString() + "'");
                string roleids = eBase.getUserRoleIDS(user);
                /*
                if (user["userroleid"].ToString().Length > 0)
                {
                    roleids = user["userroleid"].ToString();
                }
                else
                {
                    rows = eBase.a_eke_sysUsers.Select("UserID='" + user.ID + "'");
                    if (rows.Length > 0)
                    {
                        roleids = rows[0]["RoleID"].ToString();
                    }
                    else
                    {
                        roleids = eBase.UserInfoDB.getValue("select roleid from a_eke_sysUsers where UserID='" + user["ID"].ToString() + "'");
                    }
                }
                */

                _usermodels = eBase.a_eke_sysModels.Clone();
                _usermodels.PrimaryKey = null;
                //rows = eBase.a_eke_sysPowers.Select("canList=1 and (UserID='" + user.ID + "'" + (" or Convert(RoleID, 'System.String') in ('" + roleids.Replace(",", "','") + "')") + ") and ApplicationID is Null");
               // rows = eBase.a_eke_sysPowers.Select("canList=1 and (UserID='" + user.ID + "'" + (" or Str_RoleID in ('" + roleids.Replace(",", "','") + "')") + ") and ApplicationID is Null");

                rows = (from row in eBase.a_eke_sysPowers.AsEnumerable()
                        where row["canList"].ToString().Replace("True", "1") == "1" && row["ApplicationID"] == DBNull.Value &&
                        (row["UserID"].ToString() == user["ID"].ToString() || roleids.Contains(row["RoleID"].ToString()))
                        select row).ToArray();

                //Convert优化
                string ids = "";
                int idx = 0;
                foreach (DataRow dr in rows)
                {
                    if (idx > 0) ids += ",";
                    ids += "'" + dr["ModelID"].ToString() + "'";
                    idx++;
                    DataRow[] rowsa = eBase.a_eke_sysModels.Select("ModelID='" + dr["ModelID"].ToString() + "'");
                    if (rowsa.Length > 0)
                    {
                        _usermodels.Rows.Add(rowsa[0].ItemArray);
                    }
                }
            }
            return _usermodels;
        }
    }
    //所有模块
    private DataTable _allmodels;
    public DataTable allModels
    {
        get
        {
            if (_allmodels == null)
            {
                DataRow[] rows = eBase.a_eke_sysModels.Select("subModel=0", "px,addTime desc");
                if (rows.Length == 0)
                {
                    _allmodels = eBase.a_eke_sysModels.Clone();
                }
                else
                {
                    _allmodels = eBase.toDataTable(rows);
                }
            }

            return _allmodels;
        }
    }
    public ModelMenu(eUser user)
    {
        this.user = user;
        modelid = eParameters.Request("modelid");
        if (modelid.Length == 0) return;
        curMenuIDS = getCurMenuIDS(modelid);
        foreach (DataRow dr in UserModels.Rows)
        {
            addAllMenuIDS(dr["ModelID"].ToString());
        }
    }
    public string gethref(DataRow dr)
    {
        string url = "";
        if (dr["Finsh"].ToString() == "False")
        {
            url = "Model.aspx?ModelID=" + dr["ModelID"].ToString() + "&act=building";
        }
        else
        {
            if (dr["AspxFile"].ToString().Length > 0 && dr["Auto"].ToString() == "False")
            {
                url = "Custom.aspx?ModelID=" + dr["ModelID"].ToString();
            }
            else
            {
                url = "Model.aspx?ModelID=" + dr["ModelID"].ToString();
            }
        }
        url+= HttpContext.Current.Request.QueryString["debug"] != null ? "&debug=1" : "";
        return url;
    }
    private string getCurMenuIDS(string ModelID)
    {
        if (ModelID.Length == 0) return "";
        string _back = "";
        DataRow[] rows = allModels.Select("ModelID='" + ModelID + "'");
        if (rows.Length == 0) return "";
        string pid = rows[0]["ParentID"].ToString();
        if (pid.Length == 0)
        {
            _back = ModelID;
        }
        else
        {
            _back = getCurMenuIDS(pid) + "," + ModelID;
        }
        return _back;
    }
    private void addAllMenuIDS(string ModelID)
    {
        DataRow[] rows = allModels.Select("ModelID='" + ModelID + "'");
        if (rows.Length > 0)
        {
            allMenuIDS.Add(ModelID);
            string ParentID = rows[0]["ParentID"].ToString();
            if (ParentID.Length > 0)
            {
                addAllMenuIDS(ParentID);
            }
        }
    }
}
public class ApplicationMenu
{
    private eUser _user;
    private eUser User
    {
        get
        {
            return _user;
        }
    }
    private string _modelid = "";
    public string ModelID
    {
        get
        {
            return _modelid;
        }
    }
    private string _applicationid = "";
    public string ApplicationID
    {
        get
        {
            return _applicationid;
        }
    }
    private string _appitem = "";
    public string AppItem
    {
        get
        {
            return _appitem;
        }
    }
    public string ApplicationItemID
    {
        get
        {
            return AppItem;
        }
    }
    private object _lockMe = new object();
    private string _apptype;// = "1";//PC
    public string AppType
    {
        get
        {
            if (_apptype == null)
            {
                _apptype = !eBase.IsMobile() ? "1" : "2";
            }
            return _apptype;
        }
    }
    //用户的角色
    private List<string> _userroleid;
    private List<string> UserRoleID
    {
        get
        {
            if (_userroleid == null)
            { 
                /*
                if (User["userroleid"].ToString().Length > 0)
                {                  
                    _userroleid = new List<string>();
                    foreach (string role in User["userroleid"].ToString().toArray())
                    {
                        _userroleid.Add(role);
                    }                   
                    return _userroleid;
                }
                */
                _userroleid = eBase.getUserRoleID(User.ID);
            }
            return _userroleid;
        }
    }

    //企业的应用
    private List<string> _siteapps;
    private List<string> SiteApps
    {
        get
        {
            if (_siteapps == null)
            {
                _siteapps = new List<string>();
                DataRow[] rows = new DataTable().Select();
                if (User["siteid"].Length > 0) rows = eBase.a_eke_sysSiteItems.Select("SiteID=" + User["siteid"]);
                foreach (DataRow dr in rows)
                {
                    if (!_siteapps.Contains(dr["ApplicationID"].ToString()))
                    {
                        _siteapps.Add(dr["ApplicationID"].ToString());
                    }
                }
            }
            return _siteapps;
        }
    }

    private DataTable _userapps;
    private DataTable getUserApps
    {
        get
        {

            //lock (_lockMe)
            //{
            if (HttpContext.Current.Items.Contains("getUserApps"))
            {
                return HttpContext.Current.Items["getUserApps"] as DataTable;
            }

            string cacheName = "AppMenu_UserApps";
            DataTable _getuserapps = new DataTable();
            Stopwatch sw = new Stopwatch();
            sw.Start();
            DataView dv = (from row in eBase.a_eke_sysPowers.AsEnumerable()
                           where (row["UserID"].ToString() == User["ID"].ToString() || UserRoleID.Contains(row["RoleID"].ToString()))
                           && row["canList"].ToString().Replace("True", "1") == "1" && row["ApplicationID"] != DBNull.Value && SiteApps.Contains(row["ApplicationID"].ToString())
                           select row).AsDataView();
            if (dv.Count == 0)
            {
                return _getuserapps;
            }
            _getuserapps = dv.ToTable(false, "ApplicationID", "ApplicationItemID", "ModelID", "UserID");



            DataRow[] rows = eBase.a_eke_sysPowers.Select("UserID='" + User.ID + "' and canList=0");
            #region 删除没有权限的模块
            foreach (DataRow dr in rows)
            {
                DataRow[] rs = _getuserapps.Select("ApplicationItemID='" + dr["ApplicationItemID"].ToString() + "' and ModelID='" + dr["ModelID"].ToString() + "'");
                if (rs.Length > 0) _getuserapps.Rows.Remove(rs[0]);
            }
            #endregion
            #region 连接
            rows = getAppItems.Select("ModelID is null and Url like 'http%'");
            foreach (DataRow dr in rows)
            {
                DataRow[] rs = _getuserapps.Select("ApplicationID='" + dr["ApplicationID"].ToString() + "' and ModelID is not null");
                if (rs.Length > 0)
                {
                    DataRow _dr = _getuserapps.Rows.Add();
                    _dr["ApplicationID"] = dr["ApplicationID"];
                    _dr["ApplicationItemID"] = dr["ApplicationItemID"];
                }
            }
            #endregion
            #region 增加结构
            _getuserapps.Columns.Add("AppType", typeof(int));
            _getuserapps.Columns.Add("DoMain", typeof(string)); //使用域名
            _getuserapps.Columns.Add("MC", typeof(string));
            _getuserapps.Columns.Add("Pic", typeof(string));
            _getuserapps.Columns.Add("Icon", typeof(string));
            _getuserapps.Columns.Add("IconActive", typeof(string));
            _getuserapps.Columns.Add("IconWidth", typeof(int));
            _getuserapps.Columns.Add("IconHeight", typeof(int));
            _getuserapps.Columns.Add("IconHTML", typeof(string));
            _getuserapps.Columns.Add("IconSize", typeof(int));
            _getuserapps.Columns.Add("appSort", typeof(int));
            _getuserapps.Columns.Add("appAddTime", typeof(DateTime));
            _getuserapps.Columns.Add("px", typeof(int));
            _getuserapps.Columns.Add("addTime", typeof(DateTime));
            _getuserapps.Columns.Add("Auto", typeof(bool));
            _getuserapps.Columns.Add("Finsh", typeof(bool));
            _getuserapps.Columns.Add("URL", typeof(string));
            _getuserapps.Columns.Add("href", typeof(string));
            _getuserapps.Columns.Add("ParentID", typeof(string));
            _getuserapps.Columns.Add("ModelName", typeof(string));
            _getuserapps.Columns.Add("has", typeof(bool));
            _getuserapps.Columns.Add("condDisable", typeof(string));
            _getuserapps.Columns.Add("show", typeof(bool));
            #endregion
            foreach (DataRow dr in _getuserapps.Rows)
            {
                #region 循环处理数据
                dr["DoMain"] = "";
                dr["UserID"] = User.ID;
                dr["IconWidth"] = 0;
                dr["IconHeight"] = 0;
                dr["IconSize"] = 0;

                DataRow[] _rs = eBase.a_eke_sysApplications.Select("ApplicationID='" + dr["ApplicationID"].ToString() + "'");
                if (_rs.Length > 0)
                {
                    //外层处理
                    if (_rs[0]["Type"].ToString() != AppType && _rs[0]["Type"].ToString() != "3") //1pc,2,mobile,3double
                    {
                        //dr["has"] = false;
                        //continue;
                    }
                    dr["AppType"] = _rs[0]["Type"];
                    dr["mc"] = _rs[0]["mc"];

                    dr["Pic"] = _rs[0]["Pic"].ToString().Length == 0 ? "../images/nopic.gif" : "../" + _rs[0]["Pic"];
                    dr["Icon"] = _rs[0]["Icon"].ToString().Length == 0 ? "" : "../" + _rs[0]["Icon"];
                    dr["IconActive"] = _rs[0]["IconActive"].ToString().Length == 0 ? "" : "../" + _rs[0]["IconActive"];
                    dr["IconHTML"] = _rs[0]["IconHTML"];
                    dr["appSort"] = _rs[0]["PX"] == DBNull.Value ? 999999 : _rs[0]["PX"];
                    dr["appAddTime"] = _rs[0]["addTime"];

                    if (_rs[0]["IconWidth"] != DBNull.Value) dr["IconWidth"] = _rs[0]["IconWidth"];
                    if (_rs[0]["IconHeight"] != DBNull.Value) dr["IconHeight"] = _rs[0]["IconHeight"];
                    if (_rs[0]["IconSize"] != DBNull.Value) dr["IconSize"] = _rs[0]["IconSize"];

                    dr["has"] = true;

                }
                else
                {

                    dr["has"] = false;
                    continue;
                }

                if (User["SiteID"].ToString().Length > 0)
                {
                    if (eBase.a_eke_sysSiteItems.Rows.Count > 0)
                    {
                        _rs = eBase.a_eke_sysSiteItems.Select("SiteID='" + User["SiteID"].ToString() + "' and ApplicationID='" + dr["ApplicationID"].ToString() + "'");
                        if (_rs.Length > 0)
                        {
                            if (_rs[0]["AppName"].ToString().Length > 0) dr["mc"] = _rs[0]["AppName"].ToString();
                            if (_rs[0]["DoMain"].ToString().Length > 0) dr["DoMain"] = _rs[0]["DoMain"].ToString();
                        }
                    }
                }
                #region 连接
                if (dr["ModelID"].ToString().Length == 0)
                {
                    _rs = getAppItems.Select("ApplicationItemID='" + dr["ApplicationItemID"].ToString() + "' and Url like 'http%'");
                    if (_rs.Length > 0)
                    {
                        dr["px"] = _rs[0]["px"];
                        dr["auto"] = false;
                        dr["finsh"] = true;
                        dr["addTime"] = _rs[0]["addTime"];
                        dr["ModelName"] = _rs[0]["MC"];
                        dr["condDisable"] = _rs[0]["condDisable"];
                        dr["href"] = _rs[0]["URL"];
                        dr["has"] = true;
                        continue;
                    }
                }
                #endregion
                _rs = eBase.a_eke_sysApplicationItems.Select("ApplicationItemID='" + dr["ApplicationItemID"].ToString() + "' and ModelID='" + dr["ModelID"].ToString() + "'"); // and ModelID='" + dr["ModelID"].ToString() + "'
                if (_rs.Length > 0)
                {
                    dr["px"] = _rs[0]["px"];
                    dr["addTime"] = _rs[0]["addTime"];
                    dr["Finsh"] = _rs[0]["Finsh"];
                    dr["URL"] = _rs[0]["URL"];
                    dr["ParentID"] = _rs[0]["ParentID"];
                    dr["ModelName"] = _rs[0]["MC"];
                    dr["condDisable"] = _rs[0]["condDisable"];
                    dr["show"] = _rs[0]["show"];
                    dr["has"] = true;
                }
                else
                {
                    dr["has"] = false;
                    continue;
                }
                _rs = eBase.a_eke_sysModels.Select("ModelID='" + dr["ModelID"].ToString() + "'");
                if (_rs.Length == 0)
                {
                    dr["has"] = false;
                    continue;
                }
                else
                {
                    dr["Auto"] = _rs[0]["Auto"];
                    dr["href"] = gethref(dr);
                }
                #endregion
            }
            #region 删除没有的行
            for (int i = _getuserapps.Rows.Count - 1; i >= 0; i--)
            {
                if (_getuserapps.Rows[i]["has"].ToString().ToLower() == "false")
                {
                    _getuserapps.Rows.Remove(_getuserapps.Rows[i]);
                    continue;
                }
                string cond = _getuserapps.Rows[i]["condDisable"].ToString();
                if (cond.Length > 0)
                {
                    cond = eParameters.Replace(cond, null, User);
                    string result = eVsa.Eval(cond);
                    if (result.ToLower() == "true")
                    {
                        _getuserapps.Rows.Remove(_getuserapps.Rows[i]);
                        continue;
                    }
                }
            }
            #endregion
            _getuserapps.Columns.Remove("has");
            _getuserapps.TableName = cacheName;
            sw.Stop();
            if (!HttpContext.Current.Items.Contains("getUserApps"))
            {
                HttpContext.Current.Items["getUserApps"] = _getuserapps;
            }
            return _getuserapps;
            //}
        }
    }
  
    /// <summary>
    /// 当前用户有权限的所有模块
    /// </summary>
    public DataTable UserApps
    {
        get
        {
            if (_userapps == null)
            {
                //lock (_lockMe)
                //{
                    if (HttpContext.Current.Items.Contains("UserApps"))
                    {
                        _userapps = HttpContext.Current.Items["UserApps"] as DataTable;
                        return _userapps;
                    }
                    Stopwatch sw = new Stopwatch();
                    sw.Start();
                    string cacheName = "AppMenu_UserApps";
                    runtimeCache cache = new runtimeCache();
                    DataTable cdt = cache[cacheName];

                    if (cdt.Columns.Contains("UserID"))
                    {
                        _userapps = cdt.Filter("UserID='" + User.ID + "'");
                        if (_userapps.Rows.Count == 0)
                        {
                            _userapps = getUserApps;
                            if (_userapps.Columns.Contains("ParentID")) cache.Append(_userapps);
                        }
                        else
                        {
                        }
                    }
                    else //空表
                    {
                        _userapps = getUserApps;
                        if (_userapps.Columns.Contains("ParentID")) cache.Append(_userapps);
                    }
                    sw.Stop();
                    //eBase.WriteTip(_userapps.Rows.Count.ToString() + ":取数据UserApps共用 " + sw.Elapsed.TotalMilliseconds.ToString() + " 毫秒");
                    if (!HttpContext.Current.Items.Contains("UserApps"))
                    {
                        if (_userapps.Columns.Contains("ParentID")) HttpContext.Current.Items["UserApps"] = _userapps;
                    }
                //}
            }
            return _userapps;
        }
    }

    private DataTable getApplications()
    {
        if (!UserApps.Columns.Contains("ApplicationID")) return new DataTable();
        DataTable tb = UserApps.DefaultView.ToTable(true, "ApplicationID", "MC", "AppType","DoMain", "Pic", "Icon", "IconActive", "IconHTML", "appSort", "appAddTime");
        tb.Columns.Add("UserID", typeof(string));
        tb.Columns["UserID"].SetOrdinal(0);
        tb.Columns.Add("ApplicationItemID", typeof(string));
        tb.Columns.Add("ModelName", typeof(string));
        tb.Columns.Add("href", typeof(string));
        tb.Columns.Add("IconWidth", typeof(int));
        tb.Columns.Add("IconHeight", typeof(int));
        tb.Columns.Add("IconSize", typeof(int));
        //eBase.PrintDataTable(UserApps);
        foreach (DataRow dr in tb.Rows)
        {
            dr["IconWidth"] = 0;
            dr["IconHeight"] = 0;
            dr["IconSize"] = 0;
            dr["UserID"] = User.ID;
           
            DataRow[] rs = !UserApps.Columns.Contains("ParentID") ?  new DataTable().Select() : (from row in UserApps.AsEnumerable()
                            where row["ApplicationID"].ToString() == dr["ApplicationID"].ToString() && row["ModelID"] != DBNull.Value && eBase.parseBool(row["show"]) == true
                            orderby row["ParentID"].ToString(), row["px"]
                            select row).Take(1).ToArray();
            if (rs.Length > 0)
            {
                dr["ApplicationItemID"] = rs[0]["ApplicationItemID"];
                dr["ModelName"] = rs[0]["ModelName"];
                dr["href"] = rs[0]["href"];
                if (rs[0]["IconWidth"] != DBNull.Value) dr["IconWidth"] = rs[0]["IconWidth"];
                if (rs[0]["IconHeight"] != DBNull.Value) dr["IconHeight"] = rs[0]["IconHeight"];
                if (rs[0]["IconSize"] != DBNull.Value) dr["IconSize"] = rs[0]["IconSize"];
            }
        }
        tb.TableName = "AppMenu_UserApplications";
        return tb;
    }
    private DataTable _applications;
    /// <summary>
    /// 用户有权限的所有应用
    /// </summary>
    public DataTable Applications
    {
        get
        {
            if (_applications == null)
            {
                if (HttpContext.Current.Items.Contains("UserApplications"))
                {
                    _applications = HttpContext.Current.Items["UserApplications"] as DataTable;
                    return _applications;
                }
                string cacheName = "AppMenu_UserApplications";              
                runtimeCache cache = new runtimeCache();
                DataTable cdt = cache[cacheName];
                if (cdt.Columns.Contains("UserID"))
                {
                    _applications = cdt.Filter("UserID='" + User.ID + "'");
                    if (_applications.Rows.Count == 0)
                    {
                        _applications = getApplications();
                        cache.Append(_applications);
                    }
                }
                else //空表
                {
                    _applications = getApplications();
                    cache.Append(_applications);
                }
                string domain = HttpContext.Current.Request.Url.Host;
                if (_applications.Columns.Contains("ApplicationID"))
                {
                    _applications = _applications.Select("(apptype='3' or apptype='" + _apptype + "') and (len(domain) = 0 or domain='" + domain + "')", "appSort,appAddTime").toDataTable();
                    if (!HttpContext.Current.Items.Contains("UserApplications"))
                    {
                        HttpContext.Current.Items["UserApplications"] = _applications;
                    }
                }
                //eBase.Print(_applications);
                //eBase.End();
            }
            return _applications;
        }
 
    }
   
    private DataTable getAppItems
    {
        get
        {
            string cacheName = "AppMenu_AppItems";
            DataTable _getappitems = new DataTable();
            DataRow[] rows = eBase.a_eke_sysApplicationItems.Select();
            if (rows.Length == 0) return _getappitems;

            _getappitems =  eBase.toDataTable(rows);
            #region 删除多余的列
            if (_getappitems.Columns.Contains("Extend")) _getappitems.Columns.Remove("Extend");
            if (_getappitems.Columns.Contains("Propertys")) _getappitems.Columns.Remove("Propertys");
            if (_getappitems.Columns.Contains("addUser")) _getappitems.Columns.Remove("addUser");
            if (_getappitems.Columns.Contains("editTime")) _getappitems.Columns.Remove("editTime");
            if (_getappitems.Columns.Contains("editUser")) _getappitems.Columns.Remove("editUser");
            if (_getappitems.Columns.Contains("delTime")) _getappitems.Columns.Remove("delTime");
            if (_getappitems.Columns.Contains("delUser")) _getappitems.Columns.Remove("delUser");
            if (_getappitems.Columns.Contains("delTag")) _getappitems.Columns.Remove("delTag");
            #endregion
            #region 添加字段
            _getappitems.Columns.Add("Auto", typeof(bool));
            _getappitems.Columns.Add("href", typeof(string));
            #endregion

            DataRow[] rs;
            foreach (DataRow dr in _getappitems.Rows)
            {
                if (dr["modelID"].ToString().Length == 0) continue;
                rs = eBase.a_eke_sysModels.Select("ModelID='" + dr["modelID"].ToString() + "'");
                if (rs.Length > 0)
                {
                    dr["Auto"] = rs[0]["Auto"];
                }
                dr["href"] = gethref(dr);
            }
            _getappitems.TableName = cacheName;
            return _getappitems;
        }
    }

    public DataRow getTopModel(string appid)
    {
        DataRow dr = new DataTable().NewRow();
        string cacheName = "AppMenu_AppItems";
        runtimeCache cache = new runtimeCache();
        DataTable cdt = cache[cacheName];
        if (!cdt.Columns.Contains("ApplicationItemID"))
        {
            cdt = getAppItems;
            cache.Append(cdt);
        }
        //eBase.PrintDataTable(cdt);
        DataRow[] rs = (from row in cdt.AsEnumerable()
                        where row["ApplicationID"].ToString() == appid && row["ParentID"] == DBNull.Value && MenuIDS.Contains(row["ApplicationItemID"].ToString())
                        orderby row["px"]
                        select row).Take(1).ToArray();
        
        if (rs.Length == 0)
        {
            rs = (from row in cdt.AsEnumerable()
                  where row["ApplicationID"].ToString() == appid && MenuIDS.Contains(row["ApplicationItemID"].ToString())
                  orderby row["px"]
                  select row).Take(1).ToArray();
        }
        if (rs.Length > 0) dr = rs[0];
        return dr;
    }
    public string getTopModelUrl(string appid)
    {
        DataRow row = getTopModel(appid);
        if (row.Table.Columns.Count==0) return "javascript:;";
        return row["href"].ToString() + (HttpContext.Current.Request.QueryString["debug"] != null ? "&debug=1" : "");
    }
    private string gethref(DataRow dr)
    {
        string url = "";
        if (dr["Finsh"].ToString() == "False")
        {
            url = "Model.aspx?AppItem=" + dr["ApplicationItemID"].ToString() + "&act=building";
        }
        else
        {
            if (dr["URL"].ToString().Length > 0)
            {
                url = dr["URL"].ToString();
                url = eParameters.Replace(url, null, User);
                url = url.Replace("{year}",DateTime.Now.Year.ToString());
                url = url.Replace("{month}", DateTime.Now.Month.ToString());
                url = url.Replace("{day}", DateTime.Now.Day.ToString());
                if (!url.ToLower().StartsWith("http") && url.ToLower().IndexOf("appitem=") == -1)
                {
                    url += (url.IndexOf("?") == -1 ? "?" : "&") + "AppItem=" + dr["ApplicationItemID"].ToString();
                }
            }
            else
            {
                url = (eBase.parseBool(dr["Auto"].ToString()) ? "Model.aspx" : "Custom.aspx") + "?AppItem=" + dr["ApplicationItemID"].ToString();
            }
        }
        return url;
    }
    private string _homeurl;
    public string HomeURL
    {
        get
        {
            if (_homeurl == null)
            {
                if (HttpContext.Current.Items.Contains("homeurl"))
                {
                    _homeurl = HttpContext.Current.Items["homeurl"].ToString();
                    return _homeurl;
                }
                DataRow[] rs = (from row in AppItems.AsEnumerable()
                                where row["ApplicationID"].ToString() == ApplicationID && row["ParentID"] == DBNull.Value && MenuIDS.Contains(row["ApplicationItemID"].ToString())
                                orderby row["px"]
                                select row).Take(1).ToArray();
                if (rs.Length == 0)
                {
                    rs = (from row in AppItems.AsEnumerable()
                          where row["ApplicationID"].ToString() == ApplicationID && MenuIDS.Contains(row["ApplicationItemID"].ToString())
                          orderby row["px"]
                          select row).Take(1).ToArray();
                }
                if (rs.Length == 0) return "javascript:;";
                return rs[0]["href"].ToString();
            }
            return _homeurl;
        }
    }
    /// <summary>
    /// 当前应用下所有模块
    /// </summary>
    public DataTable ApplicationItems
    {
        get
        {
            return AppItems;
        }
    }
    private DataTable _appitems;
    /// <summary>
    /// 当前应用下所有模块
    /// </summary>
    public DataTable AppItems
    {
        get
        {
            if (_appitems == null)
            {
                if (HttpContext.Current.Items.Contains("AppItems"))
                {
                    _appitems = HttpContext.Current.Items["AppItems"] as DataTable;
                    return _appitems;
                }
                Stopwatch sw = new Stopwatch();
                sw.Start();
                string cacheName = "AppMenu_AppItems";
                runtimeCache cache = new runtimeCache();
                DataTable cdt = cache[cacheName];
                if (cdt.Columns.Contains("ApplicationItemID"))
                {
                    _appitems = cache[cacheName].Filter("ApplicationID='" + ApplicationID + "'");
                    if (_appitems.Rows.Count == 0)
                    {
                        cdt = getAppItems;
                        cache.Append(cdt);
                        _appitems = ApplicationID.Length == 0 ? cdt : cdt.Filter("ApplicationID='" + ApplicationID + "'");
                    }
                    else
                    {
                    }
                }
                else //空表
                {
                    cdt=getAppItems;
                    cache.Append(cdt);
                    _appitems =ApplicationID.Length == 0 ? cdt : cdt.Filter("ApplicationID='" + ApplicationID + "'");
                }
                sw.Stop();
                if (_appitems.Columns.Contains("ApplicationItemID") && !HttpContext.Current.Items.Contains("AppItems"))
                { 
                    HttpContext.Current.Items["AppItems"] = _appitems; 
                }
            }
            return _appitems;
        }
    }

    private List<string> _menuids;
    public List<string> MenuIDS
    {
        get
        {
            if (_menuids == null)
            {
                if (HttpContext.Current.Items.Contains("MenuIDS"))
                {
                    _menuids = HttpContext.Current.Items["MenuIDS"] as List<string>;
                    return _menuids;
                }
                _menuids = new List<string>();
                //_menuids = (from row in UserApps.AsEnumerable() where row["ApplicationID"].ToString() == ApplicationID select row["ApplicationItemID"].ToString()).ToList();
                string[] ids = (from row in UserApps.AsEnumerable() where row["ApplicationID"].ToString() == ApplicationID select row["ApplicationItemID"].ToString()).ToArray();
                _menuids= ids.ToList();
                foreach (string appitem in ids)
                {
                    addMenuIDS(_menuids, appitem);
                }
                if (!HttpContext.Current.Items.Contains("MenuIDS"))
                {
                    HttpContext.Current.Items["MenuIDS"] = _menuids;
                }
                //eBase.WriteTip(_menuids.Count.ToString());
            }
            return _menuids;
        }
    }
    private void addMenuIDS(List<string> list, string appitem)
    {
        DataRow[] rows = AppItems.Select("ApplicationItemID='" + appitem + "'");
        if (rows.Length > 0)
        {
            if (!list.Contains(appitem)) list.Add(appitem);

            string ParentID = rows[0]["ParentID"].ToString();
            if (ParentID.Length > 0)
            {
                addMenuIDS(list,ParentID);
            }
        }
    }

    private List<string> _curmenuids;
    public List<string> curMenuIDS
    {
        get
        {
            if (_curmenuids == null)
            {
                _curmenuids = new List<string>();
                getCurMenuIDS(_curmenuids, AppItem);
            }
            return _curmenuids;
        }
    }
    private string _menuid;
    public string MenuID
    {
        get
        {
            if (_menuid == null)
            {
                _menuid = AppItem;
                if (AppItem.Length > 0)
                {
                    DataRow[] rows = AppItems.Select("ApplicationItemID='" + AppItem + "'");
                    if (rows.Length > 0)
                    {
                        if (rows[0]["PackID"].ToString().Length > 0) _menuid = rows[0]["PackID"].ToString();
                    }
                }
            }
            return _menuid;
        }
    }
    private void getCurMenuIDS(List<string> list, string appitem)
    {
        if (appitem.Length == 0) return;       
        DataRow[] rows = AppItems.Select("ApplicationItemID='" + appitem + "'");
        if (rows.Length == 0) return;
        if (rows[0]["PackID"].ToString().Length > 0) appitem = rows[0]["PackID"].ToString();
        list.Add(appitem);
        string pid = rows[0]["ParentID"].ToString();
        if (pid.Length > 0) getCurMenuIDS(list, pid);
    }
    public ApplicationMenu(string apptype)
	{
        if (eItems.Get("eUser") == null)
        {
            eBase.Writeln("请在使用模块前先验证用户登录状态!");
            eBase.End();
        }
        _apptype = apptype;
        _user = eItems.Get("eUser");
        _appitem = eParameters.QueryString("AppItem");
        _applicationid = eParameters.QueryString("AppID");
        if (_appitem.Length > 0)
        {
            DataRow[] rows = eBase.a_eke_sysApplicationItems.Select("ApplicationItemID='" + _appitem + "'");
            if (rows.Length > 0)
            {
                _modelid = rows[0]["ModelID"].ToString();
                _applicationid = rows[0]["ApplicationID"].ToString();
            }
            if (!HttpContext.Current.Items.Contains("homeurl")) HttpContext.Current.Items["homeurl"] = HomeURL;
        }
        if (_applicationid.Length == 0)
        {
            DataRow[] rs = (from row in UserApps.AsEnumerable()
                            where row["apptype"].ToString() == _apptype || row["apptype"].ToString()=="3"
                            orderby row["appsort"],row["appAddTime"]
                            select row).Take(1).ToArray();
            if (rs.Length > 0) _applicationid = rs[0]["ApplicationID"].ToString();
        }        
    }
    public ApplicationMenu(eUser user,string apptype)
    {
        if (eItems.Get("eUser") == null)
        {
            eBase.Writeln("请在使用模块前先验证用户登录状态!");
            eBase.End();
        }
        _apptype = apptype;
        _user = user;
        _appitem = eParameters.QueryString("AppItem");
        _applicationid = eParameters.QueryString("AppID");
        if (_appitem.Length > 0)
        {
            DataRow[] rows = eBase.a_eke_sysApplicationItems.Select("ApplicationItemID='" + _appitem + "'");
            if (rows.Length > 0)
            {
                _modelid = rows[0]["ModelID"].ToString();
                _applicationid = rows[0]["ApplicationID"].ToString();
            }
            if (!HttpContext.Current.Items.Contains("homeurl")) HttpContext.Current.Items["homeurl"] = HomeURL;
        }
        if (_applicationid.Length == 0)
        {
            DataRow[] rs = (from row in UserApps.AsEnumerable()
                            orderby row["appsort"], row["appAddTime"]
                            select row).Take(1).ToArray();
            if (rs.Length > 0) _applicationid = rs[0]["ApplicationID"].ToString();
        }    
    }

    public string getMenus(string ParentID, int Level = 1, string target="")
    {
        if (AppType == "1")
        {
            return getPCMenus(ParentID, Level, target);
        }
        else
        {
            return getMobileMenus();
        }
    }
    private string getPCMenus(string ParentID, int Level = 1, string target = "")
    {
        //eBase.PrintDataTable(ApplicationItems);
        StringBuilder sb = new StringBuilder();
        if (ParentID.Length == 0)
        {
            sb.Append("<ul class=\"emenu\">\r\n");
        }
        else
        {
            sb.Append("<ul" + (curMenuIDS.IndexOf(ParentID) == -1 ? " style=\"display:none;\"" : "") + ">\r\n");
        }

        DataRow[] rows = ApplicationItems.Select(ParentID.Length == 0 ? "ParentID is Null and Show=1" : "ParentID='" + ParentID + "' and Show=1", "PX,addTime");
        for (int i = 0; i < rows.Length; i++)
        {
            if (!MenuIDS.Contains(rows[i]["ApplicationItemID"].ToString())) continue; //没有权限的模块不输出
            string curids = rows[i]["ApplicationItemID"].ToString();
            if (rows[i]["PackID"].ToString().Length > 0) curids = rows[i]["PackID"].ToString();
            sb.Append("<li><div class=\"level" + Level.ToString() + (MenuID == curids ? " cur" : "") + "\">");

            if (rows[i]["ModelID"].ToString().Length == 0)
            {
                if (rows[i]["url"].ToString().Length > 0)
                {
                    sb.Append("<a href=\"" + rows[i]["url"].ToString() + "\"");
                    if (target.Length > 0) sb.Append(" target=\"" + target + "\"");
                }
                else
                {
                    sb.Append("<a href=\"javascript:;\" onclick=\"showmenu(this);\"");
                    sb.Append(curMenuIDS.IndexOf(rows[i]["ApplicationItemID"].ToString()) > -1 ? " class=\"open\"" : " class=\"close\"");
                }
            }
            else
            {
                sb.Append("<a href=\"" + rows[i]["href"].ToString() + (HttpContext.Current.Request.QueryString["debug"] != null ? "&debug=1" : "") + "\"");
            }
            //sb.Append(rows[i]["Finsh"].ToString() == "False" ? " style=\"color:#666;\"" : "");
            sb.Append(rows[i]["Finsh"].ToString() == "False" ? " class=\"disable\"" : "");

            sb.Append(" title=\"" + rows[i]["mc"].ToString() + "\"");
            sb.Append(" onfocus=\"this.blur();\">");
            string iconhtml = rows[i]["IconHTML"].ToString();
            if (iconhtml.Length > 10)
            {
                if (rows[i].Contains("IconSize") && Convert.ToInt32(rows[i]["IconSize"]) > 0)
                {
                    iconhtml = iconhtml.Replace("<i", "<i style=\"font-size:" + rows[i]["IconSize"].ToString() + "px;\"");
                }
                sb.Append(iconhtml);
            }
            else
            {
                string iconpath = rows[i]["Icon"].ToString();
                string iconactivepath = rows[i]["IconActive"].ToString().Length > 10 ? rows[i]["IconActive"].ToString() : iconpath;
                if (iconpath.Length > 0)
                {
                    //sb.Append("<img" + (rows[i]["Finsh"].ToString() == "False" ? " class=\"gray\"" : "") + " src=\"../" + (appmenu.curMenuIDS.IndexOf(curids) > -1 ? iconactivepath : iconpath) + "\"align=\"absmiddle\" border=\"0\" >");
                }
                if (iconpath.Length > 0)
                {
                    sb.Append("<img");
                    if (rows[i].Contains("IconWidth") && rows[i].Contains("IconHeight") && (Convert.ToInt32(rows[i]["IconWidth"]) > 0 || Convert.ToInt32(rows[i]["IconHeight"]) > 0))
                    {
                        sb.Append(" style=\"" + (Convert.ToInt32(rows[i]["IconWidth"]) > 0 ? "width:" + rows[i]["IconWidth"].ToString() + "px;" : "") + (Convert.ToInt32(rows[i]["IconHeight"]) > 0 ? "height:" + rows[i]["IconHeight"].ToString() + "px;" : "") + "\"");
                    }
                    sb.Append(" class=\"def\" src=\"../" + iconpath + "\" onerror=\"this.src='../images/none.gif';\">");
                }
                if (iconactivepath.Length > 0)
                {
                    sb.Append("<img");
                    if (rows[i].Contains("IconWidth") && rows[i].Contains("IconHeight") && (Convert.ToInt32(rows[i]["IconWidth"]) > 0 || Convert.ToInt32(rows[i]["IconHeight"]) > 0))
                    {
                        sb.Append(" style=\"" + (Convert.ToInt32(rows[i]["IconWidth"]) > 0 ? "width:" + rows[i]["IconWidth"].ToString() + "px;" : "") + (Convert.ToInt32(rows[i]["IconHeight"]) > 0 ? "height:" + rows[i]["IconHeight"].ToString() + "px;" : "") + "\"");
                    }
                    sb.Append(" class=\"cur\" src=\"../" + iconactivepath + "\" onerror=\"this.src='../images/none.gif';\">");
                }

            }
            sb.Append(rows[i]["mc"].ToString());
            sb.Append("</a></div>");

            if (rows[i]["ModelID"].ToString().Length == 0)
            {
                sb.Append(getPCMenus(rows[i]["ApplicationItemID"].ToString(), Level + 1,target));
            }
            sb.Append("</li>\r\n");
        }
        sb.Append("</ul>\r\n");
        return sb.ToString();
    }
    private string getMobileMenus()
    {
        StringBuilder sb = new StringBuilder();
        DataRow[] rows, rs;
        #region 已分组
        rows = ApplicationItems.Select("ModelID is Null and Show=1", "PX,addTime");
        for (int i = 0; i < rows.Length; i++)
        {
            if (!MenuIDS.Contains(rows[i]["ApplicationItemID"].ToString()) && rows[i]["URL"] == DBNull.Value) continue;
            sb.Append("<dl class=\"eFunGroup\">\r\n");
            sb.Append("<dt>" + rows[i]["MC"].ToString() + "</dt>\r\n");
            sb.Append("<dd>\r\n");
            rs = ApplicationItems.Select("ParentID='" + rows[i]["ApplicationItemID"].ToString() + "' and ModelID is not Null and Show=1", "PX,addTime");
            for (int j = 0; j < rs.Length; j++)
            {
                if (!MenuIDS.Contains(rs[j]["ApplicationItemID"].ToString()) && rs[j]["URL"] == DBNull.Value) continue;
                if (rows[i]["ModelID"].ToString().Length == 0 && rs[j]["url"].ToString().Length > 0)
                {
                    sb.Append("<a href=\"" + rs[j]["url"].ToString() + "\" target=\"_blank\">");
                }
                else
                {
                    sb.Append("<a href=\"" + rs[j]["href"].ToString() + "\">");
                }
                string iconhtml = rs[j]["IconHTML"].ToString();
                if (iconhtml.Length > 10)
                {
                    if (rs[j].Contains("IconSize") && Convert.ToInt32(rs[j]["IconSize"]) > 0)
                    {
                        iconhtml = iconhtml.Replace("<i", "<i style=\"font-size:" + rs[j]["IconSize"].ToString() + "px;\"");
                    }
                    sb.Append(iconhtml);
                }
                else
                {
                    string iconpath = rs[j]["icon"].ToString();
                    if (iconpath.Length == 0) iconpath = "images/noicon.png";
                    sb.Append("<img");
                    if (rs[j].Contains("IconWidth") && rs[j].Contains("IconHeight") && (Convert.ToInt32(rs[j]["IconWidth"]) > 0 || Convert.ToInt32(rs[j]["IconHeight"]) > 0))
                    {
                        sb.Append(" style=\"" + (Convert.ToInt32(rs[j]["IconWidth"]) > 0 ? "width:" + rs[j]["IconWidth"].ToString() + "px;" : "") + (Convert.ToInt32(rs[j]["IconHeight"]) > 0 ? "height:" + rs[j]["IconHeight"].ToString() + "px;" : "") + "\"");
                    }
                    sb.Append((rs[j]["Finsh"].ToString() == "False" ? " class=\"gray\"" : "") + " src=\"../" + iconpath + "\"  />");
                }
                sb.Append("<p" + (rs[j]["Finsh"].ToString() == "False" ? " style=\"color:#ccc;\"" : "") + ">" + rs[j]["MC"].ToString() + "</p></a>\r\n");
            }
            sb.Append("</dd>\r\n");
            sb.Append("</dl>\r\n");
            sb.Append("<div class=\"clear\"></div>\r\n");
        }
        #endregion
        #region 未分组
        rs = ApplicationItems.Select("ModelID is not Null and ParentID is null and Show=1", "PX,addTime");
        if (rs.Length > 0)
        {
            sb.Append("<dl class=\"eFunGroup\">\r\n");
            sb.Append("<dt>未分组</dt>\r\n");
            sb.Append("<dd>\r\n");
            for (int j = 0; j < rs.Length; j++)
            {
                if (!MenuIDS.Contains(rs[j]["ApplicationItemID"].ToString()) && rs[j]["URL"] == DBNull.Value) continue;
                sb.Append("<a href=\"" + rs[j]["href"].ToString() + "\">");
                string iconhtml = rs[j]["IconHTML"].ToString();
                if (iconhtml.Length > 10)
                {
                    if (rs[j].Contains("IconSize") && Convert.ToInt32(rs[j]["IconSize"]) > 0)
                    {
                        iconhtml = iconhtml.Replace("<i", "<i style=\"font-size:" + rs[j]["IconSize"].ToString() + "px;\"");
                    }
                    sb.Append(iconhtml);
                }
                else
                {
                    string iconpath = rs[j]["icon"].ToString();
                    if (iconpath.Length == 0) iconpath = "images/noicon.png";
                    sb.Append("<img");
                    if (rs[j].Contains("IconWidth") && rs[j].Contains("IconHeight") && (Convert.ToInt32(rs[j]["IconWidth"]) > 0 || Convert.ToInt32(rs[j]["IconHeight"]) > 0))
                    {
                        sb.Append(" style=\"" + (Convert.ToInt32(rs[j]["IconWidth"]) > 0 ? "width:" + rs[j]["IconWidth"].ToString() + "px;" : "") + (Convert.ToInt32(rs[j]["IconHeight"]) > 0 ? "height:" + rs[j]["IconHeight"].ToString() + "px;" : "") + "\"");
                    }
                    sb.Append((rs[j]["Finsh"].ToString() == "False" ? " class=\"gray\"" : "") + " src=\"../" + iconpath + "\"  />");
                }
                sb.Append("<p" + (rs[j]["Finsh"].ToString() == "False" ? " style=\"color:#ccc;\"" : "") + ">" + rs[j]["MC"].ToString() + "</p></a>\r\n");
            }
            sb.Append("</dd>\r\n");
            sb.Append("</dl>\r\n");
            sb.Append("<div class=\"clear\"></div>\r\n");
        }
        #endregion
        return sb.ToString();
    }
    private void test()
    {
        List<string> list = eBase.getUserRoleID("F14761AB-9504-4F71-B412-C45C2B4E5A1C");
        foreach (string role in list)
        {
            eBase.Write(role + "::DD<br>");
        }
        eBase.Write(string.Join(",", list));


        DataTable tb = eBase.a_eke_sysApplicationMenus.Copy();
        Stopwatch sw = new Stopwatch();
        sw.Start();
        IEnumerable<DataRow> query = from row in tb.AsEnumerable()
                                     where row["ApplicationID"].ToString() == "531A3ABE-783F-4CD8-A479-AFB2E01B8F90".ToLower()
                                     select row;
        DataRow[] rows = query.ToArray();
        sw.Stop();
        eBase.Write(sw.Elapsed.TotalMilliseconds.ToString() + " 毫秒" + "<br>");
        foreach (DataRow dr in rows)
        {
            tb.Rows.Remove(dr);
        }
        eBase.PrintDataTable(tb);
    }
}