using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;
using EKETEAM.Data;
using EKETEAM.FrameWork;
using System.Xml;
using System.Xml.Serialization;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;

namespace eFrameWork.Manage
{
    public partial class ModelImport : System.Web.UI.Page
    {
        public eUser user;
        public eExtensionsList allowExts = new eExtensionsList(".efw.zip");
        protected void Page_Load(object sender, EventArgs e)
        {
            user = new eUser("Manage");
            user.Check();
            #region 安全性检查
            if (Request.UrlReferrer == null) Response.End();
            if (Request.Url.Host.ToLower() != Request.UrlReferrer.Host.ToLower()) Response.End();// || Request.Url.Port != Request.UrlReferrer.Port
            //if (!eConfig.portMapping && Request.Url.Port != Request.UrlReferrer.Port) Response.End();
            //如果判断端口，则端口映射/转发无法保存
            #endregion

            #region 保存文件
            if (Request.Files.Count == 1)
            {
                HttpPostedFile file = Request.Files[0];
                if (file.ContentLength > 0)
                {
                    string tempPath = eRunTime.tempPath;
                    string ext = file.FileName.fileExtension();
                    if(!allowExts.Contains(ext))
                    {
                        //Response.Write("<script>alert('文件格式不正确!');document.location='Models.aspx';</script>");
                        Response.Write("<script>parent.layer.msg('文件格式不正确!');document.location='ModelImport.aspx';</script>");
                        Response.End();
                    }

                    string filename = eBase.GetFileName() + ext;
                    string pathname = tempPath + filename;
                    if (!Directory.Exists(tempPath)) Directory.CreateDirectory(tempPath);
                    file.safeSaveAs(pathname, allowExts);

                    //eBase.AppendLog(ext + "::" + pathname);
                    if (ext.ToLower() == ".efw")
                    {
                        #region efw处理
                        System.IO.StreamReader sr = new System.IO.StreamReader(pathname, System.Text.Encoding.UTF8);
                        string line = sr.ReadLine();
                        sr.Close();

                        if (line.StartsWith("{"))
                        {
                            //import_json(pathname);
                        }
                        else
                        {
                            import_xml(pathname);
                        }
                        #endregion
                    }
                    if (ext.ToLower() == ".zip")
                    {
                        #region zip处理
                        new FastZip().ExtractZip(pathname, tempPath, @"+\.efw;");//覆盖
                        try
                        {
                            System.IO.File.Delete(pathname);
                        }
                        catch
                        {
                        }
                        eDirectoryInfo dinfo = new eDirectoryInfo(tempPath);
                        foreach (FileInfo _file in dinfo.GetFiles("*.efw"))
                        {
                            //eBase.AppendLog(_file.Name + "::" + _file.FullName);
                            import_xml(_file.FullName);
                        }
                        #endregion
                    }
                    eBase.clearDataCache(); //清除所有缓存
                    //Response.Write("<script>alert('导入成功!');document.location='Models.aspx';</script>");
                    Response.Write("<script>parent.layer.msg('导入成功!');setTimeout(function(){parent.document.location.assign(parent.document.location.href);},2000);</script>"); //parent.layer.close(parent.arrLayerIndex.pop());
                    Response.End();
          
                }

            }
            #endregion
        }
        private void import_xml(string pathname)
        {
            XmlDocument doc = new XmlDocument();
            //eBase.Writeln(pathname);
            try
            {
                doc.Load(pathname);
                System.IO.File.Delete(pathname);
            }
            catch
            {
            }

           
            //eBase.WriteHTML(doc.InnerXml);
            //eBase.End();
           
          
            XmlNode node = doc.SelectSingleNode("/root/model");
            if (node != null)
            {
                List<string> tables = new List<string>();

                foreach (XmlNode _node in node.ChildNodes)
                {
                    string tablename = _node.Attributes["name"].Value.ToLower();
                    if (tables.Contains(tablename)) continue;
                    tables.Add(tablename);
                    //eBase.Writeln(_node.Name + "::" + _node.Attributes.Count.ToString() + "::" + _node.Attributes["name"].Value + "::" + _node.Attributes["description"].Value);
                    DataTable dt = _node.ChildNodes.toDataTable();
                    //eBase.PrintDataTable(dt);
                    eBase.DataBase.SchemaCreate(dt); 
                }
            }
           
            node = doc.SelectSingleNode("/root/data");
            if (node != null)
            {
                List<string> tables = new List<string>();
                foreach (XmlNode _node in node.ChildNodes)
                {
                    string tablename=_node.Attributes["name"].Value.ToLower();
                    if (tables.Contains(tablename)) continue;
                    tables.Add(tablename);
                    //eBase.Writeln("Data:" + _node.Name + "::" + _node.Attributes["name"].Value);
                    DataTable dt = _node.ChildNodes.toDataTable();
                    eBase.DataBase.SchemaImport(dt);
                    //eBase.End();
                }
                //eBase.End();
            }
            //eBase.End();
            node = doc.SelectSingleNode("/root/files");
            if (node != null)
            {
                string basepath = Server.MapPath("~");
                foreach (XmlNode _node in node.ChildNodes)
                {
                    string path = _node.Attributes["path"].Value;
                    string filepath = basepath + path.Replace("..", "").Replace("/", "\\");
                    //filepath += ".txt";
                    string body = System.Web.HttpUtility.HtmlDecode(_node.InnerXml);
                    eFileInfo efi = new eFileInfo(filepath);
                    if (!Directory.Exists(efi.Path)) Directory.CreateDirectory(efi.Path);
                    eBase.WriteFile(filepath, body);
                }
                
            }
            
            GC.Collect();
            GC.WaitForPendingFinalizers();
            //eBase.End();
        }
        /*
        private void import_json(string pathname)
        {
            string _json = eBase.ReadFile(pathname);

            try
            {
                System.IO.File.Delete(pathname);
            }
            catch
            {
            }

            eJson json = new eJson(_json);
            eJson model = json.GetCollection("a_eke_sysModels").Collection[0];
            string file = model.GetValue("AspxFile");
            string aspxFile = Server.MapPath("~/System/") + file + ".log";
            if (json.IsValue("aspxFile"))
            {
                string text = json.GetValue("aspxFile");
                eBase.WriteFile(aspxFile, text);
            }
            string csFile = Server.MapPath("~/System/") + file + ".cs.log";
            if (json.IsValue("csFile"))
            {
                string text = json.GetValue("csFile");
                eBase.WriteFile(csFile, text);
            }
            string desFile = Server.MapPath("~/System/") + file + ".designer.cs.log";
            if (json.IsValue("desFile"))
            {
                string text = json.GetValue("desFile");
                eBase.WriteFile(desFile, text);
            }
            eOleDB.ImportJson(_json, false);
        }
        */

        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(); 
            }
            */
        }
    }
}