using System;
using System.Collections.Generic;
using System.Data;
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;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;
using System.IO;

public partial class Manage_ExportConfig : System.Web.UI.Page
{
   
    public string modelids = eParameters.QueryString("modelids");
    public string appid = eParameters.QueryString("appid");
    private string getAllXML()
    {
        XmlDocument doc = new XmlDocument();
        string[] tables = new string[] { 
            "a_eke_sysActions", 
            "a_eke_sysAllowDomain", 
            "a_eke_sysApplicationItems",
            "a_eke_sysApplicationMenus",
            "a_eke_sysApplications",
            "a_eke_sysCheckUps",
            "a_eke_sysConditions",
            "a_eke_sysConfigs",
            "a_eke_sysDataContents",
            "a_eke_sysDataSources",
            "a_eke_sysDataViews",
            "a_eke_sysLabels",
            "a_eke_sysModelConditionItems",
            "a_eke_sysModelConditions",
            "a_eke_sysModelItems",
            "a_eke_sysModelPanels",
            "a_eke_sysModels",
            "a_eke_sysModelTabs",
            "a_eke_sysReportItems",
            "a_eke_sysReports",
            "a_eke_sysServices",
            "a_eke_sysSiteItems",
            "a_eke_sysSites"
        };
        //tables = new string[] { "a_eke_sysModels" };
        foreach (string table in tables)
        {

            eList list = new eList(table);
            list.Where.Add("deltag=0");//modelid='B9EEA58A-6863-4DA8-836A-AD393E525C9B' and 
            DataTable tb = list.getDataTable();
            tb.ExtendedProperties.Add("name", table);
            doc.appendData(tb);
        }
        return doc.InnerXml;
    }
    private void ExportAll_bak()
    {
        string xml = getAllXML();
        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_sysSites where SiteID='1'");
        //string fileName = modelName + "-配置文件.xml";
        string fileName = "eframework.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();
    }
    private void ExportAll()
    {
        string xml = getAllXML();
        byte[] xmlByte = Encoding.UTF8.GetBytes(xml);
        MemoryStream mstream = new MemoryStream();
        ZipOutputStream zstream = new ZipOutputStream(mstream);
        ZipEntry zen = new ZipEntry("eframework.efw");
        zstream.PutNextEntry(zen);
        //zstream.SetLevel(6);
        zstream.Write(xmlByte, 0, xmlByte.Length);
        zstream.Close();
        zstream.Finish();
        zstream.Close();

        Response.Clear();
        Response.ContentType = "application/octet-stream";
        string strFileName = HttpUtility.UrlEncode("update.zip");
        Response.AddHeader("Content-Disposition", "attachment; filename=" + strFileName);
        Response.BinaryWrite(mstream.ToArray());
        Response.Flush();
        Response.End();
    }

    private string getModelIDS(string ModelID)
    {
        string temp = "'" + ModelID + "'";
        DataTable dt = eBase.DataBase.getDataTable("select ModelID FROM a_eke_sysModels where delTag='0' and ParentID='" + ModelID + "'");
        foreach (DataRow dr in dt.Rows)
        {
            temp += "," + getModelIDS(dr["ModelID"].ToString());
        }
        return temp;
    }
    private string getModelsXML()
    {
        XmlDocument doc = new XmlDocument();
        string[] tables = new string[] { 
            "a_eke_sysActions", 
            "a_eke_sysCheckUps",
            "a_eke_sysConditions",
            "a_eke_sysModelConditionItems",
            "a_eke_sysModelConditions",
            "a_eke_sysModelItems",
            "a_eke_sysModelPanels",
            "a_eke_sysModels",
            "a_eke_sysModelTabs",
            "a_eke_sysReportItems",
            "a_eke_sysReports"
        };
        //tables = new string[] { "a_eke_sysModels" };
        eList list = new eList("a_eke_sysModels");
        list.Fields.Add("ModelID");
        if (modelids.Length > 0) list.Where.Add("deltag=0 and modelid in ('" + modelids.Replace(",", "','") + "')");
        if (appid.Length > 0) list.Where.Add("deltag=0 and modelid in (select Distinct modelid from a_eke_sysApplicationItems where ApplicationID='" + appid + "')");
        DataTable tb = list.getDataTable();
        //eBase.PrintDataTable(tb);
        string ids = "";
        for (int i = 0; i < tb.Rows.Count; i++)
        {
            if (i > 0) ids += ",";
            ids += getModelIDS(tb.Rows[i]["modelid"].ToString());
        }
        //eBase.Writeln(ids);
        if (Request.QueryString["columns"] != null)
        {
            tb = eBase.DataBase.getDataTable("select code,Auto from a_eke_sysModels where modelID in (" + ids + ")");
            //eBase.PrintDataTable(tb);
            eDictionary tbs = new eDictionary();
            foreach (DataRow dr in tb.Rows)
            {
                if (dr["code"].ToString().ToLower().StartsWith("a_eke_sys")) continue;
                if (dr["Auto"].ToString().ToLower()=="false") continue;
               // eBase.Writeln(dr["code"].ToString());
                if (tbs.ContainsKey(dr["code"].ToString())) continue;
                tbs.Add(dr["code"].ToString(), "");
                DataTable dt = eBase.DataBase.getSchemaColumns(dr["code"].ToString());
                if (!dt.ExtendedProperties.Contains("name")) dt.ExtendedProperties.Add("name", dr["code"].ToString());
                if (!dt.ExtendedProperties.Contains("description")) dt.ExtendedProperties.Add("description", eBase.DataBase.getTableDescription(dr["code"].ToString()));
                doc.appendModel(dt);
            }
            
        }
       
        
        
       
        //eBase.End();
        if (appid.Length > 0)
        {
            string[] apptables = new string[] { 
            "a_eke_sysApplicationItems", 
            "a_eke_sysApplicationIcons",
            "a_eke_sysApplicationMenus",
            "a_eke_sysApplications"
            };
            foreach (string table in apptables)
            {
                list = new eList(table);
                list.Where.Add("deltag=0 and ApplicationID='" + appid + "'");
                tb = list.getDataTable();
                tb.ExtendedProperties.Add("name", table);
                doc.appendData(tb);

            }
            //eBase.Writeln(appid);
            //eBase.End();
        }
        //eBase.Writeln(ids);
        //eBase.End();

        //eBase.Print(tables);
        foreach (string table in tables)
        {

            list = new eList(table);
            list.Where.Add("deltag=0 and modelid in (" + ids + ")");
            tb = list.getDataTable();
            //eBase.PrintDataTable(tb);
            tb.ExtendedProperties.Add("name", table);
            doc.appendData(tb);

            #region 程序文件

            foreach (DataRow dr in tb.Rows)
            {
                string path = "";
                string basepath = Server.MapPath("~");
                if (dr.Table.Columns.Contains("AspxFile") && 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.Table.Columns.Contains("mAspxFile") && 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
        }
        //return doc.InnerXml.Replace("><", ">\r\n<");
        return doc.InnerXml;
    }
    private void ExportModels()
    {
        string xml = getModelsXML();
        //eBase.Writeln(xml);
        //eBase.End();

        byte[] xmlByte = Encoding.UTF8.GetBytes(xml);
        MemoryStream mstream = new MemoryStream();
        ZipOutputStream zstream = new ZipOutputStream(mstream);
        ZipEntry zen = new ZipEntry("eframework.efw");
        zstream.PutNextEntry(zen);
        //zstream.SetLevel(6);
        zstream.Write(xmlByte, 0, xmlByte.Length);
        zstream.Close();
        zstream.Finish();
        zstream.Close();

        Response.Clear();
        Response.ContentType = "application/octet-stream";
        string strFileName = HttpUtility.UrlEncode("eframework.zip");
        Response.AddHeader("Content-Disposition", "attachment; filename=" + strFileName);
        Response.BinaryWrite(mstream.ToArray());
        Response.Flush();
        Response.End();
    }
    private void ExportApplication()
    {
        string appname = eBase.DataBase.getValue("select mc from a_eke_sysApplications where applicationid='" + appid + "'");
        string xml = getModelsXML();
        byte[] xmlByte = Encoding.UTF8.GetBytes(xml);
        MemoryStream mstream = new MemoryStream();
        ZipOutputStream zstream = new ZipOutputStream(mstream);
        ZipEntry zen = new ZipEntry(appname + ".efw");
        zstream.PutNextEntry(zen);
        //zstream.SetLevel(6);
        zstream.Write(xmlByte, 0, xmlByte.Length);
        zstream.Close();
        zstream.Finish();
        zstream.Close();

        Response.Clear();
        Response.ContentType = "application/octet-stream";
        string strFileName = HttpUtility.UrlEncode(appname + ".zip");
        Response.AddHeader("Content-Disposition", "attachment; filename=" + strFileName);
        Response.BinaryWrite(mstream.ToArray());
        Response.Flush();
        Response.End();
    }

    private string getTablesXML()
    {
        XmlDocument doc = new XmlDocument();
        string[] tables = eParameters.Form("tables").toArray();
        foreach (string table in tables)
        {

            DataTable dt = eBase.DataBase.getSchemaColumns(table);
            if (!dt.ExtendedProperties.Contains("name")) dt.ExtendedProperties.Add("name", table);
            if (!dt.ExtendedProperties.Contains("description")) dt.ExtendedProperties.Add("description", eBase.DataBase.getTableDescription(table));
            doc.appendModel(dt);


            eList list = new eList(table);
            list.Where.Add("deltag=0");//modelid='B9EEA58A-6863-4DA8-836A-AD393E525C9B' and 
            DataTable tb = list.getDataTable();
            tb.ExtendedProperties.Add("name", table);
            doc.appendData(tb);
        }
        return doc.InnerXml;
    }
    private void ExportTables()
    {
        string xml = getTablesXML();
        byte[] xmlByte = Encoding.UTF8.GetBytes(xml);
        MemoryStream mstream = new MemoryStream();
        ZipOutputStream zstream = new ZipOutputStream(mstream);
        ZipEntry zen = new ZipEntry("eframework.config");
        zstream.PutNextEntry(zen);
        //zstream.SetLevel(6);
        zstream.Write(xmlByte, 0, xmlByte.Length);
        zstream.Close();
        zstream.Finish();
        zstream.Close();

        Response.Clear();
        Response.ContentType = "application/octet-stream";
        string strFileName = HttpUtility.UrlEncode("update.zip");
        Response.AddHeader("Content-Disposition", "attachment; filename=" + strFileName);
        Response.BinaryWrite(mstream.ToArray());
        Response.Flush();
        Response.End();
    }
    protected void Page_Load(object sender, EventArgs e)
    {

        //eBase.Write(modelids + "::" + getModelIDS(modelids));
        //eBase.End();

        eUser user = new eUser("Manage");
        user.Check();
        string act = eParameters.Form("act");
        if (act == "exptable")
        {
            ExportTables();
        }
        if (modelids.Length > 0)
        {
             ExportModels();
        }
        else
        {
            if (appid.Length > 0)
            {
                ExportApplication();
            }
            else
            {
                ExportAll();
            }
        }
    }
}