using System;
using System.Data;
using System.IO;
using System.Text;
using System.Web;
using isRoc.Core;
using isRoc.Core.UI;
using isRoc.Data;
using isRoc.Data.Entity;

namespace isRoc.Logic.Admin
{
    /// <summary>
    /// 数据库管理类
    /// </summary>
    public class AdminDB
    {
        private SiteFun _fun = new SiteFun();
        private SiteDat _siteDat = new SiteDat();
        private AdminUI _admUi = new AdminUI();
        private HtmlUI _htmlUi = new HtmlUI();

        /// <summary>
        /// 执行SQL语句
        /// </summary>
        public string SQL()
        {
            StringBuilder sr = new StringBuilder();
            string sql = _fun.Post("sql");
            bool reCount = _fun.ToInt(_fun.Post("reCount")) == 0 ? false : true;
            if (_fun.IsPost && reCount)
            {
                int count = new PostData().CountPost();
                count += new ColumnData().CountColumnPost();
                sr.Append(_admUi.SuccessBox(string.Format(_siteDat.GetLan("MsgCountSucc"), count)));
            }
            //数量重计
            sr.Append(_admUi.AdminBoxStart(true));
            sr.Append(_htmlUi.FormStart());
            sr.Append(_htmlUi.TableStart("onCenter"));
            sr.Append(_htmlUi.TrStart());
            sr.Append(_htmlUi.CreateTh(_siteDat.GetLan("ReCount")));
            sr.Append(_htmlUi.CreateTd(_htmlUi.HiddenInput("reCount", 1) + _htmlUi.SubmitButton(_siteDat.GetLan("BtnCount")) + _siteDat.GetLan("IntroCount")));
            sr.Append(_htmlUi.TrFinal());
            sr.Append(_htmlUi.TableFinal());
            sr.Append(_htmlUi.FormFinal());
            sr.Append(_admUi.AdminBoxFinal());
            //SQL执行
            sr.Append(_admUi.AdminBoxStart(true));
            sr.Append(_htmlUi.FormStart());
            sr.Append(_htmlUi.TableStart("onCenter"));
            sr.Append(_htmlUi.TrStart());
            sr.Append(_htmlUi.CreateTh("SQL") + _htmlUi.CreateTd(_htmlUi.Textarea("sql", 20, 0, _fun.HtmlEncode(sql))));
            sr.Append(_htmlUi.TrFinal());
            sr.Append(_htmlUi.TrStart());
            sr.Append(_htmlUi.CreateTh() + _htmlUi.CreateTd(_htmlUi.SubmitButton() + _htmlUi.ResetButton()));
            sr.Append(_htmlUi.TrFinal());
            sr.Append(_htmlUi.TableFinal());
            sr.Append(_htmlUi.FormFinal());
            sr.Append(_admUi.AdminBoxFinal());
            //取得默认值
            if (_fun.IsPost && !string.IsNullOrEmpty(sql))
            {
                try
                {
                    DataSet ds = new DataBase().ExecSql(sql);
                    sr.Append(_admUi.SuccessBox(_siteDat.GetLan("MsgExeSqlSucc")));
                    //显示执行结果
                    if (ds.Tables.Count > 0)
                    {
                        sr.Append(_admUi.AdminBoxStart(true));
                        sr.Append(_htmlUi.FormStart());
                        sr.Append(_htmlUi.TableStart());
                        sr.Append(_htmlUi.TrStart());
                        for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
                        {
                            sr.Append(_htmlUi.CreateTh(ds.Tables[0].Columns[i].ColumnName));
                        }
                        sr.Append(_htmlUi.TrFinal());
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            sr.Append(_htmlUi.TrStart());
                            for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
                            {
                                sr.Append(_htmlUi.CreateTd(_fun.HtmlEncode(ds.Tables[0].Rows[i][j].ToString())));
                            }
                            sr.Append(_htmlUi.TrFinal());
                        }
                        sr.Append(_htmlUi.TableFinal());
                        sr.Append(_htmlUi.FormFinal());
                        sr.Append(_admUi.AdminBoxFinal());
                    }
                }
                catch (Exception err) { sr.Append(_admUi.ErrorBox(err.Message)); }
            }
            return sr.ToString();
        }

        /// <summary>
        /// 备份和恢复
        /// </summary>
        public string Backup()
        {
            StringBuilder sr = new StringBuilder();
            string backupPath = Path.Combine(SiteCfg.Router, "Common/Data/Backup/");
            if (_fun.IsPost)
            {
                try
                {
                    bool dbSel = _fun.ToInt(_fun.Post("dbSel")) > 0;
                    bool attachSel = _fun.ToInt(_fun.Post("attachSel")) > 0;
                    bool delBackup = _fun.ToInt(_fun.Post("del")) > 0;
                    bool sendMail = _fun.ToInt(_fun.Post("sendMail")) > 0;
                    string fileName = _fun.Post("fileName");
                    //开始备份数据
                    if (dbSel || attachSel)
                    {
                        if (dbSel)
                        {
                            string dbFile = HttpContext.Current.Server.MapPath(SiteCfg.DBPath);
                            string tmpSavFileName = string.Format("{1}-{0}.bak", Path.GetFileNameWithoutExtension(dbFile), DateTime.Now.ToString("yyyyMMdd"));
                            File.Copy(dbFile, Path.Combine(backupPath, tmpSavFileName), true);
                        }
                        //开始备份附件
                        if (attachSel)
                        {
                            //Folder.CopyFolder(Path.Combine(SiteCfg.Router, @"Attach\"), Path.Combine(rootFolder, @"Attach\"));
                        }
                        sr.Append(_admUi.SuccessBox(_siteDat.GetLan("MsgBackupSucc")));
                    }
                    else
                    {
                        if (sendMail)
                        {
                            SettingBasicItem basic = new SettingData().GetSetting().Basic;
                            SiteMail mail = new SiteMail();
                            string dt = DateTime.Now.ToString("yyyy-MM-dd");
                            mail.To = basic.Mail;
                            mail.Subject = string.Format("{0} DB BAK, {1}", basic.Name, dt);
                            mail.From = basic.MailFrom;
                            mail.Body = "Time: " + dt;
                            mail.Host = basic.MailHost;
                            mail.Port = basic.MailPort;
                            mail.UserName = basic.MailUserID;
                            mail.Password = basic.MailPassword;
                            mail.Send(Path.Combine(backupPath, fileName));
                            sr.Append(_admUi.SuccessBox(_siteDat.GetLan("MsgBackupSucc")));
                        }
                        if (delBackup)
                        {
                            File.Delete(Path.Combine(backupPath, fileName));
                            sr.Append(_admUi.SuccessBox(_siteDat.GetLan("MsgDelBackupSucc")));
                        }
                    }
                }
                catch (Exception err) { sr.Append(_admUi.ErrorBox(err.Message)); }
            }
            sr.Append(_admUi.AdminBoxStart(true));
            sr.Append(_htmlUi.FormStart());
            sr.Append(_htmlUi.TableStart("onCenter"));
            sr.Append(_htmlUi.TrStart());
            sr.Append(_htmlUi.CreateTh(_siteDat.GetLan("Backup")) + _htmlUi.CreateTd(_htmlUi.CheckBoxInput(_siteDat.GetLan("Database"), "dbSel", 1, false)));
            /*sr.Append(_htmlUi.CreateTh(_siteDat.GetLan("Backup")) + _htmlUi.CreateTd(_htmlUi.CheckBoxInput(_siteDat.GetLan("Database"), "dbSel", 1, false) + _htmlUi.CheckBoxInput(_siteDat.GetLan("Attach"), "attachSel", 1, false)));*/
            sr.Append(_htmlUi.TrFinal());
            sr.Append(_htmlUi.TrStart());
            sr.Append(_htmlUi.CreateTh() + _htmlUi.CreateTd(_htmlUi.SubmitButton() + _htmlUi.ResetButton()));
            sr.Append(_htmlUi.TrFinal());
            sr.Append(_htmlUi.TableFinal());
            sr.Append(_htmlUi.FormFinal());
            sr.Append(_admUi.AdminBoxFinal());
            //列表
            sr.Append(_admUi.AdminBoxStart(true));
            sr.Append(_htmlUi.TableStart());
            sr.Append(_htmlUi.TrStart());
            sr.Append(_htmlUi.CreateTh(_siteDat.GetLan("FileName")));
            sr.Append(_htmlUi.CreateTh(_siteDat.GetLan("DateTime")));
            sr.Append(_htmlUi.CreateTh(_siteDat.GetLan("Size")));
            sr.Append(_htmlUi.CreateTh(_siteDat.GetLan("Delete")));
            sr.Append(_htmlUi.CreateTh(_siteDat.GetLan("MailNotice")));
            sr.Append(_htmlUi.CreateTh(_siteDat.GetLan("Operate")));
            sr.Append(_htmlUi.TrFinal());
            //循环
            int i = 1;
            foreach (string file in Directory.GetFiles(backupPath))
            {
                i++;
                FileInfo fileInfo = new FileInfo(file);
                sr.Append(_htmlUi.FormStart());
                sr.Append(_htmlUi.TrStart(i % 2 == 0 ? " cRow" : null));
                sr.Append(_htmlUi.CreateTd(fileInfo.Name));
                sr.Append(_htmlUi.CreateTd(fileInfo.CreationTime));
                sr.Append(_htmlUi.CreateTd(_fun.ToInt(fileInfo.Length / 1024) + " Kb"));
                sr.Append(_htmlUi.CreateTd(_htmlUi.CheckBoxInput("del", 1, false)));
                sr.Append(_htmlUi.CreateTd(_htmlUi.CheckBoxInput("sendMail", 1, false)));
                sr.Append(_htmlUi.CreateTd(_htmlUi.HiddenInput("fileName", _fun.HtmlEncode(fileInfo.Name)) + _htmlUi.SubmitButton()));
                sr.Append(_htmlUi.TrFinal());
                sr.Append(_htmlUi.FormFinal());
            }
            //循环结束
            sr.Append(_htmlUi.TableFinal());
            sr.Append(_admUi.AdminBoxFinal());
            return sr.ToString();
        }
    }
}
