<%@ Page Language="C#" AutoEventWireup="true" %>

<%@ Import Namespace="System.Configuration" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Xml" %>
<%@ Import Namespace="ynhtm.DBUtility" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            var url = this.Request.Url;
            this.txtSiteUrl.Text = url.Scheme + "://" + url.Authority;
            this.txtUserName.Text = "admin";
            this.txtSQLiteDataSource.Text = this.Server.MapPath("~/App_Data/ynhtm.db");
            this.txtSQLServer.Text = Environment.MachineName;
            this.multView.SetActiveView(this.viewMain);
        }
    }

    void SetConnectionString(string connectionString, string providerName)
    {
        var key = ynhtm.DBUtility.DbBase.DBKey;
        var path = this.Server.MapPath("~/Web.config");
        var doc = new XmlDocument();
        doc.Load(path);
        var node = doc.SelectSingleNode("configuration//connectionStrings//add[@name='" + key + "']");
        var attr = node.Attributes["connectionString"];
        if (attr != null)
            attr.Value = connectionString;
        else
        {
            attr = doc.CreateAttribute("connectionString");
            attr.Value = connectionString;
            node.Attributes.Append(attr);
        }
        attr = node.Attributes["providerName"];
        if (attr != null)
            attr.Value = providerName;
        else
        {
            attr = doc.CreateAttribute("providerName");
            attr.Value = providerName;
            node.Attributes.Append(attr);
        }
        doc.Save(path);
    }

    void Success(IDb db)
    {
        db.ExecuteNonQuery(
            File.ReadAllText(Path.GetDirectoryName(this.Request.PhysicalPath) + @"\Setup.sql"),
            db.CreateParameter("SiteName", this.txtSiteName.Text),
            db.CreateParameter("SiteUrl", this.txtSiteUrl.Text),
            db.CreateParameter("UserName", this.txtUserName.Text),
            db.CreateParameter("PassWord", ynhtm.Common.Text.HashMD5(this.ViewState["PassWord"].ToString())),
            db.CreateParameter("IP", this.Request.UserHostAddress),
            db.CreateParameter("PicMaskFile", @"~\Admin\Images\PicMask.png")
            );
        var path = this.Request.PhysicalPath;
        File.Copy(path, Path.ChangeExtension(path, "txt"), true);
        File.Delete(path);
        this.multView.SetActiveView(this.viewSuccess);
    }

    protected void btnNext_Click(object sender, EventArgs e)
    {
        if (this.IsValid)
        {
            this.ViewState["PassWord"] = this.txtPassWord.Text;
            switch (this.radlDbType.Text)
            {
                case "SQLite":
                    this.multView.SetActiveView(this.viewSQLite);
                    break;
                case "SqlServer":
                    this.multView.SetActiveView(this.viewSQLServer);
                    break;
            }
        }
    }

    protected void btnBack_Click(object sender, EventArgs e)
    {
        this.multView.SetActiveView(this.viewMain);
    }

    protected void btnSQLite_Click(object sender, EventArgs e)
    {
        if (this.IsValid)
        {
            var dataSource = this.txtSQLiteDataSource.Text;
            Directory.CreateDirectory(Path.GetDirectoryName(dataSource));
            if (File.Exists(dataSource)) File.Delete(dataSource);
            File.WriteAllText(dataSource, null);
            var connectionString = "data source=" + dataSource;
            this.SetConnectionString(connectionString, "System.Data.SQLite");
            using (var db = new SQLiteDb(connectionString))
            {
                db.ExecuteNonQuery(File.ReadAllText(Path.GetDirectoryName(this.Request.PhysicalPath) + @"\Sqlite.sql"));
                this.Success(db);
            }
        }
    }

    protected void btnSQLServer_Click(object sender, EventArgs e)
    {
        if (this.IsValid)
        {
            var connectionString = "SERVER=" + this.txtSQLServer.Text + ";DATABASE=" + this.txtSQLServerDataBase.Text + ";UID=" + this.txtSQLServerUserName.Text + ";PWD=" + this.txtSQLServerPassWord.Text;
            this.SetConnectionString(connectionString, "System.Data.SqlClient");
            using (var db = new SqlDb(connectionString))
            {
                db.ExecuteNonQuery(File.ReadAllText(Path.GetDirectoryName(this.Request.PhysicalPath) + @"\SqlServer.sql"));
                this.Success(db);
            }
        }
    }
    
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
    <title>盛讯 System 安装向导</title>
    <link rel="stylesheet" type="text/css" href="Style.css" />
</head>
<body>
    <form id="form1" runat="server">
    <div id="wrapper">
        <asp:MultiView ID="multView" runat="server">
            <asp:View ID="viewMain" runat="server">
                <h1>
                    盛讯 System 安装向导</h1>
                <table cellpadding="0" cellspacing="15">
                    <tr>
                        <td class="lab">
                            <span class="red">*</span> 数据库类型:
                        </td>
                        <td>
                            <asp:RadioButtonList ID="radlDbType" runat="server" RepeatDirection="Horizontal"
                                RepeatLayout="Flow">
                                <asp:ListItem Value="SQLite">SQLite</asp:ListItem>
                                <asp:ListItem Value="SqlServer">SQL Server</asp:ListItem>
                            </asp:RadioButtonList>
                            <asp:RequiredFieldValidator runat="server" ControlToValidate="radlDbType" ErrorMessage="请选择"
                                Display="Dynamic" ForeColor="Red"></asp:RequiredFieldValidator><br />
                            <span class="gray">SQLite 数据库不需要额外的软件环境，SQL Server 最低需要 2005 版</span>
                        </td>
                    </tr>
                    <tr>
                        <td class="lab">
                            <asp:Label runat="server" AssociatedControlID="txtSiteName">网站名称:</asp:Label>
                        </td>
                        <td>
                            <asp:TextBox ID="txtSiteName" runat="server" Width="260px"></asp:TextBox>
                        </td>
                    </tr>
                    <tr>
                        <td class="lab">
                            <asp:Label runat="server" AssociatedControlID="txtSiteUrl">网站地址:</asp:Label>
                        </td>
                        <td>
                            <asp:TextBox ID="txtSiteUrl" runat="server" Width="260px"></asp:TextBox>
                        </td>
                    </tr>
                    <tr>
                        <td class="lab">
                            <asp:Label runat="server" AssociatedControlID="txtUserName"><span class="red">*</span> 管理员名称:</asp:Label>
                        </td>
                        <td>
                            <asp:TextBox ID="txtUserName" runat="server" Width="150px"></asp:TextBox>
                            <asp:RequiredFieldValidator runat="server" ControlToValidate="txtUserName" ErrorMessage="请填写"
                                SetFocusOnError="True" Display="Dynamic" ForeColor="Red"></asp:RequiredFieldValidator><br />
                            <span class="gray">后台登录的用户名</span>
                        </td>
                    </tr>
                    <tr>
                        <td class="lab">
                            <asp:Label runat="server" AssociatedControlID="txtPassWord"><span class="red">*</span> 管理员密码:</asp:Label>
                        </td>
                        <td>
                            <asp:TextBox ID="txtPassWord" runat="server" Width="150px" TextMode="Password"></asp:TextBox>
                            <asp:RequiredFieldValidator runat="server" ControlToValidate="txtPassWord" ErrorMessage="请填写"
                                SetFocusOnError="True" Display="Dynamic" ForeColor="Red"></asp:RequiredFieldValidator><br />
                            <span class="gray">后台登录密码，请并牢记它</span>
                        </td>
                    </tr>
                    <tr>
                        <td class="lab">
                            <asp:Label runat="server" AssociatedControlID="txtPassWord1"><span class="red">*</span> 确认密码:</asp:Label>
                        </td>
                        <td>
                            <asp:TextBox ID="txtPassWord1" runat="server" Width="150px" TextMode="Password"></asp:TextBox>
                            <asp:RequiredFieldValidator runat="server" ControlToValidate="txtPassWord1" ErrorMessage="请填写"
                                SetFocusOnError="True" Display="Dynamic" ForeColor="Red"></asp:RequiredFieldValidator><asp:CompareValidator
                                    runat="server" ControlToValidate="txtPassWord1" ControlToCompare="txtPassWord"
                                    ErrorMessage="不正确" Display="Dynamic" ForeColor="Red" SetFocusOnError="True"></asp:CompareValidator><br />
                            <span class="gray">重复上面的密码</span>
                        </td>
                    </tr>
                </table>
                <div id="button">
                    <asp:Button ID="btnNext" runat="server" Text="下一步" OnClick="btnNext_Click" />
                </div>
            </asp:View>
            <asp:View ID="viewSQLite" runat="server">
                <h1>
                    盛讯 System 安装向导（SQLite 设置）</h1>
                <table cellpadding="0" cellspacing="15">
                    <tr>
                        <td class="lab">
                            <asp:Label runat="server" AssociatedControlID="txtSQLiteDataSource"><span class="red">*</span> 数据库路径:</asp:Label>
                        </td>
                        <td>
                            <asp:TextBox ID="txtSQLiteDataSource" runat="server" Width="260px"></asp:TextBox>
                            <asp:RequiredFieldValidator runat="server" ControlToValidate="txtSQLiteDataSource"
                                ErrorMessage="请填写" SetFocusOnError="True" Display="Dynamic" ForeColor="Red"></asp:RequiredFieldValidator><br />
                            <span class="gray">SQLite 数据库文件的完整路径，一般使用 .db 后缀</span>
                        </td>
                    </tr>
                </table>
                <div id="button">
                    <asp:Button runat="server" Text="上一步" CausesValidation="false" UseSubmitBehavior="false"
                        OnClick="btnBack_Click" />
                    <asp:Button ID="btnSQLite" runat="server" Text="确认安装" OnClick="btnSQLite_Click" />
                </div>
            </asp:View>
            <asp:View ID="viewSQLServer" runat="server">
                <h1>
                    盛讯 System 安装向导（SQL Server 设置）</h1>
                <table cellpadding="0" cellspacing="15">
                    <tr>
                        <td class="lab">
                            <asp:Label runat="server" AssociatedControlID="txtSQLServer"><span class="red">*</span> 数据库服务器:</asp:Label>
                        </td>
                        <td>
                            <asp:TextBox ID="txtSQLServer" runat="server" Width="150px"></asp:TextBox>
                            <asp:RequiredFieldValidator runat="server" ControlToValidate="txtSQLServer" ErrorMessage="请填写"
                                SetFocusOnError="True" Display="Dynamic" ForeColor="Red"></asp:RequiredFieldValidator><br />
                            <span class="gray">可以是 IP，半角点号“.”表示本机</span>
                        </td>
                    </tr>
                    <tr>
                        <td class="lab">
                            <asp:Label runat="server" AssociatedControlID="txtSQLServerDataBase"><span class="red">*</span> 数据库名:</asp:Label>
                        </td>
                        <td>
                            <asp:TextBox ID="txtSQLServerDataBase" runat="server" Width="150px"></asp:TextBox>
                            <asp:RequiredFieldValidator runat="server" ControlToValidate="txtSQLServerDataBase"
                                ErrorMessage="请填写" SetFocusOnError="True" Display="Dynamic" ForeColor="Red"></asp:RequiredFieldValidator><br />
                            <span class="gray">需要已建立的数据库名（建议新建一个空库）</span>
                        </td>
                    </tr>
                    <tr>
                        <td class="lab">
                            <asp:Label runat="server" AssociatedControlID="txtSQLServerUserName"><span class="red">*</span> 登录用户名:</asp:Label>
                        </td>
                        <td>
                            <asp:TextBox ID="txtSQLServerUserName" runat="server" Width="150px"></asp:TextBox>
                            <asp:RequiredFieldValidator runat="server" ControlToValidate="txtSQLServerUserName"
                                ErrorMessage="请填写" SetFocusOnError="True" Display="Dynamic" ForeColor="Red"></asp:RequiredFieldValidator><br />
                            <span class="gray">数据库登录用户名，常用：sa</span>
                        </td>
                    </tr>
                    <tr>
                        <td class="lab">
                            <asp:Label runat="server" AssociatedControlID="txtSQLServerPassWord"><span class="red">*</span> 登录密码:</asp:Label>
                        </td>
                        <td>
                            <asp:TextBox ID="txtSQLServerPassWord" runat="server" Width="150px"></asp:TextBox>
                            <asp:RequiredFieldValidator runat="server" ControlToValidate="txtSQLServerPassWord"
                                ErrorMessage="请填写" SetFocusOnError="True" Display="Dynamic" ForeColor="Red"></asp:RequiredFieldValidator><br />
                            <span class="gray">数据库登录密码</span>
                        </td>
                    </tr>
                </table>
                <div id="button">
                    <asp:Button runat="server" Text="上一步" CausesValidation="false" UseSubmitBehavior="false"
                        OnClick="btnBack_Click" />
                    <asp:Button ID="btnSQLServer" runat="server" Text="确认安装" OnClick="btnSQLServer_Click" />
                </div>
            </asp:View>
            <asp:View ID="viewSuccess" runat="server">
                <h1>
                    盛讯 System 安装向导（安装成功）</h1>
                <table cellpadding="0" cellspacing="15">
                    <tr>
                        <td class="lab">
                            数据库类型:
                        </td>
                        <td>
                            <%=this.radlDbType.SelectedItem.Text%>
                        </td>
                    </tr>
                    <tr>
                        <td class="lab">
                            管理员名称:
                        </td>
                        <td>
                            <%=this.Server.HtmlEncode(this.txtUserName.Text)%>
                        </td>
                    </tr>
                    <tr>
                        <td class="lab">
                            管理员密码:
                        </td>
                        <td>
                            <%=this.Server.HtmlEncode(this.ViewState["PassWord"].ToString())%>
                        </td>
                    </tr>
                </table>
                <div id="button">
                    <input type="button" value="进入后台管理入口" onclick="javascript:location = '../Admin/Default.aspx';" />
                </div>
            </asp:View>
        </asp:MultiView>
        <div id="footer">
            版权所有 &copy;
            <%=DateTime.Now.Year%>
            昆明盛讯网络科技有限公司</div>
    </div>
    </form>
</body>
</html>
