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.Xml.Serialization;

namespace eFrameWork.Manage
{
    public partial class ModelExport : System.Web.UI.Page
    {
        bool outFile = true;

        private DataTable _modelids;
        public DataTable ModelIDS
        {
            get
            {
                if (_modelids == null)
                {
                    _modelids = eBase.DataBase.getDataTable("select ModelID,ParentID from a_eke_sysModels where delTag=0");
                }
                return _modelids;
            }
        }
        public string getids(string modelid)
        {
            DataRow[] rows = ModelIDS.Select("Convert(ParentID, 'System.String')='" + modelid + "'");
            if (rows.Length == 0)
            {
                return modelid;
            }
            else
            {
                foreach (DataRow dr in rows)
                {
                    modelid += "," + getids(dr["modelid"].ToString());
                }
            }
            return modelid;
        }
        private string getModelJson(string ModelID)
        {
            return "";
            /*
            eMTable models = new eMTable("a_eke_sysModels");
            models.Where.Add("ModelID='" + ModelID + "'");

            eMTable Items = new eMTable("a_eke_sysModelItems");
            models.Add(Items);
            
            eMTable Conds = new eMTable("a_eke_sysModelConditions");
            eMTable CondItems = new eMTable("a_eke_sysModelConditionItems");
            Conds.Add(CondItems);
            models.Add(Conds);

            eMTable action = new eMTable("a_eke_sysActions");
            models.Add(action);

            eMTable modelcond = new eMTable("a_eke_sysConditions");
            models.Add(modelcond);

            eMTable tabs = new eMTable("a_eke_sysModelTabs");
            models.Add(tabs);

            eMTable groups = new eMTable("a_eke_sysModelPanels");
            models.Add(groups);

            string ct = DataBase.getValue("select count(*) from a_eke_sysCheckUps where ModelID='" + ModelID + "'");
            if (ct.Length > 0 && ct != "0")
            {
                eMTable checkups = new eMTable("a_eke_sysCheckUps");
                models.Add(checkups);
            }


            eMTable Reports = new eMTable("a_eke_sysReports");
            eMTable ReportItems = new eMTable("a_eke_sysReportItems");
            Reports.Add(ReportItems);
            models.Add(Reports);


            string json = models.ExportJson();
           
            eJson _json = new eJson(json);
            _json.Convert = true;
            string code = DataBase.getValue("select Code from a_eke_sysModels where ModelID='" + ModelID + "'");
            string modelSQL = DataBase.getTableSql(code);
            _json.Add("modelSQL", HttpUtility.UrlEncode(modelSQL));

            DataTable dt = DataBase.getDataTable("select ModelID,MC,Code,Auto,AspxFile from a_eke_sysModels where ParentID='" + ModelID + "' and delTag=0");
            foreach (DataRow dr in dt.Rows)
            {
                string js = getModelJson(dr["ModelID"].ToString());
                eJson _js = new eJson(js);
                _js.Convert = true;
                _json.Add("subModels", _js);
            }
            return _json.ToString(); 
            */
        }
        private DataRow _modelinfo;
        public DataRow ModelInfo
        {
            get
            {
                if (_modelinfo == null)
                {
                    DataTable dt = eBase.DataBase.getDataTable("select * from a_eke_sysModels where ModelID='" + ModelID + "'");
                    if (dt.Rows.Count > 0) _modelinfo = dt.Rows[0];
                }
                return _modelinfo;
            }
        }
        private eDataBase _database;
        public eDataBase DataBase
        {
            get
            {
                if (_database == null)
                {
                    if (_database == null)
                    {
                        if (ModelInfo["DataSourceID"].ToString().Length > 0)
                        {
                            _database = new eDataBase(ModelInfo);
                        }
                        else
                        {
                            _database = eBase.DataBase;
                        }
                    }
                }
                return _database;
            }
        }
        private string ExportModel(string modelid)
        {
            //eBase.PrintDataTable(ModelIDS);
          

            XmlDocument doc = new XmlDocument();
            string ids = getids(modelid);
            ids = "'" + ids.Replace(",", "','") + "'";
            //Response.Write(ids);


            #region  生成关系
            eList a_eke_sysModels = new eList("a_eke_sysModels");
            a_eke_sysModels.Where.Add("deltag=0");
            //a_eke_sysModels.Where.Add("modelid='" + modelid + "'");
            a_eke_sysModels.Where.Add("modelid in (" + ids + ")");
            //a_eke_sysModels.Where.Add("modelid in ('7254820c-df55-4655-be0a-f14527556493','bf9da797-4b14-488f-9297-b7599edfe5cc')"); //'5ac4ba59-a545-467e-997d-7721802a403b','C6399A56-C165-4610-AE02-F593DBE8226A'



            eList a_eke_sysActions = new eList("a_eke_sysActions");
            a_eke_sysActions.Where.Add("deltag=0");
            a_eke_sysModels.Add(a_eke_sysActions);

            eList a_eke_sysCheckUps = new eList("a_eke_sysCheckUps");
            a_eke_sysCheckUps.Where.Add("deltag=0");
            a_eke_sysModels.Add(a_eke_sysCheckUps);

            eList a_eke_sysConditions = new eList("a_eke_sysConditions");
            a_eke_sysConditions.Where.Add("deltag=0");
            a_eke_sysModels.Add(a_eke_sysConditions);

            eList a_eke_sysModelConditions = new eList("a_eke_sysModelConditions");
            a_eke_sysModelConditions.Where.Add("deltag=0");
            eList a_eke_sysModelConditionItems = new eList("a_eke_sysModelConditionItems");
            a_eke_sysModelConditionItems.Where.Add("deltag=0");
            a_eke_sysModelConditions.Add(a_eke_sysModelConditionItems);
            a_eke_sysModels.Add(a_eke_sysModelConditions);


            eList a_eke_sysModelItems = new eList("a_eke_sysModelItems");
            a_eke_sysModelItems.Where.Add("deltag=0");
            //a_eke_sysModelItems.Rows = 1;
            a_eke_sysModels.Add(a_eke_sysModelItems);

            eList a_eke_sysModelTabs = new eList("a_eke_sysModelTabs");
            a_eke_sysModelTabs.Where.Add("deltag=0");
            a_eke_sysModels.Add(a_eke_sysModelTabs);

            eList a_eke_sysModelPanels = new eList("a_eke_sysModelPanels");
            a_eke_sysModelPanels.Where.Add("deltag=0");
            a_eke_sysModels.Add(a_eke_sysModelPanels);




            eList a_eke_sysReports = new eList("a_eke_sysReports");
            a_eke_sysReports.Where.Add("deltag=0");
            eList a_eke_sysReportItems = new eList("a_eke_sysReportItems");
            a_eke_sysReportItems.Where.Add("deltag=0");
            //a_eke_sysReportItems.Rows = 5;
            a_eke_sysReports.Add(a_eke_sysReportItems);
            a_eke_sysModels.Add(a_eke_sysReports);
            #endregion
            #region 获取数据
            //eBase.Writeln("a_eke_sysModels");
            DataTable Models = a_eke_sysModels.getDataTable();
           
            if(Models.Columns.Contains("addTime"))Models.Columns.Remove("addTime");
            if(Models.Columns.Contains("DataSourceID"))Models.Columns.Remove("DataSourceID");
            if(Models.Columns.Contains("LabelIDS"))Models.Columns.Remove("LabelIDS");
            if(Models.Columns.Contains("ServiceID"))Models.Columns.Remove("ServiceID");
            //eBase.PrintDataTable(Models);     


            //eBase.Writeln("a_eke_sysActions");
            DataTable Actions = a_eke_sysActions.getDataTable();

            //eBase.PrintDataTable(Actions);

            // eBase.Writeln("a_eke_sysCheckUps");
            DataTable CheckUps = a_eke_sysCheckUps.getDataTable();

            //eBase.PrintDataTable(CheckUps);



            //eBase.Writeln("a_eke_sysModelConditions");
            DataTable ModelConditions = a_eke_sysModelConditions.getDataTable();

            //eBase.PrintDataTable(ModelConditions);

            //eBase.Writeln("a_eke_sysModelConditionItems");
            DataTable ModelConditionItems = a_eke_sysModelConditionItems.getDataTable();

            //eBase.PrintDataTable(ModelConditionItems);

            //eBase.Writeln("a_eke_sysModelItems");
            DataTable ModelItems = a_eke_sysModelItems.getDataTable();
            //eBase.PrintDataTable(ModelItems);


            //eBase.Writeln("a_eke_sysModelTabs");
            DataTable ModelTabs = a_eke_sysModelTabs.getDataTable();
            //eBase.PrintDataTable(ModelTabs);

            //eBase.Writeln("a_eke_sysModelPanels");
            DataTable ModelPanels = a_eke_sysModelPanels.getDataTable();
            //eBase.PrintDataTable(ModelPanels);


            //eBase.Writeln("a_eke_sysReports");
            DataTable Reports = a_eke_sysReports.getDataTable();
            //eBase.PrintDataTable(Reports);

            //eBase.Writeln("a_eke_sysReportItems");
            DataTable ReportItems = a_eke_sysReportItems.getDataTable();
            //eBase.PrintDataTable(ReportItems);
            #endregion
            #region 数据处理
            DataRow[] rows;
            //eBase.PrintDataTable(Models);
            //eBase.End();

            List<string> tables = new List<string>();
            foreach (DataRow dr in Models.Rows)
            {
                if (tables.Contains(dr["code"].ToString().ToLower())) continue;
                tables.Add(dr["code"].ToString().ToLower());

                #region 结构及数据
                string code = dr["code"].ToString();
                if (code.Length > 0)
                {
                    //eBase.WriteHTML(code);
                    //结构
                    DataTable dt = DataBase.getSchemaColumns(code);
                    if (!dt.ExtendedProperties.Contains("name")) dt.ExtendedProperties.Add("name", code);
                    if (!dt.ExtendedProperties.Contains("description")) dt.ExtendedProperties.Add("description", dr["mc"].ToString());
                    doc.appendModel(dt);

                    //数据
                    if (Request.QueryString["data"] != null)
                    {
                        dt = DataBase.getDataTable("select * from " + DataBase.StartNameSplitChar + code + DataBase.EndNameSplitChar);
                        dt.ExtendedProperties.Add("name", code);
                        #region 已删除处理
                        if (dt.Rows.Count > 0 && dt.Columns.Contains("deltag"))
                        {
                            for (int i = dt.Rows.Count - 1; i >= 0; i--)
                            {
                                if (dt.Rows[i]["deltag"].ToString().ToLower() == "1" || dt.Rows[i]["deltag"].ToString().ToLower() == "true")
                                {
                                    dt.Rows.Remove(dt.Rows[i]);
                                }
                            }
                        }
                        #endregion
                        doc.appendData(dt);
                    }                   
                }
                #endregion
                #region 程序文件
                string path="";
                string basepath = Server.MapPath("~");
                if (dr["AspxFile"].ToString().Length > 0)
                {
                    path = dr["AspxFile"].ToString();
                    if (path.StartsWith(".") || path.StartsWith("/"))
                    {
                        string filepath = basepath + path.Replace("..", "").Replace("/", "\\");
                        string csfilepath = filepath + ".cs";
                        if (System.IO.File.Exists(filepath))
                        {
                            string body = eBase.ReadFile(filepath);
                            doc.appendFile(path, body);
                        }
                        if (System.IO.File.Exists(csfilepath))
                        {
                            string body = eBase.ReadFile(csfilepath);
                            doc.appendFile(path + ".cs", body);
                        }
                    }
                }
                if (dr["mAspxFile"].ToString().Length > 0)
                {
                    path = dr["mAspxFile"].ToString();
                    if (path.StartsWith(".") || path.StartsWith("/"))
                    {
                        string filepath = basepath + path.Replace("..", "").Replace("/", "\\");
                        string csfilepath = filepath + ".cs";
                        if (System.IO.File.Exists(filepath))
                        {
                            string body = eBase.ReadFile(filepath);
                            doc.appendFile(path, body);
                        }
                        if (System.IO.File.Exists(csfilepath))
                        {
                            string body = eBase.ReadFile(csfilepath);
                            doc.appendFile(path + ".cs", body);
                        }
                    }
                }
                #endregion
            }
            #endregion
            //eBase.End();
            #region 生成XML
           
            //eBase.Write("<hr>");
            //eBase.Writeln("a_eke_sysModels");
            //eBase.PrintDataTable(Models);
            Models.ExtendedProperties.Add("name", "a_eke_sysModels");
            doc.appendData(Models);



            //eBase.Writeln("a_eke_sysActions");
            //eBase.PrintDataTable(Actions);
            Actions.ExtendedProperties.Add("name", "a_eke_sysActions");
            doc.appendData(Actions);


            //eBase.Writeln("a_eke_sysCheckUps");
            //eBase.PrintDataTable(CheckUps);
            CheckUps.ExtendedProperties.Add("name", "a_eke_sysCheckUps");
            doc.appendData(CheckUps);



            //eBase.Writeln("a_eke_sysModelConditions");
            //eBase.PrintDataTable(ModelConditions);
            ModelConditions.ExtendedProperties.Add("name", "a_eke_sysModelConditions");
            doc.appendData(ModelConditions);


            //eBase.Writeln("a_eke_sysModelConditionItems");
            //eBase.PrintDataTable(ModelConditionItems);
            ModelConditionItems.ExtendedProperties.Add("name", "a_eke_sysModelConditionItems");
            doc.appendData(ModelConditionItems);



            //eBase.Writeln("a_eke_sysModelItems");
            //eBase.PrintDataTable(ModelItems);
            ModelItems.ExtendedProperties.Add("name", "a_eke_sysModelItems");
            doc.appendData(ModelItems);




            //eBase.Writeln("a_eke_sysModelTabs");
            //eBase.PrintDataTable(ModelTabs);
            ModelTabs.ExtendedProperties.Add("name", "a_eke_sysModelTabs");
            doc.appendData(ModelTabs);



            //eBase.Writeln("a_eke_sysModelPanels");
            //eBase.PrintDataTable(ModelPanels);
            ModelPanels.ExtendedProperties.Add("name", "a_eke_sysModelPanels");
            doc.appendData(ModelPanels);

            //eBase.Writeln("a_eke_sysReports");
            //eBase.PrintDataTable(Reports);
            Reports.ExtendedProperties.Add("name", "a_eke_sysReports");
            doc.appendData(Reports);

            //eBase.Writeln("a_eke_sysReportItems");
            //eBase.PrintDataTable(ReportItems);
            ReportItems.ExtendedProperties.Add("name", "a_eke_sysReportItems");
            doc.appendData(ReportItems);

            #endregion
            //eBase.WriteHTML(doc.InnerXml);
            return doc.InnerXml;
        }
        public string ModelID = eParameters.QueryString("ModelID");
        public eUser user;
        protected void Page_Load(object sender, EventArgs e)
        {
            user = new eUser("Manage");
            user.Check();




            string xml = ExportModel(ModelID);
            //eBase.WriteHTML(xml);
            //eBase.End();

            /*
            Response.Clear();
            Response.ContentType = "text/xml";
            Response.Write(xml);
            Response.End();
            */

            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 modelName = eBase.DataBase.getValue("select mc from a_eke_sysModels where modelid='" + ModelID + "'");
            string fileName = modelName + ".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();
        }
        protected void Page_Load_bak(object sender, EventArgs e)
        {

            Response.Charset = "UTF-8";
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            string ModelID = eParameters.QueryString("ModelID");
            DataTable dt = DataBase.getDataTable("select ModelID,MC,Code,Auto,AspxFile from a_eke_sysModels where ModelID='" + ModelID + "'");

            if (dt.Rows.Count == 0)
            {
                Response.End();
            }



           
            string json = "";
            if (dt.Rows[0]["Auto"].ToString() == "True") //自动模块
            {
                json = getModelJson(ModelID);
            }
            else //自定义模块
            {
                #region 自定义模块
                /*
                eMTable models = new eMTable("a_eke_sysModels");
                models.Where.Add("ModelID='" + ModelID + "'");

                json = models.ExportJson();
                eJson _json = new eJson(json);
                _json.Convert = true;
                string text = "";
                string file = dt.Rows[0]["AspxFile"].ToString();
                string aspxFile = Server.MapPath("~/System/") + file;
                if (System.IO.File.Exists(aspxFile))
                {
                    text = eBase.ReadFile(aspxFile);
                    text = eBase.encode(text);
                    _json.Add("aspxFile", text);
                }
                string csFile = Server.MapPath("~/System/") + file + ".cs";
                if (System.IO.File.Exists(csFile))
                {
                    text = eBase.ReadFile(csFile);
                    text = eBase.encode(text);
                    _json.Add("csFile", text);
                }
                string desFile = Server.MapPath("~/System/") + file + ".designer.cs";
                if (System.IO.File.Exists(desFile))
                {
                    text = eBase.ReadFile(desFile);
                    text = eBase.encode(text);
                    _json.Add("desFile", text);
                }
                json = _json.ToString();
                */
                #endregion
            }
            byte[] buffer = Encoding.UTF8.GetBytes(json);
            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);
            if (outFile)
            {

                string fileName = dt.Rows[0]["mc"].ToString() + ".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 = "application/octet-stream";
                Response.AddHeader("Accept-Ranges", "bytes");
                Response.AddHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
                Response.Write(Encoding.UTF8.GetString(outBuffer));
            }
            else
            {
                Response.Write(json);
            }
            Response.End();



        }
    }
}