using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;

using SnSee.Config;
using SnSee.Bean;

public partial class Admin_SystemConfig_Version : System.Web.UI.Page
{
    AdminBaseBean _AdminBeanLogin = null;
    private bool IsMustUpdate = true;
    private XmlDocument _XmlDocument = null;
    private XmlNode _FileNode = null;
    private XmlNode _DataNode = null;
    private XmlNode _ExplainNode = null;
    XmlDataSource xdsFile = new XmlDataSource();
    XmlDataSource xdsData = new XmlDataSource();
    protected string UpdateExplainText;

    protected void Page_Load(object sender, EventArgs e)
    {
        SnSee.Module.Admin.Admin.AdminIsLogin(out _AdminBeanLogin, true);
        if (!SnSee.Module.Admin.Admin.IsSystemManage(_AdminBeanLogin.AdminName, _AdminBeanLogin.AdminPwd))
        {
            Response.Redirect("../ErrorTip.aspx?EMsg=您目前无权限访问当前页，请联系网站管理员！");
        }

        //升级文件
        string Version = SnSee.Module.Systems.Version.GetSystemVersion();
        bool IsNowVersioExists; string NewVersioUrl;
        string NewVersion = SnSee.Module.Systems.Version.GetSystemVersionNew(out IsNowVersioExists, out NewVersioUrl);

        if (!IsNowVersioExists)
        {
            IsMustUpdate = false;
            lbtnUpdate.Visible = false;
            lblMsg.Text = "错误提示：<br />您当前的系统版本号存在异常，请核查！<br />核查方法：在系统管理目录下的“Version.xml”文件中记载着系统版本号，您如果对该文件做过修改，请还原其修改前数据！<br /></span>";
        }

        if (string.IsNullOrEmpty(NewVersion) || System.String.CompareOrdinal(NewVersion, Version) <= 0)
        {
            IsMustUpdate = false;
            lbtnUpdate.Visible = false;
            lblMsg.Text = "提示：没有要升级的版本！";
        }

        if (IsMustUpdate)
        {
            _XmlDocument = SnSee.Module.Systems.Version.GetUpdateXmlDocument(out _FileNode, out _DataNode, out _ExplainNode);
            if (_XmlDocument != null)
            {
                rptList_DataBind(_FileNode, _DataNode);
                if (_ExplainNode != null)
                {
                    UpdateExplainText = _ExplainNode.InnerXml;
                    if (string.IsNullOrEmpty(UpdateExplainText))
                    {
                        pnlUpdateExplainText.Visible = false;
                    }
                }
            }
        }
        else
        {
            pnlFileUpdate.Visible = false;
            pnlDataUpdate.Visible = false;
        }
    }

    /// <summary>
    /// 载入列表
    /// </summary>
    private void rptList_DataBind(XmlNode _FileNode, XmlNode _DataNode)
    {
        if (_FileNode != null)
        {
            xdsFile.ID = "xdsFileList" + Guid.NewGuid().ToString();
            xdsFile.Data = _FileNode.OuterXml;
            rptList.DataSource = xdsFile;
            rptList.DataBind();
            xdsFile.Dispose();
        }
        else
        {
            pnlFileUpdate.Visible = false;
        }
        if (_DataNode != null)
        {
            xdsData.ID = "xdsDataList" + Guid.NewGuid().ToString();
            xdsData.Data = _DataNode.OuterXml;
            rptDataList.DataSource = xdsData;
            rptDataList.DataBind();
            xdsData.Dispose();
        }
        else
        {
            pnlDataUpdate.Visible = false;
        }
    }

    protected void lbtnUpdate_Click(object sender, EventArgs e)
    {
        //升级文件
        string Version = SnSee.Module.Systems.Version.GetSystemVersion();
        bool IsNowVersioExists; string NewVersioUrl;
        string NewVersion = SnSee.Module.Systems.Version.GetSystemVersionNew(out IsNowVersioExists, out NewVersioUrl);

        if (!IsNowVersioExists)
        {
            lblMsg.Text = "<span class='align_left'><br />错误提示：<br />您当前的系统版本号存在异常，请核查！<br />核查方法：在系统管理目录下的“Version.config”文件中记载着系统版本号，您如果对该文件做过修改，请还原其修改前数据！<br /></span>";
            return;
        }

        if (_XmlDocument == null)
        {
            lblMsg.Text = "错误提示：无法获取升级文件列表！";
            return;
        }

        if (string.IsNullOrEmpty(NewVersion) || System.String.CompareOrdinal(NewVersion, Version) <= 0)
        {
            lblMsg.Text = "提示：没有要升级的版本！";
            return;
        }

        #region 升级准备
        #region 数据库准备
        string BakFilePath = null;
        if (_DataNode != null && _DataNode.ChildNodes.Count > 0)
        {
            //检查数据库
            if (!SnSee.Module.Systems.Version.UpdateDataCheck(_DataNode))
            {
                lblMsg.Text = "提示：数据库中有存在要升级的数据列表中的表或字段，无法执行升级，如果您手动更改过数据库结构，请还原后重试！";
                return;
            }

            //备份数据库
            if (!SnSee.Module.Systems.Version.UpdateDataBackup(out BakFilePath))
            {
                lblMsg.Text = "错误提示：在备份数据库时出现错误，请重试或联系产品开发者！";
                return;
            }
        }
        #endregion

        string tempDir = null;
        #region 文件准备
        if (_FileNode != null && _FileNode.ChildNodes.Count > 0)
        {
            //下载文件
            tempDir = SnSee.Module.Systems.Version.UpdateFileDownload(_FileNode);
            if (string.IsNullOrEmpty(tempDir))
            {
                lblMsg.Text = "错误提示：在下载升级的文件时出现错误，请重试或联系产品开发者！";
                return;
            }

            //备份文件
            if (!SnSee.Module.Systems.Version.UpdateFileBackup(_FileNode))
            {
                lblMsg.Text = "错误提示：在备份需升级的文件时出现错误，请重试或联系产品开发者！";
                return;
            }
        }
        #endregion
        #endregion

        #region 执行升级
        #region 数据库升级
        if (_DataNode != null && _DataNode.ChildNodes.Count > 0)
        {
            //更新数据库
            if (!SnSee.Module.Systems.Version.UpdateData(_DataNode))
            {
                lblMsg.Text = "错误提示：在升级数据库时出现错误，请重试或联系产品开发者！";
                return;
            }
        }
        #endregion

        #region 文件升级
        bool IsUpdate = true;
        if (_FileNode != null && _FileNode.ChildNodes.Count > 0)
        {
            try
            {
                for (int i = 0; i < _FileNode.ChildNodes.Count; i++)
                {
                    if (_FileNode.ChildNodes[i] != null && _FileNode.ChildNodes[i].Attributes["FilePath"] != null && !string.IsNullOrEmpty(_FileNode.ChildNodes[i].Attributes["FilePath"].InnerText))
                    {
                        string strFilePath = System.Web.HttpContext.Current.Server.MapPath(SnSee.Config.WebConfig.WebPath + "/" + tempDir + "/" + _FileNode.ChildNodes[i].Attributes["FilePath"].InnerText);
                        string strToFilePath = System.Web.HttpContext.Current.Server.MapPath(_FileNode.ChildNodes[i].Attributes["FilePath"].InnerText);

                        try
                        {
                            if (System.IO.File.Exists(strFilePath))
                            {
                                System.IO.File.Copy(strFilePath, strToFilePath, true);
                                //升级文件成功
                                if (_FileNode.ChildNodes[i].Attributes["State"] != null)
                                {
                                    _FileNode.ChildNodes[i].Attributes["State"].InnerText = "升级成功";
                                }
                            }
                            else
                            {
                                IsUpdate = false;
                                if (_FileNode.ChildNodes[i].Attributes["State"] != null)
                                {
                                    _FileNode.ChildNodes[i].Attributes["State"].InnerText = "升级失败";
                                }
                            }
                        }
                        catch
                        {
                            IsUpdate = false;
                            if (_FileNode.ChildNodes[i].Attributes["State"] != null)
                            {
                                _FileNode.ChildNodes[i].Attributes["State"].InnerText = "升级失败";
                            }
                            break;
                        }
                    }
                }
            }
            catch
            {
                IsUpdate = false;
                return;
            }
        }
        #endregion
        #endregion

        #region 升级操作执行后
        if (IsUpdate)
        {//成功
            //删除升级临时文件
            if (SnSee.Module.File.FileInfo.DeleteDirectory(tempDir, true))
            {
                System.IO.Directory.Delete(System.Web.HttpContext.Current.Server.MapPath(tempDir));
            }

            //设置当前系统版本号
            SnSee.Module.Systems.Version.SetSystemVersion(NewVersion);

            #region 删除与更新文件同目录的备份文件
            if (_FileNode != null && _FileNode.ChildNodes.Count > 0)
            {
                for (int i = 0; i < _FileNode.ChildNodes.Count; i++)
                {
                    try
                    {
                        if (_FileNode.ChildNodes[i] != null && _FileNode.ChildNodes[i].Attributes["FilePath"] != null && !string.IsNullOrEmpty(_FileNode.ChildNodes[i].Attributes["FilePath"].InnerText))
                        {
                            string backFilePath = System.Web.HttpContext.Current.Server.MapPath(_FileNode.ChildNodes[i].Attributes["FilePath"].InnerText + ".bak");
                            if (System.IO.File.Exists(backFilePath))
                            {
                                System.IO.File.Delete(backFilePath);
                            }
                        }
                    }
                    catch
                    {
                    }
                }
            }
            #endregion

            lblMsg.Text = "恭喜您，系统升级成功！";
            lbtnUpdate.Visible = false;
        }
        else
        {//失败，从备份文件中还原文件
            bool IsRevert = true;
            try
            {
                if (_FileNode != null && _FileNode.ChildNodes.Count > 0)
                {
                    for (int i = 0; i < _FileNode.ChildNodes.Count; i++)
                    {
                        if (_FileNode.ChildNodes[i] != null && _FileNode.ChildNodes[i].Attributes["FilePath"] != null && !string.IsNullOrEmpty(_FileNode.ChildNodes[i].Attributes["FilePath"].InnerText))
                        {
                            string backFilePath = System.Web.HttpContext.Current.Server.MapPath(_FileNode.ChildNodes[i].Attributes["FilePath"].InnerText + ".bak");
                            if (System.IO.File.Exists(backFilePath))
                            {
                                try
                                {
                                    System.IO.File.Copy(_FileNode.ChildNodes[i].Attributes["FilePath"].InnerText + ".bak", _FileNode.ChildNodes[i].Attributes["FilePath"].InnerText, true);
                                }
                                catch
                                {
                                    IsRevert = false;
                                }
                            }
                        }
                    }
                }

                //还原数据库文件
                try
                {
                    string DataPath = null;
                    string AccessConnectionString = System.Configuration.ConfigurationManager.AppSettings["AccessConnectionString"];
                    if (!string.IsNullOrEmpty(AccessConnectionString))
                    {
                        string[] arr = AccessConnectionString.Split(new char[] { ';' });
                        if (arr != null && arr.Length > 0)
                        {
                            for (int i = 0; i < arr.Length; i++)
                            {
                                if (arr[i].ToString().Contains("Data Source"))
                                {
                                    string[] arrDataSource = arr[i].ToString().Split(new char[] { '=' });
                                    if (arrDataSource != null && arrDataSource.Length > 1)
                                    {
                                        DataPath = arrDataSource[1];
                                    }
                                }
                            }
                        }
                    }

                    System.IO.File.Copy(BakFilePath, DataPath, true);

                }
                catch
                {
                    IsRevert = false;
                }
            }
            catch
            {
                IsRevert = false;
            }

            if (IsRevert)
            {
                lblMsg.Text = "错误提示：在升级文件时出现错误，系统已经还原升级前文件！如需升级请重新操作！";
            }
            else
            {
                lblMsg.Text = "错误提示：在升级文件时出现错误，请重试！如果系统无法使用，请用相应的备份文件(系统管理目录下的“VersionUpdateHistory”目录有备份历史)替换升级失败的文件！";
            }
        }
        #endregion

        rptList_DataBind(_FileNode, _DataNode);
    }
}