using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Web.UI;
using System.Xml;
using isRoc.Core;
using isRoc.Logic;
using isRoc.Logic.Admin;

namespace isRoc.Web
{
    /// <summary>
    /// 管理平台类
    /// </summary>
    public partial class AdminCP : System.Web.UI.Page
    {
        private SiteFun _fun = new SiteFun();
        private SiteDat _siteDat = new SiteDat();
        private _AdminCookie _ac = new _AdminCookie();

        /// <summary>
        /// 获取标题
        /// </summary>
        /// <returns></returns>
        public string GetTitle()
        {
            return _siteDat.GetLan("AdmCpTitle");
        }

        /// <summary>
        /// 后台页面执行过程
        /// </summary>
        /// <param name="sender">系统对象</param>
        /// <param name="e">事件对象</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack) { Page.DataBind(); }
            try
            {
                Stopwatch watch = new Stopwatch();
                watch.Start();
                //菜单HTML设置
                StringBuilder parentMenu = new StringBuilder();
                parentMenu.AppendLine("<div class=\"item\" id=\"{$ID}\">");
                parentMenu.AppendLine("\t<div class=\"top\">");
                parentMenu.AppendLine("\t\t<a class=\"menuCap\" rel=\"{$Rel}\">{$Caption}</a><span></span>");
                parentMenu.AppendLine("\t</div>");
                parentMenu.AppendLine("\t<div class=\"content\">");
                parentMenu.AppendLine("\t\t<ul>");
                parentMenu.AppendLine("\t\t{$ItemList}");
                parentMenu.AppendLine("\t\t</ul>");
                parentMenu.AppendLine("\t</div>");
                parentMenu.AppendLine("</div>");
                string menuItem = "<li><a href=\"{$Link}\">{$Caption}</a>{$Icon}</li>";
                //初始化后台基类
                _AdminBase admBase = new _AdminBase();
                //初始化全局数据连接
                admBase.InitConn();
                menuDisplay.Text = new _AdminBase().MenuCode(GetMenuXml(admBase.IsLogin), parentMenu.ToString(), menuItem);
                //是否登录
                if (admBase.IsLogin)
                {
                    //是否是用户控件扩展
                    if (_fun.Query("act") == "extend")
                    {
                        try
                        {
                            string folder = _fun.Query("folder");
                            string key = _fun.Query("key");
                            if (!string.IsNullOrEmpty(folder)) { folder = folder.Replace("..", string.Empty); }
                            XmlDocument extendXml = new XmlDocument();
                            string configXmlPath = Path.Combine(SiteCfg.Router, string.Format("Common/Expand/_Admin/{0}/Config.xml", folder));
                            if (File.Exists(configXmlPath))
                            {
                                extendXml.Load(configXmlPath);
                                //用户控件的文件名
                                string ucFile = string.Empty;
                                foreach (XmlNode node in extendXml.SelectNodes("/root/item"))
                                {
                                    if (node.Attributes["key"].Value == key)
                                    {
                                        ucFile = node.Attributes["file"].Value;
                                        if (!string.IsNullOrEmpty(ucFile)) { ucFile = ucFile.Replace("..", string.Empty); }
                                        break;
                                    }
                                }
                                string ucFilePath = string.Format("Common/Expand/_Admin/{0}/{1}", folder, ucFile);
                                if (File.Exists(Path.Combine(SiteCfg.Router, ucFilePath)))
                                {
                                    Control uc = new UserControl().LoadControl(ucFilePath);
                                    mainDisplay.Controls.Add(uc);
                                }
                                else { mainDisplay.Text = "No " + ucFilePath; }
                            }
                        }
                        catch (Exception er) { mainDisplay.Text = er.Message; }
                    }
                    else { mainDisplay.Text = getMainCode(); }
                }
                else { mainDisplay.Text = admBase.LoginWindow(); }
                powered.Text = SiteCfg.Powered;
                watch.Stop();
                debug.Text = watch.Elapsed.TotalSeconds.ToString("0.0000");
                watch.Reset();
            }
            catch (Exception err)
            {
                IMyError exeError = new MyError();
                foreach (IMyError myError in new SiteExpand().GetTypes(typeof(IMyError).FullName))
                {
                    exeError = myError;
                    break;
                }
                exeError.PrintError(err);
            }
        }

        /// <summary>
        /// 获取管理菜单的XML内容
        /// </summary>
        /// <param name="isLogin">是否登录状态</param>
        /// <returns>返回完整XML内容</returns>
        private string GetMenuXml(bool isLogin)
        {
            StringBuilder xml = new StringBuilder();
            xml.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
            xml.AppendLine("<root>");
            int i = 0;
            if (isLogin)
            {
                i++;
                xml.AppendFormat("<parent name=\"{0}\" id=\"menu_{1}\" rel=\"{1}\">", _siteDat.GetLan("AdmMenuIdx"), i);
                xml.AppendFormat("<item name=\"{0}\" link=\"./\" icon=\"home.gif\"/>", _siteDat.GetLan("AdmMenuBackHome"));
                xml.AppendFormat("<item name=\"{0}\" link=\"?\" icon=\"system.gif\"/>", _siteDat.GetLan("AdmMenuWelcome"));
                xml.AppendLine("<item name=\"" + _siteDat.GetLan("AdmMenuExit") + "\" link=\"javascript:if(confirm('" + _siteDat.GetLan("MsgAdmExit") + "')){top.location.href='?act=exit';};\" icon=\"verify.gif\"/>");
                xml.AppendLine("</parent>");
                i++;
                xml.AppendFormat("<parent name=\"{0}\" id=\"menu_{1}\" rel=\"{1}\">", _siteDat.GetLan("AdmMenuBasic"), i);
                xml.AppendFormat("<item name=\"{0}\" link=\"?act=basic&amp;mode=base\" icon=\"system.gif\"/>", _siteDat.GetLan("AdmMenuBase"));
                xml.AppendFormat("<item name=\"{0}\" link=\"?act=basic&amp;mode=par\" icon=\"tool.gif\"/>", _siteDat.GetLan("AdmMenuPar"));
                xml.AppendLine("</parent>");
                i++;
                xml.AppendFormat("<parent name=\"{0}\" id=\"menu_{1}\" rel=\"{1}\">", _siteDat.GetLan("AdmMenuTheme"), i);
                xml.AppendFormat("<item name=\"{0}\" link=\"?act=theme&amp;mode=select\" icon=\"dark.gif\"/>", _siteDat.GetLan("AdmMenuThemeSel"));
                xml.AppendFormat("<item name=\"{0}\" link=\"?act=myTag&amp;mode=post\" icon=\"\"/>", _siteDat.GetLan("AdmMenuAddMT"));
                xml.AppendFormat("<item name=\"{0}\" link=\"?act=myTag&amp;mode=list\" icon=\"\"/>", _siteDat.GetLan("AdmMenuMTMgr"));
                xml.AppendLine("</parent>");
                i++;
                xml.AppendFormat("<parent name=\"{0}\" id=\"menu_{1}\" rel=\"{1}\">", _siteDat.GetLan("AdmMenuDB"), i);
                xml.AppendFormat("<item name=\"{0}\" link=\"?act=db&amp;mode=backup\" icon=\"save.gif\"/>", _siteDat.GetLan("AdmMenuDBBackup"));
                xml.AppendFormat("<item name=\"{0}\" link=\"?act=db&amp;mode=sql\" icon=\"data.gif\"/>", _siteDat.GetLan("AdmMenuDBSQL"));
                xml.AppendLine("</parent>");
                i++;
                xml.AppendFormat("<parent name=\"{0}\" id=\"menu_{1}\" rel=\"{1}\">", _siteDat.GetLan("AdmMenuColumnMgr"), i);
                xml.AppendFormat("<item name=\"{0}\" link=\"?act=column&amp;mode=post\" icon=\"add.gif\"/>", _siteDat.GetLan("AdmMenuColumnAdd"));
                xml.AppendFormat("<item name=\"{0}\" link=\"?act=column&amp;mode=list\" icon=\"dark.gif\"/>", _siteDat.GetLan("AdmMenuColumnList"));
                xml.AppendFormat("<item name=\"{0}\" link=\"?act=tag&amp;mode=list\" icon=\"lab.gif\"/>", _siteDat.GetLan("AdmMenuTagMgr"));
                xml.AppendLine("</parent>");
                i++;
                xml.AppendFormat("<parent name=\"{0}\" id=\"menu_{1}\" rel=\"{1}\">", _siteDat.GetLan("AdmMenuMain"), i);
                xml.AppendFormat("<item name=\"{0}\" link=\"?act=post&amp;mode=post&amp;m=A\" icon=\"add.gif\"/>", _siteDat.GetLan("AdmMenuArtAdd"));
                xml.AppendFormat("<item name=\"{0}\" link=\"?act=post&amp;mode=list&amp;m=A\" icon=\"dark.gif\"/>", _siteDat.GetLan("AdmMenuArtMgr"));
                xml.AppendFormat("<item name=\"{0}\" link=\"?act=comment&amp;mode=list\" icon=\"comment.gif\"/>", _siteDat.GetLan("AdmMenuCMTMgr"));
                xml.AppendLine("</parent>");
                i++;
                xml.AppendFormat("<parent name=\"{0}\" id=\"menu_{1}\" rel=\"{1}\">", _siteDat.GetLan("AdmMenuPG"), i);
                xml.AppendFormat("<item name=\"{0}\" link=\"?act=post&amp;mode=post&amp;m=P\" icon=\"add.gif\"/>", _siteDat.GetLan("AdmMenuPGAdd"));
                xml.AppendFormat("<item name=\"{0}\" link=\"?act=post&amp;mode=list&amp;m=P\" icon=\"dark.gif\"/>", _siteDat.GetLan("AdmMenuPGMgr"));
                xml.AppendLine("</parent>");
                i++;
                xml.AppendFormat("<parent name=\"{0}\" id=\"menu_{1}\" rel=\"{1}\">", _siteDat.GetLan("AdmMenuMgr"), i);
                xml.AppendFormat("<item name=\"{0}\" link=\"?act=user&amp;mode=post\" icon=\"add.gif\"/>", _siteDat.GetLan("AdmMenuMgrAdd"));
                xml.AppendFormat("<item name=\"{0}\" link=\"?act=user&amp;mode=list\" icon=\"user.gif\"/>", _siteDat.GetLan("AdmMenuMgrControl"));
                xml.AppendLine("</parent>");
                i++;
                xml.AppendFormat("<parent name=\"{0}\" id=\"menu_{1}\" rel=\"{1}\">", _siteDat.GetLan("AdmMenuFlw"), i);
                xml.AppendFormat("<item name=\"{0}\" link=\"?act=fellow&amp;mode=post\" icon=\"add.gif\"/>", _siteDat.GetLan("AdmMenuFlwAdd"));
                xml.AppendFormat("<item name=\"{0}\" link=\"?act=fellow&amp;mode=list&amp;home=1\" icon=\"dark.gif\"/>", _siteDat.GetLan("AdmMenuFlwIdx"));
                xml.AppendFormat("<item name=\"{0}\" link=\"?act=fellow&amp;mode=list\" icon=\"delete.gif\"/>", _siteDat.GetLan("AdmMenuFlwMgr"));
                xml.AppendLine("</parent>");
                i++;
                xml.AppendFormat("<parent name=\"{0}\" id=\"menu_{1}\" rel=\"{1}\">", _siteDat.GetLan("AdmMenuLog"), i);
                xml.AppendFormat("<item name=\"{0}\" link=\"?act=info&amp;mode=cache\" icon=\"data.gif\"/>", _siteDat.GetLan("AdmMenuCache"));
                xml.AppendFormat("<item name=\"{0}\" link=\"?act=info&amp;mode=tb\" icon=\"comment.gif\"/>", _siteDat.GetLan("AdmMenuTrackback"));
                xml.AppendFormat("<item name=\"{0}\" link=\"?act=attach&amp;mode=list\" icon=\"attach.gif\"/>", _siteDat.GetLan("AttachList"));
                xml.AppendLine("</parent>");
                //一般扩展
                i++;
                xml.AppendFormat("<parent name=\"{0}\" id=\"menu_{1}\" rel=\"{1}\">", _siteDat.GetLan("AdmMenuExpand"), i);
                foreach (object type in new SiteExpand().GetTypes(typeof(IAdminExpand).FullName))
                {
                    IAdminExpand iae = ((IAdminExpand)type);
                    xml.AppendFormat("<item name=\"{0}\" link=\"?act=expand&amp;key={1}\" icon=\"\"/>", iae.Name, iae.Key);
                }
                //超级扩展
                foreach (string folder in Directory.GetDirectories(Path.Combine(SiteCfg.Router, "Common/Expand/_Admin")))
                {
                    DirectoryInfo dInfo = new DirectoryInfo(folder);
                    string xmlPath = Path.Combine(folder, "Config.xml");
                    if (File.Exists(xmlPath))
                    {
                        XmlDocument cfgXml = new XmlDocument();
                        cfgXml.Load(xmlPath);
                        foreach (XmlNode node in cfgXml.SelectNodes("/root/item"))
                        {
                            if (node.Attributes["menuShow"].Value == "yes")
                            {
                                xml.AppendFormat("<item name=\"{0}\" link=\"?act=extend&amp;folder={1}&amp;key={2}\" icon=\"\"/>", node.Attributes["name"].Value, dInfo.Name, node.Attributes["key"].Value);
                            }
                        }
                    }
                }
                xml.AppendLine("</parent>");
                i++;
                xml.AppendFormat("<parent name=\"{0}\" id=\"menu_{1}\" rel=\"{1}\">", _siteDat.GetLan("AdmMenuUpgrade"), i);
                xml.AppendFormat("<item name=\"{0}\" link=\"?act=upgrade&amp;mode=info\" icon=\"verify.gif\"/>", _siteDat.GetLan("AdmMenuChkUP"));
                xml.AppendLine("</parent>");
            }
            else
            {
                i++;
                xml.AppendFormat("<parent name=\"{0}\" id=\"menu_{1}\" rel=\"{1}\">", _siteDat.GetLan("AdmMenuIdx"), i);
                xml.AppendFormat("<item name=\"{0}\" link=\"?\" icon=\"\"/>", _siteDat.GetLan("AdmMenuWelcome"));
                xml.AppendFormat("<item name=\"{0}\" link=\"Readme.html\" icon=\"\"/>", _siteDat.GetLan("AdmMenuReadme"));
                xml.AppendFormat("<item name=\"{0}\" link=\"{1}page/download.aspx\" icon=\"\"/>", _siteDat.GetLan("AdmMenuUPLog"), SiteCfg.WebSite);
                xml.AppendLine("</parent>");
                i++;
                xml.AppendFormat("<parent name=\"{0}\" id=\"menu_{1}\" rel=\"{1}\">", _siteDat.GetLan("AdmMenuHelpOL"), i);
                xml.AppendFormat("<item name=\"{0}\" link=\"{1}\" icon=\"\"/>", _siteDat.GetLan("AdmMenuHelpCenter"), SiteCfg.WebSite);
                xml.AppendLine("</parent>");
                i++;
                xml.AppendFormat("<parent name=\"{0}\" id=\"menu_{1}\" rel=\"{1}\">", _siteDat.GetLan("AdmMenuOffi"), i);
                xml.AppendFormat("<item name=\"{0}\" link=\"{1}\" icon=\"\"/>", _siteDat.GetLan("AdmMenuOffiSite"), SiteCfg.WebSite);
                xml.AppendFormat("<item name=\"{0}\" link=\"mailto:master@isroc.com\" icon=\"\"/>", _siteDat.GetLan("AdmMenuOffiContact"));
                xml.AppendLine("</parent>");
            }
            xml.AppendLine("</root>");
            return xml.ToString();
        }

        /// <summary>
        /// 显示主要部分的代码
        /// </summary>
        private string getMainCode()
        {
            string sr = string.Empty;
            switch (_fun.Query("act"))
            {
                case "exit":
                    {
                        _ac.Clear();
                        Response.Redirect(Request.FilePath);
                        break;
                    }
                case "basic":
                    {
                        switch (_fun.Query("mode"))
                        {
                            case "par": { sr += new AdminSetting().Parameter(); break; }
                            default: { sr += new AdminSetting().Basic(); break; }
                        }
                        break;
                    }
                case "theme":
                    {
                        switch (_fun.Query("mode"))
                        {
                            default: { sr += new AdminTheme().Select(); break; }
                        }
                        break;
                    }
                case "myTag":
                    {
                        switch (_fun.Query("mode"))
                        {
                            case "post": { sr += new AdminMyTag().Post(); break; }
                            default: { sr += new AdminMyTag().List(); break; }
                        }
                        break;
                    }
                case "db":
                    {
                        switch (_fun.Query("mode"))
                        {
                            case "sql": { sr += new AdminDB().SQL(); break; }
                            default: { sr += new AdminDB().Backup(); break; }
                        }
                        break;
                    }
                case "column":
                    {
                        switch (_fun.Query("mode"))
                        {
                            case "post": { sr += new AdminColumn().Post(); break; }
                            default: { sr += new AdminColumn().List(); break; }
                        }
                        break;
                    }
                case "tag":
                    {
                        switch (_fun.Query("mode"))
                        {
                            default: { sr += new AdminTag().List(); break; }
                        }
                        break;
                    }
                case "post":
                    {
                        string m = _fun.Query("m");
                        switch (_fun.Query("mode"))
                        {
                            case "post": { sr += new AdminPost().Post(m); break; }
                            default: { sr += new AdminPost().List(m); break; }
                        }
                        break;
                    }
                case "comment":
                    {
                        switch (_fun.Query("mode"))
                        {
                            case "post": { sr += new AdminComment().Post(); break; }
                            default: { sr += new AdminComment().List(20); break; }
                        }
                        break;
                    }
                case "fellow":
                    {
                        switch (_fun.Query("mode"))
                        {
                            case "post": { sr += new AdminFellow().Post(); break; }
                            default: { sr += new AdminFellow().List(); break; }
                        }
                        break;
                    }
                case "info":
                    {
                        switch (_fun.Query("mode"))
                        {
                            case "cache": { sr += new AdminCache().List(); break; }
                            case "tb": { sr += new AdminTrackback().List(); break; }
                            default: { sr += new AdminWelcome().Business(); break; }
                        }
                        break;
                    }
                case "user":
                    {
                        switch (_fun.Query("mode"))
                        {
                            case "post": { sr += new AdminUser().Post(); break; }
                            default: { sr += new AdminUser().List(); break; }
                        }
                        break;
                    }
                case "attach":
                    {
                        switch (_fun.Query("mode"))
                        {
                            default: { sr += new AdminAttach().List(); break; }
                        }
                        break;
                    }
                case "expand":
                    {
                        string key = _fun.Query("key");
                        sr += new AdminExpand().OutWrite(key);
                        break;
                    }
                case "upgrade":
                    {
                        switch (_fun.Query("mode"))
                        {
                            case "info": { sr += new AdminUpgrade().OutWrite(); break; }
                        }
                        break;
                    }
                default:
                    {
                        sr += new AdminWelcome().OutCode();
                        break;
                    }
            }
            return sr;
        }
    }
}
