using System;
using System.Linq;
using System.Web;
using Whir.Domain;
using Whir.ezEIP.Web;
using Whir.Framework;
using Whir.Service;

public partial class whir_system_Handler_Developer_Menu : SysHandlerPageBase
{
    SysManagePageBase SysManagePageBase = new SysManagePageBase();

    protected void Page_Load(object sender, EventArgs e)
    {
        var action = RequestUtil.Instance.GetFormString("_action");
        Exec(this, action);
    }

    /// <summary>
    /// 保存数据
    /// </summary>
    /// <returns></returns>
    public HandlerResult Save()
    {
        int menuId = RequestUtil.Instance.GetFormString("MenuId").ToInt();

        //反射获取表单字段数据
        var type = typeof(Menu);
        var menu = ServiceFactory.MenuService.SingleOrDefault<Menu>(menuId) ?? ModelFactory<Menu>.Insten();
        menu = GetPostObject(type, menu) as Menu;

        ServiceFactory.MenuService.Save(menu);
        return new HandlerResult { Status = true, Message = "保存成功" };
    }

    /// <summary>
    /// 删除数据
    /// </summary>
    /// <returns></returns>
    public HandlerResult Del()
    {
        int menuId = RequestUtil.Instance.GetFormString("MenuId").ToInt();
        var menu = ServiceFactory.MenuService.SingleOrDefault<Menu>(menuId);
        if (menu == null)
            return new HandlerResult { Status = false, Message = "要删除的菜单数据不存在" };

        var subMenus = ServiceFactory.MenuService.Query<Menu>("WHERE ParentId=@0", menuId).ToList();
        if (subMenus.Any())
            return new HandlerResult { Status = false, Message = "不可删除含有下级的菜单" };

        ServiceFactory.MenuService.Delete(menu);
        return new HandlerResult { Status = true, Message = "删除成功" };
    }


    /// <summary>
    /// 获取栏目菜单
    /// </summary>
    /// <returns></returns>
    public HandlerResult GetColumnMenu()
    {
        var siteId = RequestUtil.Instance.GetFormString("siteId").ToInt(0);
        var subjectTypeId = RequestUtil.Instance.GetFormString("subjecttypeid").ToInt(0);//子站为1，专题为2，否则为0，默认为栏目内容管理
        string html = "";
        string sessionName = "";
        string refreshName = "";
        try
        {
            switch (subjectTypeId)
            {
                case 0://内容管理
                    {
                        sessionName = "columnSessionHtml";
                        refreshName = "column_refresh_flag";
                        html = Session[sessionName] == null ? "" : Session[sessionName].ToStr();
                        if (html == "" || CookieUtil.Instance.GetCookieValue(refreshName, "0") != "")
                        {
                            html = "<ul  class=\"topnav menu-left-nest\">";
                            html += "<li><a style=\"border-left: 0px solid!important;\" class=\"title-menu-left\">";
                            html += "<span>内容管理</span><button  onclick=\"colseMenu();\" data-dismiss=\"alert\" class=\"close\" type=\"button\">×</button></a></li>";
                            html += GetMenuHtml(0, siteId, 0, 0, 1);
                            html += " </ul>";
                        }
                    }
                    break;
                case 1://子站
                    {
                        sessionName = "subSiteSessionHtml";
                        refreshName = "subsite_refresh_flag";
                        html = Session[sessionName] == null ? "" : Session[sessionName].ToStr();
                        if (html == "" || CookieUtil.Instance.GetCookieValue(refreshName, "0") != "")
                        {
                            html = "<ul  class=\"topnav menu-left-nest\">";
                            html += "<li><a  style=\"border-left: 0px solid!important;\" class=\"title-menu-left\">";
                            html += "<span>子站管理</span><button  onclick=\"colseMenu();\" data-dismiss=\"alert\" class=\"close\" type=\"button\">×</button></a></li>";
                            html += GetSubSiteMenuHtml(siteId);
                            html += " </ul>";
                        }
                    }
                    break;
                case 2://专题
                    {
                        sessionName = "subjectSessionHtml";
                        refreshName = "subject_refresh_flag";
                        html = Session[sessionName] == null ? "" : Session[sessionName].ToStr();
                        if (html == "" || CookieUtil.Instance.GetCookieValue(refreshName, "0") != "")
                        {
                            html = "<ul  class=\"topnav menu-left-nest\">";
                            html += "<li><a  style=\"border-left: 0px solid!important;\" class=\"title-menu-left\">";
                            html += "<span>专题管理</span><button  onclick=\"colseMenu();\" data-dismiss=\"alert\" class=\"close\" type=\"button\">×</button></a></li>";
                            html += GetSubjectMenuHtml(siteId);
                            html += " </ul>";
                        }
                    }
                    break;
            }
            CookieUtil.Instance.RemoveCookie(refreshName);
            Session[sessionName] = html;
            return new HandlerResult
            {
                Status = true,
                Message = html
            };
        }
        catch (Exception)
        {
            return new HandlerResult
            {
                Status = false,
                Message = "获取数据失败！"
            };
        }
    }


    ///<summary>
    /// 递归获取菜单 内容管理
    /// </summary>
    /// <param name="columnId">栏目id</param>
    /// <param name="siteId"></param>
    /// <param name="siteType"></param>
    /// <param name="depth"></param>
    /// <returns></returns>
    protected string GetMenuHtml(int parentId, int siteId, int siteType, int subjectId, int depth)
    {
        string html = "";
        string temp = "";
        //子菜单按钮：查看前台1、发布2、基本信息3、高级设置4、seo设置5、栏目设置6、表单管理7
        string subMenuButton = "";
        var list = ServiceFactory.ColumnService.Query<Column>("WHERE IsDel=0 AND ParentId=@0 AND SiteId=@1 AND SiteType=@2 AND (MarkType='' OR MarkType IS NULL) ORDER BY Sort ASC", parentId, siteId, siteType).ToList();

        foreach (var column in list)
        {
            if (!SysManagePageBase.IsRoleHaveColumnRes("查看", column.ColumnId, subjectId == 0 ? -1 : subjectId)) continue; //没有查看栏目权限

            string herf = (SysPath + "ModuleMark/Common/Redirect.aspx?columnid={0}{1}&time=" + Rand.Instance.Number(7))
                                        .FormatWith(column.ColumnId, subjectId == 0 ? "" : "&subjectid=" + subjectId);//判断是否子站下的栏目，是就加上子站id


            if (column.ModelId != 0)
                subMenuButton += "1,2,";
            if (!column.OutUrl.IsEmpty())
                subMenuButton += "6,";
            if (SysManagePageBase.IsDevUser)
            {
                if (column.ModelId != 0)
                    subMenuButton += "2,3,4,5,7";
                else
                    subMenuButton += "2,3,4,5";
            }
            else
            {
                if (SysManagePageBase.IsRoleHaveColumnRes("栏目修改", column.ColumnId, -1))
                    subMenuButton += "3,";

                if (SysManagePageBase.IsRoleHaveColumnRes("SEO设置", column.ColumnId, -1))
                    subMenuButton += "5,";
            }
            if (!column.OutUrl.IsEmpty())
            {
                herf = column.OutUrl; //如果是外链
                subMenuButton = "6";
            }

            temp = GetMenuHtml(column.ColumnId, siteId, siteType, subjectId, depth + 1);
            string columnName = subjectId > 0 ? ServiceFactory.SubjectColumnService.GetColumnName(column.ColumnId, subjectId) : column.ColumnName;
            columnName = columnName.IsEmpty() ? column.ColumnName : columnName;
            string name = columnName.Length > 10 ? columnName.Substring(0, 7) + "..." : columnName;
            if (temp != "")  //有子栏目
            {
                html += "<li><a id=\"column{2}-{3}\" class=\"tooltip-tip{0} ajax-load tooltipster-disable\" href=\"{1}\"".FormatWith(depth == 1 ? "" : depth.ToStr(), "javascript:void();", column.ColumnId, subjectId);
                html += "title=\"{2}\"><span>{0}{1}</span>".FormatWith(name, SysManagePageBase.IsDevUser ? "[" + column.ColumnId + "]" : "", columnName);
                html += "<span class=\"caret\" style=\"border-width:7px !important;\"  buttonIds=\"{0}\" columnId=\"{1}\" subjectId=\"{2}\" classId=\"{3}\" style=\"cursor:pointer;\"></span></a>"
                    .FormatWith(subMenuButton, column.ColumnId, subjectId, siteType);
                html += "<ul>";
                html += temp;
                html += "</ul></li>";
            }
            else
            {
                html += "<li><a class=\"tooltip-tip{0} ajax-load tooltipster-disable\" href=\"javascript:void();\" onclick=\"javascript:window.location.href='{1}'\"".FormatWith(depth == 1 ? "" : depth.ToStr(), herf);
                html += "title=\"{2}\"><span>{0}{1}</span>".FormatWith(name, SysManagePageBase.IsDevUser ? "[" + column.ColumnId + "]" : "", columnName);
                html += "<span class=\"caret\" style=\"border-width:7px !important;\"   buttonIds=\"{0}\" columnId=\"{1}\" subjectId=\"{2}\" classId=\"{3}\"  style=\"cursor:pointer;\"></span></a>"
                    .FormatWith(subMenuButton, column.ColumnId, subjectId, siteType);
                html += "</li>";
            }
            subMenuButton = "";
        }

        return html;
    }

    ///<summary>
    /// 递归获取菜单 子站
    /// </summary>
    /// <param name="columnId"></param>
    /// <param name="siteId"></param>
    /// <param name="siteType"></param>
    /// <param name="depth"></param>
    /// <returns></returns>
    protected string GetSubSiteMenuHtml(int siteId)
    {
        string html = "";
        var listSubjectClass = ServiceFactory.SubjectClassService.GetSubsiteClassList(siteId).ToList();

        foreach (SubjectClass sc in listSubjectClass)
        {
            var subjectList = ServiceFactory.SubjectService.GetListBySubjectClassID(sc.SubjectClassId);
            if (subjectList.Count > 0)
            {
                html += "<li><a id=\"class{2}\"  class=\"tooltip-tip{0} ajax-load tooltipster-disable\" href=\"{1}\"".FormatWith("", "javascript:void()", sc.SubjectClassId);
                html += "title=\"{0}\"><span>{0}</span></a>".FormatWith(sc.SubjectClassName);
                html += "<ul>";

                foreach (var subject in subjectList)
                {
                    if (!SysManagePageBase.IsRoleHaveColumnRes("查看", subject.SubjectId, 0)) continue; //没有查看栏目权限

                    var listColumn = ServiceFactory.ColumnService.Query<Column>("WHERE IsDel=0 AND ParentId=@0 AND SiteId=@1 AND SiteType=@2 AND (MarkType='' OR MarkType IS NULL) ORDER BY Sort ASC", 0, siteId, sc.SubjectClassId).ToList();
                    string name = subject.SubjectName.Length > 10 ? subject.SubjectName.Substring(0, 7) + "..." : subject.SubjectName;
                    if (listColumn.Count > 0)
                    {

                        html += "<li><a  id=\"subsite{2}\"  class=\"tooltip-tip{0} ajax-load tooltipster-disable\" href=\"{1}\"".FormatWith(2, "javascript:void()", subject.SubjectId); //三级菜单
                        html += "title=\"{2}\"><span>{0}{1}</span>".FormatWith(name, SysManagePageBase.IsDevUser ? "[" + subject.SubjectId + "]" : "", subject.SubjectName);
                        html += "<span class=\"caret\" style=\"border-width:7px !important;\"  buttonIds=\"{0}\" columnId=\"{1}\" subjectId=\"{2}\" classId=\"{3}\" style=\"cursor:pointer;\"></span></a>"
                                        .FormatWith('2', subject.SubjectId * -1, subject.SubjectId, sc.SubjectClassId);
                        html += "<ul>";
                        html += GetMenuHtml(0, siteId, sc.SubjectClassId, subject.SubjectId, 3); //递归子站栏目 下的子栏目
                        html += "</ul></li>";
                    }
                    else
                    {
                        name = sc.SubjectClassName.Length > 10 ? sc.SubjectClassName.Substring(0, 7) + "..." : sc.SubjectClassName;
                        html += "<li><a class=\"tooltip-tip{0} ajax-load tooltipster-disable\" href=\"{1}\"".FormatWith(2, "javascript:void()");
                        html += "title=\"{0}\"><span>{1}</span></a>".FormatWith(sc.SubjectClassName, name);

                    }
                }
                html += "</ul></li>";
            }
            else
            {
                html += "<li><a class=\"tooltip-tip{0} ajax-load tooltipster-disable\" href=\"{1}\"".FormatWith("", "javascript:void()");
                html += "title=\"{0}\"><span>{0}</span></a></li>".FormatWith(sc.SubjectClassName);

            }
        }
        return html;
    }

    ///<summary>
    /// 递归获取菜单 专题
    /// </summary>
    /// <param name="columnId"></param>
    /// <param name="siteId"></param>
    /// <param name="siteType"></param>
    /// <param name="depth"></param>
    /// <returns></returns>
    protected string GetSubjectMenuHtml(int siteId)
    {
        string html = "";
        var listSubjectClass = ServiceFactory.SubjectClassService.GetSubjectClassList(siteId).ToList();
        foreach (SubjectClass sc in listSubjectClass)
        {
            var subjectList = ServiceFactory.SubjectService.GetListBySubjectClassID(sc.SubjectClassId);
            if (subjectList.Count > 0)
            {
                html += "<li><a id=\"class{2}\" class=\"tooltip-tip{0} ajax-load tooltipster-disable\" href=\"{1}\"".FormatWith("", "javascript:void()", sc.SubjectClassId);
                html += "title=\"{0}\"><span>{0}</span></a>".FormatWith(sc.SubjectClassName);
                html += "<ul>";

                foreach (var subject in subjectList)
                {
                    if (!SysManagePageBase.IsRoleHaveColumnRes("查看", subject.SubjectId, 0)) continue; //没有查看栏目权限

                    var listColumn = ServiceFactory.ColumnService.Query<Column>("WHERE IsDel=0 AND ParentId=@0 AND SiteId=@1 AND SiteType=@2 AND (MarkType='' OR MarkType IS NULL) ORDER BY Sort ASC", 0, siteId, sc.SubjectClassId).ToList();
                    if (listColumn.Count > 0)
                    {

                        html += "<li><a   id=\"subject{2}\" class=\"tooltip-tip{0} ajax-load tooltipster-disable\" href=\"{1}\"".FormatWith(2, "javascript:void()", subject.SubjectId); //三级菜单
                        html += "title=\"{0}\"><span>{0}{1}</span>".FormatWith(subject.SubjectName, SysManagePageBase.IsDevUser ? "[" + subject.SubjectId + "]" : "");
                        html += "<span class=\"caret\" style=\"border-width:7px !important;\"  buttonIds=\"{0}\" columnId=\"{1}\" subjectId=\"{2}\" classId=\"{3}\" style=\"cursor:pointer;\"></span></a>"
                                    .FormatWith('2', subject.SubjectId * -1, subject.SubjectId, sc.SubjectClassId);
                        html += "<ul>";
                        html += GetMenuHtml(0, siteId, sc.SubjectClassId, subject.SubjectId, 3); //递归子站栏目 下的子栏目
                        html += "</ul></li>";
                    }
                    else
                    {
                        html += "<li><a class=\"tooltip-tip{0} ajax-load tooltipster-disable\" href=\"{1}\"".FormatWith(2, "javascript:void()");
                        html += "title=\"{0}\"><span>{0}</span></a>".FormatWith(sc.SubjectClassName);

                    }
                }
                html += "</ul></li>";
            }
            else
            {
                html += "<li><a class=\"tooltip-tip{0} ajax-load tooltipster-disable\" href=\"{1}\"".FormatWith("", "javascript:void()");
                html += "title=\"{0}\"><span>{0}</span></a></li>".FormatWith(sc.SubjectClassName);

            }
        }
        return html;
    }
}