using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Web.Configuration;
using System.Xml;
using System.Data;
using System.Data.SqlClient;
using SysDoor;
using SysCore;

public partial class Root_Account_Create : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        new RootControl().CheckRootLogin();
        if (!Page.IsPostBack)
        {
            txt_dir.Text="D:\\xplat\\";
        }
    }
    protected void btnCreate_Click(object sender, EventArgs e)
    {
        lbl_msg.Text = "";
        string db_id = txt_db_id.Text.Trim();
        string account_name = txt_account_name.Text.Trim();
        db_id = db_id.Replace(" ", "")
                     .Replace("'", "");
        account_name = account_name.Replace(" ", "")
                     .Replace("'", "");
        if (db_id.Equals(""))
        {
            lbl_msg.Text = "账套号不允许为空！";
            return;
        }
        if (account_name.Equals(""))
        {
            lbl_msg.Text = "账套名称不允许为空！";
            return;
        }
        if (!XTools.IsPositiveInt(db_id))
        {
            lbl_msg.Text = "账套号必须为正整数！";
            return;
        }
        string db_name = "xplat" + db_id;
        SqlUtil su = new SqlUtil();
        su.SetDatabaseName("master");
        string sql = "select count(1) from master..sysdatabases where [name]='" + db_name + "'";
        if (Convert.ToInt32(su.ExecuteScalar(sql, null)) > 0)
        {
            lbl_msg.Text = "账套" + db_id + "已存在！";
            return;
        }
        
        string dir = txt_dir.Text;
        if (dir.Substring(dir.Length - 1).Equals("\\"))
        {
            dir = dir.Substring(0, dir.Length - 1);
        }
        //如果不存在目录
        if (!Directory.Exists(dir))
        {
            try
            {
                //创建目录
                Directory.CreateDirectory(dir);
            }
            catch
            {
                lbl_msg.Text = "创建存放文件夹失败！可能权限不足,可尝试手工建立文件夹后再重试。";
            }
        }

        sql = "create database [xplat" + db_id + "](filename='" + dir + "')";
        sql = @"
            CREATE DATABASE [@db_name]
            ON 
            PRIMARY
            ( 
	            NAME='@db_name', 
	            FILENAME='@dir\@db_name.mbf'
            ) 
            LOG ON
            ( 
	            NAME='@db_name_log',
	            FileName='@dir\@db_name.ldf'
            )";
        sql = sql.Replace("@db_name", db_name)
                 .Replace("@dir", dir);

        try
        {
            su.ExecuteNonQuery(sql, null);
        }
        catch (Exception err)
        {
            lbl_msg.Text = "建账失败！具体错误：<br/><br/>" + err.Message;
            return;
        }
        Response.Redirect("InstallSQL_Frame.aspx?db_name=" + db_name + "&account_name=" + account_name + "&create_db=1");
    }
}