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 = eOleDB.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)
        {
            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 = eOleDB.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 = eOleDB.getValue("select Code from a_eke_sysModels where ModelID='" + ModelID + "'");
            string modelSQL = eOleDB.getTableSql(code);
            _json.Add("modelSQL", HttpUtility.UrlEncode(modelSQL));

            DataTable dt = eOleDB.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 string ExportModel(string modelid)
        {
            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();
            Models.Columns.Remove("addTime");
            //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;
            foreach (DataRow dr in Models.Rows)
            {
                #region 结构及数据
                string code = dr["code"].ToString();
                if (code.Length > 0)
                {
                    //eBase.WriteHTML(code);
                    //结构
                    DataTable dt = eOleDB.getSchemaColumns(code);
                    dt.ExtendedProperties.Add("name", code);
                    dt.ExtendedProperties.Add("description", dr["mc"].ToString());
                    doc.appendModel(dt);

                    //数据
                    dt = eOleDB.getDataTable("select * from " + code);
                    dt.ExtendedProperties.Add("name", code);
                    doc.appendData(dt);
                    //eBase.PrintDataTable(dt);
                }
                #endregion
                string ModelID = dr["ModelID"].ToString();
                string newModelID = Guid.NewGuid().ToString();
                dr["ModelID"] = newModelID;

                rows = Models.Select("ParentID='" + ModelID + "'");
                rows.UpdateForeignKey("ParentID", ModelID, newModelID, false);


                rows = ModelItems.Select("BindModelID='" + ModelID + "'");
                rows.UpdateForeignKey("BindModelID", ModelID, newModelID, true);

                rows = ModelItems.Select("FillModelID='" + ModelID + "'");
                rows.UpdateForeignKey("FillModelID", ModelID, newModelID, true);


                // eBase.Writeln(ModelID + " to " + newModelID);

                rows = Actions.Select("ModelID='" + ModelID + "'");
                rows.UpdateForeignKey("ModelID", ModelID, newModelID, true);

                rows = CheckUps.Select("ModelID='" + ModelID + "'");
                rows.UpdateForeignKey("ModelID", ModelID, newModelID, true);




                rows = ModelConditions.Select("ModelID='" + ModelID + "'");
                //rows.UpdateForeignKey("ModelID", newModelID, true);
                foreach (DataRow _dr in rows)
                {
                    string _ModelConditionID = _dr["ModelConditionID"].ToString();
                    string _newModelConditionID = Guid.NewGuid().ToString();
                    _dr["ModelConditionID"] = _newModelConditionID;

                    rows = ModelConditionItems.Select("ModelConditionID='" + _ModelConditionID + "'");
                    rows.UpdateForeignKey("ModelConditionID", _ModelConditionID, _newModelConditionID, true);
                    rows.UpdateForeignKey("ModelID", ModelID, newModelID, false);


                    _dr["ModelID"] = newModelID;
                }


                rows = ModelItems.Select("ModelID='" + ModelID + "'");
                foreach (DataRow _dr in rows)
                {
                    string _ModelItemID = _dr["ModelItemID"].ToString();
                    string _newModelItemID = Guid.NewGuid().ToString();
                    DataRow[] rs = ModelItems.Select("FillItem='" + _ModelItemID + "'");
                    rs.UpdateForeignKey("FillItem", _ModelItemID, _newModelItemID, false);

                    rs = ModelItems.Select("FillModelItemID='" + _ModelItemID + "'");
                    rs.UpdateForeignKey("FillModelItemID", _ModelItemID, _newModelItemID, false);

                    _dr["ModelItemID"] = _newModelItemID;
                    _dr["ModelID"] = newModelID;
                    //
                }
                //rows.UpdateForeignKey("ModelID",ModelID, newModelID,true);
                //eBase.PrintDataRow(rows);
                //eBase.PrintDataTable(ModelItems);




                rows = ModelTabs.Select("ModelID='" + ModelID + "'");
                foreach (DataRow _dr in rows)
                {
                    string _ModelTabID = _dr["ModelTabID"].ToString();
                    string _newModelTabID = Guid.NewGuid().ToString();
                    _dr["ModelTabID"] = _newModelTabID;

                    rows = Models.Select("ModelTabID='" + _ModelTabID + "'");
                    rows.UpdateForeignKey("ModelTabID", _ModelTabID, _newModelTabID, false);

                    rows = ModelPanels.Select("ModelTabID='" + _ModelTabID + "'");
                    rows.UpdateForeignKey("ModelTabID", _ModelTabID, _newModelTabID, false);

                    rows = ModelItems.Select("ModelTabID='" + _ModelTabID + "'");
                    rows.UpdateForeignKey("ModelTabID", _ModelTabID, _newModelTabID, false);

                    _dr["ModelID"] = newModelID;
                }


                rows = ModelPanels.Select("ModelID='" + ModelID + "'");
                foreach (DataRow _dr in rows)
                {
                    string _ModelPanelID = _dr["ModelPanelID"].ToString();
                    string _newModelPanelID = Guid.NewGuid().ToString();
                    _dr["ModelPanelID"] = _newModelPanelID;

                    rows = Models.Select("ModelPanelID='" + _ModelPanelID + "'");
                    rows.UpdateForeignKey("ModelPanelID", _ModelPanelID, _newModelPanelID, false);

                    rows = ModelItems.Select("ModelPanelID='" + _ModelPanelID + "'");
                    rows.UpdateForeignKey("ModelPanelID", _ModelPanelID, _newModelPanelID, false);

                    _dr["ModelID"] = newModelID;
                }
                //rows.UpdateForeignKey("ModelID", ModelID, newModelID, true);

                rows = Reports.Select("ModelID='" + ModelID + "'");
                foreach (DataRow _dr in rows)
                {
                    string _ReportID = _dr["ReportID"].ToString();
                    string _newReportID = Guid.NewGuid().ToString();
                    _dr["ReportID"] = _newReportID;



                    rows = ReportItems.Select("ReportID='" + _ReportID + "'");
                    rows.UpdateForeignKey("ReportID", _ReportID, _newReportID, true);
                    _dr["ModelID"] = newModelID;
                }
            }
            #endregion
            #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;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            string ModelID = eParameters.QueryString("ModelID");
            string xml = ExportModel(ModelID);

            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 = eOleDB.getValue("select mc from a_eke_sysModels where modelid='" + ModelID + "'");
            string fileName = modelName + ".efw";
            if (Request.ServerVariables["HTTP_USER_AGENT"].ToString().ToLower().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));
            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 = eOleDB.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";
                if (Request.ServerVariables["HTTP_USER_AGENT"].ToString().ToLower().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();



        }
    }
}