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 System.Xml;
using System.Reflection;
using EKETEAM.Extension.ComObject;


namespace eFrameWork.Manage
{
    //数据源切换
    public partial class TableInfo : System.Web.UI.Page
    {
        public string id = eParameters.Request("id");
        public string act = eParameters.Request("act");
        public string value = eParameters.Request("value");
        public string tbname = eParameters.Request("tbname");
        
        public string sql = "";
        public eUser user;
        private void autoUpload(string xml)
        {
            Type type = null;
            string _class = "AutoUpload";
            string _method = "upload";
            Assembly[] asses = AppDomain.CurrentDomain.GetAssemblies();
            foreach (Assembly _ass in asses)
            {
                type = _ass.GetType(_class);
                if (type != null) break;
            }
            if (type != null)
            {
                MethodInfo method = null;
                try
                {
                    method = type.GetMethod(_method);
                }
                catch
                {
                }
                if (method != null)
                {
                    string[] objs = new string[] { xml };
                    object obj = Activator.CreateInstance(type);
                    object result = obj.Method(_method, objs);                   
                }
            }
        }
        private string ExportTable()
        {
            XmlDocument doc = new XmlDocument();
            DataTable dt = eBase.DataBase.getSchemaColumns(tbname);
            if (!dt.ExtendedProperties.Contains("name")) dt.ExtendedProperties.Add("name", tbname);
            //dt.ExtendedProperties.Add("description", tbname);
            doc.appendModel(dt);

            string type = eParameters.Request("type");
            if (type == "2")
            {
                dt = eBase.DataBase.getDataTable("select * from " + eBase.DataBase.StartNameSplitChar + tbname + eBase.DataBase.EndNameSplitChar);
                dt.ExtendedProperties.Add("name", tbname);
                doc.appendData(dt);
            }
            return doc.InnerXml;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            user = new eUser("Manage");
            user.Check();
            #region 导出EFW
            if (act == "exportefw")
            {
                string xml = ExportTable();
                //eBase.WriteHTML(xml);

                byte[] buffer = Encoding.UTF8.GetBytes(xml);
                byte[] outBuffer = new byte[buffer.Length + 3];
                outBuffer[0] = (byte)0xEF;
                outBuffer[1] = (byte)0xBB;
                outBuffer[2] = (byte)0xBF;
                Array.Copy(buffer, 0, outBuffer, 3, buffer.Length);

                string fileName = tbname  + ".efw";
                string userAgent = HttpContext.Current.Request.UserAgent == null ? "" : HttpContext.Current.Request.UserAgent.Replace(" ", "").ToLower();
                if (userAgent.IndexOf("msie") > -1) fileName = HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);  //IE需要编码
                //Response.ContentType = "text/xml";
                Response.ContentType = "application/octet-stream";
                Response.AddHeader("Accept-Ranges", "bytes");
                Response.AddHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
                Response.Write(Encoding.UTF8.GetString(outBuffer));
                Response.End();
            }
            #endregion
            #region 生成框架结构信息
            if (act == "createschema")
            {
                string basePath = Server.MapPath("~/upload/temp");
                if (!System.IO.Directory.Exists(basePath)) System.IO.Directory.CreateDirectory(basePath);
                basePath += "\\database_schema.xml";
                XmlDocument doc = new XmlDocument();
                DataTable dt = eBase.DataBase.getSchemaTables();
                foreach (DataRow dr in dt.Rows)
                {
                    string name = dr["value"].ToString();
                    if (!name.ToLower().StartsWith("a_eke_sys") && "organizationals,dictionaries".IndexOf(name.ToLower()) == -1) continue;
                    DataTable dt2 = eBase.DataBase.getSchemaColumns(name);
                    doc.appendModel(dt2);
                }
                eBase.WriteFile(basePath, doc.InnerXml);
                autoUpload(doc.InnerXml);  
                Response.Redirect("TableInfo.aspx", true);
            }
            #endregion
            if (act == "delalltable")
            {
                foreach (DataRow dr in eBase.DataBase.getTables().Rows)
                {
                    //eBase.DataBase.Execute("drop table " + dr["name"].ToString());
                }

                Response.Redirect("TableInfo.aspx", true);
            }
            if (act == "settabledescription")
            {
                eBase.DataBase.Execute("EXEC sys.sp_addextendedproperty N'MS_Description',N'" + value + "','user','dbo','table','" + tbname + "',NULL,NULL");
                eBase.DataBase.Execute("EXEC sys.sp_updateextendedproperty N'MS_Description',N'" + value + "','user','dbo','table','" + tbname + "',NULL,NULL");               
                eBase.End();
            }
            if (act == "setcolumndescription")
            {
                string column = Request.QueryString["column"].ToString();
                eBase.DataBase.Execute("EXEC sp_addextendedproperty N'MS_Description',N'" + value + "','user','dbo','table','" + tbname + "','column','" + column + "'");
                eBase.DataBase.Execute("EXEC sp_updateextendedproperty N'MS_Description',N'" + value + "','user','dbo','table','" + tbname + "','column','" + column + "'");
                eBase.End();
            }

            if (Request.QueryString["name"] != null)
            {
                string name = Request.QueryString["name"].ToString();

                DataTable dt = eBase.DataBase.getColumns(name);
                Response.Write("<div style=\"margin-left:80px;\">\r\n");
                foreach (DataRow _dr in dt.Rows)
                {
                    Response.Write("<div class=\"item\">\r\n");
                    Response.Write("<span style=\"display:inline-block;width:270px;_width:250px;" + (_dr["MC"].ToString().Length == 0 ? "color:#ff0000;" : "") + "\">" + _dr["code"].ToString() + "</span>");
                    Response.Write("<input type=\"text\" class=\"edit\" value=\"" + _dr["MC"].ToString() + "\"  onBlur=\"setColumnDescription(this,'" + name + "','" + _dr["code"].ToString() + "');\" /><br>\r\n");
                    Response.Write("</div>\r\n");
                }
                Response.Write("</div>\r\n");
                Response.End();
            }


            DataTable tb = eBase.DataBase.getTables();
            //eBase.PrintDataTable(tb);
            StringBuilder sb = new StringBuilder();
            int i = 1;
            sb.Append("<div class=\"item\"><label><input type=\"checkbox\" name=\"selallitem\" value=\"1\" onclick=\"selectAllItems(this);\" />全选</label>\r\n");
            sb.Append("<span style=\"display:inline-block;width:300px;margin-left:20px; \">表名</span>");
            sb.Append("<span style=\"display:inline-block;width:320px; \">描述</span>");
            sb.Append("<span style=\"display:inline-block;width:80px;\">操作</span>");
            sb.Append("</div>\r\n");
            foreach (DataRow dr in tb.Rows)
            {

                sql = "select top 1 value from sys.extended_properties where major_id=(SELECT id from sysobjects where name='" + dr["name"].ToString() + "' and  xtype = 'U') and minor_id=0";
                sql = "select top 1 value from sys.extended_properties where major_id=" +  dr["id"].ToString()+ " and minor_id=0";
                string sm = eBase.DataBase.getValue(sql);

                sb.Append("<div class=\"item\" onclick=\"selectRow(this);\"><input type=\"checkbox\" name=\"selitem\" value=\"" + dr["name"].ToString() + "\" />\r\n");
                sb.Append("<span style=\"display:inline-block;width:30px;\">" + i.ToString().PadLeft(3, '0') + "</span>");
                sb.Append("<span dataname=\"" + dr["name"].ToString() + "\" onclick=\"opensub(this);\" on_click=\"show(" + i.ToString() + ",this);\" style=\"display:inline-block;width:300px;" + (sm.Length == 0 ? "color:#ff0000;" : "") + "\" class=\"close\">" + dr["name"].ToString());
                sb.Append("</span>");
                sb.Append("<input type=\"text\" class=\"edit\" value=\"" + sm + "\" onBlur=\"setTableDescription(this,'" + dr["name"].ToString() + "');\" />");
                sb.Append(" <a href=\"javascript:;\" style=\"display:inline-block;margin-left:8px;color:#222;\" onclick=\"createModel('" + dr["name"].ToString() + "');\">生成实体</a>");
                sb.Append(" <a href=\"javascript:;\" style=\"display:inline-block;margin-left:8px;color:#222;\" onclick=\"createTable('" + dr["name"].ToString() + "');\">生成脚本</a>");

                sb.Append(" <a href=\"javascript:;\" style=\"display:inline-block;margin-left:8px;color:#222;\" onclick=\"exportEFW('" + dr["name"].ToString() + "');\">导出(.efw)</a>");
                sb.Append("</div>\r\n");
                /*
                DataTable dt = eOleDB.getColumns(dr["name"].ToString());
                sb.Append("<div id=\"div_" + i.ToString() + "\" style=\"display:none;margin-left:80px;\">\r\n");
                foreach (DataRow _dr in dt.Rows)
                {
                    sb.Append("<span style=\"display:inline-block;width:270px;_width:250px;" + (_dr["MC"].ToString().Length == 0 ? "color:#ff0000;" : "") + "\">" +_dr["code"].ToString() + "</span>");
                    sb.Append("<input type=\"text\" class=\"edit\" value=\"" + _dr["MC"].ToString() + "\"  onBlur=\"setColumnDescription(this,'" + dr["name"].ToString() + "','" + _dr["code"].ToString()  + "');\" /><br>\r\n");
                }
                sb.Append("</div>\r\n");
                */
                i++;
                //eBase.PrintDataTable(dt);
            }
            //eBase.PrintDataTable(tb);
            LitBody.Text = sb.ToString();
        }



        protected void Page_PreRender(object sender, EventArgs e)
        {
            if (Master == null) return;
            Literal lit = (Literal)Master.FindControl("LitTitle");
            if (lit != null)
            {
                lit.Text = "数据结构 - " + eConfig.manageName(); 
            }
        }
    }
}