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

namespace eFrameWork.Manage
{
    public partial class ApplicationItems : System.Web.UI.Page
    {
        public string appName = "";
        public string AppId = eParameters.QueryString("AppId");
        public void updatePX(string ParentID)
        {
            string sql = "update a_eke_sysApplicationItems set PX=(";
            sql += "select b.rownum from ";
            sql += "(";
            sql += "select ROW_NUMBER() over(order by px,addtime) as rownum,ApplicationItemID,addTime from a_eke_sysApplicationItems where delTag=0 and ApplicationID='" + AppId + "'";
            sql += (ParentID.Length == 0 ? " and ParentID IS NULL" : " and ParentID='" + ParentID + "'");
            sql += ") as b where b.ApplicationItemID=a_eke_sysApplicationItems.ApplicationItemID";
            sql += ")  where delTag=0 and ApplicationID='" + AppId + "'";
            sql += (ParentID.Length == 0 ? " and ParentID IS NULL" : " and ParentID='" + ParentID + "'");
            eOleDB.Execute(sql);
        }
        private void getListItems(StringBuilder sb, string ParentID, int level)
        {
            updatePX(ParentID);
            string sql = "SELECT a.ApplicationItemID,a.PackID,a.ModelID,a.ParentID,a.MC,a.Condition,a.URL,a.Show,a.Finsh,a.DefaultValue,a.Icon,a.PX,b.Auto FROM a_eke_sysApplicationItems a";
            sql += " left join a_eke_sysModels b on a.ModelID=b.ModelID";
            sql += " where a.ApplicationID='" + AppId + "' " + (ParentID.Length == 0 ? " and a.ParentID is null" : " and a.ParentID='" + ParentID + "'") + " and a.delTag=0";
            sql += " order by a.PX,a.addTime";
            DataTable tb=eOleDB.getDataTable(sql);
            for (int i = 0; i < tb.Rows.Count; i++)
            {
                DataRow dr=tb.Rows[i];
                int ct = 0;              
                if (dr["modelid"].ToString().Length == 0) ct = Convert.ToInt32( eOleDB.getValue("select count(*) from a_eke_sysApplicationItems where ApplicationID='" + AppId + "'  and ParentID='" + dr["ApplicationItemID"].ToString() + "' and delTag=0"));
                int textIndent = level * 25;
                //if (ct > 0 && level > 0) textIndent -= 18;

                sb.Append("<tr erowid=\"" + dr["ApplicationItemID"].ToString() + "\" parentid=\"" + dr["ParentID"].ToString() + "\">\r\n");
                sb.Append("<td height=\"26\" align=\"center\"><a title=\"删除模块\" href=\"javascript:;\" onclick=\"delApp(this,'" + dr["ApplicationItemID"].ToString() + "');\"><img width=\"16\" height=\"16\" src=\"images/del.png\" border=\"0\"></a></td>\r\n");

                sb.Append("<td><input reload=\"true\" type=\"checkbox\" onclick=\"setApp(this,'" + dr["ApplicationItemID"].ToString() + "','show');\"" + (dr["show"].ToString() == "True" ? " checked" : "") + " /></td>\r\n");
                sb.Append("<td style=\"text-indent:" + textIndent.ToString() + "px;\">");
                if (ct > 0) { sb.Append("<a href=\"javascript:;\" class=\"open\" _onclick=\"showsub(this);\" style=\"margin:0px;\"></a>"); }
                //sb.Append("<span>" + dr["mc"].ToString() + "</span>");

                sb.Append("<input reload=\"true\" class=\"text\" style=\"width:" + (350 - textIndent - 20 - (ct>0 ? 18:0)) + "px;\" type=\"text\" value=\"" + System.Web.HttpUtility.HtmlEncode(dr["MC"].ToString()) + "\" oldvalue=\"" + System.Web.HttpUtility.HtmlEncode(dr["MC"].ToString()) + "\" onBlur=\"setApp(this,'" + dr["ApplicationItemID"].ToString() + "','mc');\">");
                sb.Append("</td>\r\n");
                sb.Append("<td>");
                sb.Append("<select reload=\"true\" onChange=\"setApp(this,'" + dr["ApplicationItemID"].ToString() + "','ModelID');\" style=\"width:140px;\">\r\n");
                sb.Append("<option value=\"NULL\">无</option>\r\n");
                sb.Append(eOleDB.getOptions("select MC,ModelID from a_eke_sysModels where delTag=0 and (Type=1 or Type=4 or Type=5) and subModel=0 order by addTime desc", "MC", "ModelID",dr["ModelID"].ToString()));
                sb.Append("<select>");
                sb.Append("</td>\r\n");
                sb.Append("<td>");
                sb.Append("<select reload=\"true\" onChange=\"setApp(this,'" + dr["ApplicationItemID"].ToString() + "','ParentID');\" style=\"width:140px;\">\r\n");
                sb.Append("<option value=\"NULL\">无</option>\r\n");
                sb.Append(eOleDB.getOptions("select ApplicationItemID,MC from a_eke_sysApplicationItems where delTag=0 and ModelID is null and len(mc)>0 and ApplicationItemID!='" + dr["ApplicationItemID"].ToString() + "' order by PX,addTime", "MC", "ApplicationItemID",dr["ParentID"].ToString()));
                sb.Append("<select>");
                sb.Append("</td>\r\n");
                sb.Append("<td>");
                if (dr["ModelID"].ToString().Length > 0)
                {

                    sb.Append("<select reload=\"false\" onChange=\"setApp(this,'" + dr["ApplicationItemID"].ToString() + "','PackID');\" style=\"width:140px;\">\r\n");
                    sb.Append("<option value=\"NULL\">无</option>\r\n");
                    //sb.Append(eOleDB.getOptions("select ApplicationItemID,MC from a_eke_sysApplicationItems where delTag=0 and (len(ModelID)>0" + (dr["PackID"].ToString().Length > 0 ? " or ApplicationItemID='" + dr["PackID"].ToString() + "'" : "") + ") and len(mc)>0 and ApplicationItemID!='" + dr["ApplicationItemID"].ToString() + "' order by PX,addTime", "MC", "ApplicationItemID", dr["PackID"].ToString()));
                    sb.Append(eOleDB.getOptions("select ApplicationItemID,MC from a_eke_sysApplicationItems where delTag=0 " + (dr["parentID"].ToString().Length > 0 ? " and ParentID='" + dr["parentID"].ToString() + "'" : " and ParentID is null") + " and (len(ModelID)>0" + (dr["PackID"].ToString().Length > 0 ? " or ApplicationItemID='" + dr["PackID"].ToString() + "'" : "") + ") and len(mc)>0 and ApplicationItemID!='" + dr["ApplicationItemID"].ToString() + "' order by PX,addTime", "MC", "ApplicationItemID", dr["PackID"].ToString()));
                    sb.Append("<select>");

                }
                else
                {
                    sb.Append("&nbsp;");
                }
                sb.Append("</td>");
                sb.Append("<td>");
                if (dr["ModelID"].ToString().Length > 0)
                {
                    sb.Append("<input class=\"text\" type=\"text\" value=\"" + System.Web.HttpUtility.HtmlEncode(dr["Condition"].ToString()) + "\" oldvalue=\"" + System.Web.HttpUtility.HtmlEncode(dr["Condition"].ToString()) + "\" onBlur=\"setApp(this,'" + dr["ApplicationItemID"].ToString() + "','condition');\">");
                }
                else
                {
                    sb.Append("&nbsp;");
                }
                sb.Append("</td>\r\n");
                sb.Append("<td>");
                if (dr["ModelID"].ToString().Length > 0)
                {
                    sb.Append("<input class=\"text\" type=\"text\" value=\"" + System.Web.HttpUtility.HtmlEncode(dr["DefaultValue"].ToString()) + "\" oldvalue=\"" + System.Web.HttpUtility.HtmlEncode(dr["DefaultValue"].ToString()) + "\" onBlur=\"setApp(this,'" + dr["ApplicationItemID"].ToString() + "','defaultvalue');\">");
                }
                else
                {
                    sb.Append("&nbsp;");
                }
                sb.Append("</td>\r\n");
                sb.Append("<td>");
                if (dr["ModelID"].ToString().Length > 0)
                {
                    string _url = dr["url"].ToString();
                    if (_url.Length == 0) _url = (dr["auto"].ToString() == "True" ? "Model.aspx" : "Custom.aspx") + "?AppItem=" + dr["ApplicationItemID"].ToString();

                    sb.Append("<input class=\"text\" type=\"text\" value=\"" + _url + "\" oldvalue=\"" + _url + "\"  style=\"width:120px;\" onBlur=\"setApp(this,'" + dr["ApplicationItemID"].ToString() + "','url');\" />");
                }
                else
                {
                    sb.Append("&nbsp;");
                }
                sb.Append("</td>\r\n");
                sb.Append("<td>");
                sb.Append("<input class=\"text\" type=\"text\" value=\"" + dr["icon"].ToString() + "\" oldvalue=\"" + dr["icon"].ToString() + "\"  style=\"display:none;width:140px;\" onBlur=\"setApp(this,'" + dr["ApplicationItemID"].ToString() + "','icon');\" />");
                sb.Append("<img src=\"../" + dr["icon"].ToString() + "\" style=\"min-width:20px;min-height:20px;max-width:24px;max-height:24px;vertical-align:middle;margin-right:6px;\" onerror=\"this.src='../images/none.gif';\">");
                sb.Append("<a href=\"javascript:;\" onclick=\"openIconForm(this);\">选择</a>");
                sb.Append("</td>\r\n");
                sb.Append("<td><select reload=\"false\" onChange=\"setApp(this,'" + dr["ApplicationItemID"] + "','finsh');\" style=\"width:70px;color:#" + (dr["finsh"].ToString() == "True" ? "33cc00" : "ff0000") + ";\">\r\n");
                sb.Append("<option value=\"\">无</option>\r\n");
                sb.Append("<option style=\"color:#33cc00;\" value=\"1\"" + (dr["finsh"].ToString() == "True" ? " selected=\"true\"" : "") + ">完成</option>\r\n");
                sb.Append("<option style=\"color:#ff0000;\" value=\"0\"" + (dr["finsh"].ToString() == "False" ? " selected=\"true\"" : "") + ">未完成</option>\r\n");
                sb.Append("<select></td>\r\n");
                sb.Append("<td style=\"cursor:move;\">&nbsp;</td>\r\n"); // dr["px"].ToString() 
                sb.Append("</tr>\r\n");

                if (dr["modelid"].ToString().Length > 0) continue;
                getListItems(sb, dr["ApplicationItemID"].ToString(), level + 1);
            }
        }
        private void getAppList(StringBuilder sb)
        {
            sb.Append("<table id=\"eDataTable_Items\" class=\"eDataTable\" border=\"0\" cellpadding=\"0\" cellspacing=\"1\" widt5h=\"100%\">\r\n");
            sb.Append("<thead>\r\n");
            sb.Append("<tr bgcolor=\"#f2f2f2\">\r\n");
            sb.Append("<td height=\"25\" width=\"30\" align=\"center\"><a title=\"添加列\" href=\"javascript:;\" onclick=\"addApp(this);\"><img width=\"16\" height=\"16\" src=\"images/add.png\" border=\"0\"></a></td>\r\n");
            sb.Append("<td width=\"40\">显示</td>\r\n");
            sb.Append("<td width=\"350\">名称</td>\r\n");
            sb.Append("<td width=\"150\">模块</td>\r\n");
            sb.Append("<td width=\"150\">上级</td>\r\n");
            sb.Append("<td width=\"150\">合并到</td>\r\n");
            sb.Append("<td width=\"160\">条件</td>\r\n");
            sb.Append("<td width=\"150\">默认值</td>\r\n");
            sb.Append("<td width=\"150\">URL</td>\r\n");
            sb.Append("<td width=\"80\">图标</td>\r\n");
            sb.Append("<td width=\"80\">状态</td>\r\n");
            sb.Append("<td width=\"60\">顺序</td>\r\n");
            sb.Append("</tr>\r\n");
            sb.Append("</thead>\r\n");
            sb.Append("<tbody eSize=\"false\" eMove=\"true\">\r\n");
            getListItems(sb, "", 0);
            sb.Append("</tbody>\r\n");
            sb.Append("</table>\r\n");
        }

        private DataTable _menuitems;
        public DataTable MenuItems
        {
            get
            {
                if (_menuitems == null)
                {
                    _menuitems = eOleDB.getDataTable("select * from a_eke_sysApplicationMenus where ApplicationID='" + AppId + "' and delTag=0");
                }
                return _menuitems;
            }
        }
        public void updateMenuPX(string ParentID)
        {
            string sql = "update a_eke_sysApplicationMenus set PX=(";
            sql += "select b.rownum from ";
            sql += "(";
            sql += "select ROW_NUMBER() over(order by px,addtime) as rownum,ApplicationMenuID,addTime from a_eke_sysApplicationMenus where delTag=0 and ApplicationID='" + AppId + "'";
            sql += (ParentID.Length == 0 ? " and ParentID IS NULL" : " and ParentID='" + ParentID + "'");
            sql += ") as b where b.ApplicationMenuID=a_eke_sysApplicationMenus.ApplicationMenuID";
            sql += ")  where delTag=0 and ApplicationID='" + AppId + "'";
            sql += (ParentID.Length == 0 ? " and ParentID IS NULL" : " and ParentID='" + ParentID + "'");
            eOleDB.Execute(sql);
        }
        private void getMenuItems(StringBuilder sb, string ParentID, int level)
        {
            updateMenuPX(ParentID);
            DataRow[] rows = MenuItems.Select(ParentID.Length == 0 ? "ParentID is null" : "ParentID='" + ParentID + "'", "px,addtime");
            foreach (DataRow dr in rows)
            {
                int ct = 0;
                if (dr["ParentID"].ToString().Length == 0) ct = MenuItems.Select("ParentID='" + dr["ApplicationMenuID"].ToString() + "'").Length;
                int textIndent = level * 25;

                sb.Append("<tr erowid=\"" + dr["ApplicationMenuID"].ToString() + "\" parentid=\"" + dr["ParentID"].ToString() + "\">\r\n");
                sb.Append("<td height=\"26\" align=\"center\"><a title=\"删除菜单\" href=\"javascript:;\" onclick=\"delMenu(this,'" + dr["ApplicationMenuID"].ToString() + "');\"><img width=\"16\" height=\"16\" src=\"images/del.png\" border=\"0\"></a></td>\r\n");
                sb.Append("<td><input reload=\"true\" type=\"checkbox\" onclick=\"setMenu(this,'" + dr["ApplicationMenuID"].ToString() + "','show');\"" + (dr["show"].ToString() == "True" ? " checked" : "") + " /></td>\r\n");

                sb.Append("<td style=\"text-indent:" + textIndent.ToString() + "px;\">");
                if (ct > 0) { sb.Append("<a href=\"javascript:;\" class=\"open\" _onclick=\"showsub(this);\" style=\"margin:0px;\"></a>"); }
                sb.Append("<input reload=\"true\" class=\"text\" style=\"width:" + (350 - textIndent - 20 - (ct > 0 ? 18 : 0)) + "px;\" type=\"text\" value=\"" + System.Web.HttpUtility.HtmlEncode(dr["MC"].ToString()) + "\" oldvalue=\"" + System.Web.HttpUtility.HtmlEncode(dr["MC"].ToString()) + "\" onBlur=\"setMenu(this,'" + dr["ApplicationMenuID"].ToString() + "','mc');\">");
                sb.Append("</td>\r\n");

                sb.Append("<td>");
                sb.Append("<select reload=\"true\" onChange=\"setMenu(this,'" + dr["ApplicationMenuID"].ToString() + "','ParentID');\" style=\"width:140px;\">\r\n");
                sb.Append("<option value=\"NULL\">无</option>\r\n");


                sb.Append(MenuItems.Select("ParentID is null").toDataTable().Select("len(mc)>0 and ApplicationMenuID<>'" + dr["ApplicationMenuID"].ToString() + "'", "px,addtime").toDataTable().toOptions("ApplicationMenuID", "MC", dr["ParentID"].ToString()));
                sb.Append("<select>");
                sb.Append("</td>\r\n");

                sb.Append("<td><input class=\"text\" type=\"text\" value=\"" + dr["url"].ToString() + "\" oldvalue=\"" + dr["url"].ToString() + "\"  style=\"width:330px;\" onBlur=\"setMenu(this,'" + dr["ApplicationMenuID"].ToString() + "','url');\" /></td>\r\n");
               // sb.Append("<td>图标</td>\r\n");
                sb.Append("<td style=\"cursor:move;\">&nbsp;</td>\r\n"); // dr["px"].ToString() 
                sb.Append("</tr>\r\n");

                if (dr["ParentID"].ToString().Length > 0) continue;
                getMenuItems(sb, dr["ApplicationMenuID"].ToString(), level + 1);
            }
        }
        private void getMenuList(StringBuilder sb)
        {
            sb.Append("<div style=\"margin:6px;line-height:23px;\"><b>移动端菜单</b></div>\r\n");
            sb.Append("<table id=\"eDataTable_Menus\" class=\"eDataTable\" border=\"0\" cellpadding=\"0\" cellspacing=\"1\" widt5h=\"100%\">\r\n");
            sb.Append("<thead>\r\n");
            sb.Append("<tr bgcolor=\"#f2f2f2\">\r\n");
            sb.Append("<td height=\"25\" width=\"30\" align=\"center\"><a title=\"添加列\" href=\"javascript:;\" onclick=\"addMenu(this);\"><img width=\"16\" height=\"16\" src=\"images/add.png\" border=\"0\"></a></td>\r\n");
            sb.Append("<td width=\"40\">显示</td>\r\n");
            sb.Append("<td width=\"350\">名称</td>\r\n");
            sb.Append("<td width=\"150\">上级</td>\r\n");
            sb.Append("<td width=\"350\">URL</td>\r\n");
            // sb.Append("<td width=\"80\">图标</td>\r\n");
            sb.Append("<td width=\"60\">顺序</td>\r\n");
            sb.Append("</tr>\r\n");
            sb.Append("</thead>\r\n");
            sb.Append("<tbody eSize=\"false\" eMove=\"true\">\r\n");
            getMenuItems(sb, "", 0);

            sb.Append("</tbody>\r\n");
            sb.Append("</table>\r\n");
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            appName = eOleDB.getValue("select mc from a_eke_sysApplications where ApplicationID='" + AppId + "'");
            string sql = "";
            string act = eParameters.QueryString("act").ToLower();
            StringBuilder sb = new StringBuilder();
            if (act.Length == 0)
            {
                #region 功能清单
                getAppList(sb);
                getMenuList(sb);
                litBody.Text = sb.ToString();
                #endregion
            }
            else
            {
                string ApplicationMenuID = eParameters.QueryString("ApplicationMenuID");
                string ApplicationItemID = eParameters.QueryString("ApplicationItemID");
                string value = eParameters.QueryString("value").Replace("'", "''");
                string item = eParameters.QueryString("item").ToLower();
                #region 获取数据
                if (act == "getdata")
                {
                    Response.Clear();
                    getAppList(sb);
                    getMenuList(sb);
                    Response.Write(sb.ToString());
                    Response.End();
                }
                #endregion
                #region 添加菜单
                if (act == "addmenu")
                {
                    eOleDB.Execute("insert into a_eke_sysApplicationMenus (ApplicationID) values ('" + AppId + "')");
                    eOleDB.Execute(sql);

                    eJson json = new eJson();
                    json.Add("success", "1");
                    json.Add("message", "添加成功");
                    Response.Write(json.ToString());
                    Response.End();
                }
                #endregion
                #region 修改菜单
                if (act == "setmenu")
                {
                    sql = "update a_eke_sysApplicationMenus set " + item + "='" + value + "' where ApplicationMenuID='" + ApplicationMenuID + "'";
                    if (value == "NULL") sql = "update a_eke_sysApplicationMenus set " + item + "=" + value + " where ApplicationMenuID='" + ApplicationMenuID + "'";
                    eOleDB.Execute(sql);
                    eBase.clearDataCache("a_eke_sysApplicationMenus");
                    Response.End();
                }
                #endregion
                #region  删除菜单
                if (act == "delmenu")
                {
                    eOleDB.Execute("delete from a_eke_sysApplicationMenus where ApplicationID='" + AppId + "' and ApplicationMenuID='" + ApplicationMenuID + "'");
                    eBase.clearDataCache("a_eke_sysApplicationMenus");
                    Response.End();
                }
                #endregion
                //拖动排序
                if (act == "setmenuorders")
                {

                    string ids = eParameters.Form("ids");
                    string[] arr = ids.Split(",".ToCharArray());
                    for (int i = 0; i < arr.Length; i++)
                    {
                        value = (i + 1).ToString();
                        eOleDB.Execute("update a_eke_sysApplicationMenus set PX='" + value + "' where ApplicationID='" + AppId + "' and ApplicationMenuID='" + arr[i] + "'");
                    }

                    if (Request.QueryString["parentid"] != null)
                    {
                        string parentid = eParameters.QueryString("parentid");
                        string oldpid = eOleDB.getValue("select parentid from a_eke_sysApplicationMenus where ApplicationMenuID='" + eParameters.QueryString("AppMenu") + "'");
                        eOleDB.Execute("update a_eke_sysApplicationMenus set parentid=" + (parentid.Length == 0 ? "NULL" : "'" + parentid + "'") + " where ApplicationMenuID='" + eParameters.QueryString("AppMenu") + "'");
                        updatePX(oldpid);
                    }

                    eBase.clearDataCache("a_eke_sysApplicationMenus");
                    Response.End();
                }


                #region 添加模块
                if (act == "addapp")
                {

                    eOleDB.Execute("insert into a_eke_sysApplicationItems (ApplicationID) values ('" + AppId + "')");
                    eOleDB.Execute(sql);

                    eJson json = new eJson();
                    json.Add("success", "1");
                    json.Add("message", "添加成功");
                    Response.Write(json.ToString());
                    Response.End();
                }
                #endregion
                #region 修改模块
                if (act == "setapp")
                {
                    if (item == "px" && value == "0") value = "999999";
                    sql = "update a_eke_sysApplicationItems set " + item + "='" + value + "' where ApplicationItemID='" + ApplicationItemID + "'";
                    if (value == "NULL") sql = "update a_eke_sysApplicationItems set " + item + "=" + value + " where ApplicationItemID='" + ApplicationItemID + "'"; 
                    eOleDB.Execute(sql);
                    if (item.ToLower() == "modelid") //模块名称设置
                    {
                        sql = "update a_eke_sysApplicationItems set MC=(select mc from a_eke_sysModels where modelid='" + value + "') where ApplicationItemID='" + ApplicationItemID + "' and len(isnull(mc,''))=0";
                        eOleDB.Execute(sql);
                    }
                    eBase.clearDataCache("a_eke_sysApplicationItems");
                    Response.End();
                }
                #endregion
                #region  删除模块
                if (act == "delapp")
                {
                    eOleDB.Execute("delete from a_eke_sysApplicationItems where ApplicationID='" + AppId + "' and ApplicationItemID='" + ApplicationItemID + "'");
                    eBase.clearDataCache("a_eke_sysApplicationItems");
                    Response.End();
                }
                #endregion

                //拖动排序
                if (act == "setorders")
                {
                  
                    string ids = eParameters.Form("ids");
                    string[] arr = ids.Split(",".ToCharArray());
                    for (int i = 0; i < arr.Length; i++)
                    {
                        value = (i + 1).ToString();
                        eOleDB.Execute("update a_eke_sysApplicationItems set PX='" + value + "' where ApplicationID='" + AppId + "' and ApplicationItemID='" + arr[i] + "'");
                    }

                    if (Request.QueryString["parentid"]!=null)
                    {
                        string parentid = eParameters.QueryString("parentid");
                        string oldpid = eOleDB.getValue("select parentid from a_eke_sysApplicationItems where ApplicationItemID='" + eParameters.QueryString("appitem") + "'");
                        eOleDB.Execute("update a_eke_sysApplicationItems set parentid=" + (parentid.Length == 0 ? "NULL" : "'" + parentid + "'") + " where ApplicationItemID='" + eParameters.QueryString("appitem") + "'");
                        updatePX(oldpid);
                    }

                    eBase.clearDataCache("a_eke_sysApplicationItems");
                    Response.End();
                }



               
            }
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            Literal lit = (Literal)Master.FindControl("LitTitle");
            if (lit != null)
            {
                lit.Text = "应用管理 - " + eConfig.manageName() ;
            }
        }
    }
}