<%@ Control Language="C#" %>
<%@ Import Namespace="Kesion.Publics" %>
<%@ Import Namespace="Kesion.BLL" %>
<%@ Import Namespace="Kesion.Cache" %>
<%@ Import Namespace="Kesion.HtmlTags" %>
<%@ Import Namespace="Kesion.APPCode" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="Kesion.Course" %>
<%@ Import Namespace="Kesion.Components" %>
<script runat="server" type="text/C#">
    dynamic __user = HttpContext.Current.Items["user"];                //初始化用户信息，
    DataRow drr = null;//编辑初始化
    public int CourseID = 0;     //课程id
    public int PeriodID = 0;     //课时id
    public int ParentID = 0;     //父ID信息
    public string action = string.Empty;

    //页面加载事件  初始化获取相关信息
    protected void Page_Load(object sender, EventArgs e)
    {
        CourseID =Utils.StrToInt(KSCMS.S("courseid"));//获取课程id信息
        ParentID = Utils.StrToInt(KSCMS.S("ParentID"));
        PeriodID = Utils.StrToInt(KSCMS.S("periodid"));

        action = KSCMS.S("do");//获取行为操作信息
        switch (action.ToLower())
        {
            case "add":
            case "edit":
                if (KSCMS.S("action").ToString().ToLower() == "save")
                {
                    SaveInfo();//保存信息
                }
                else
                {
                    //初始化信息
                    InitialPeriodInfo();
                }
                break;
            case "moveup"://上移
                PeriodMoveUP();
                break;
            case "movedown"://下移
                PeriodMoveDOWN();
                break;
            case "del"://删除信息
                DelPeriodInfo(KSCMS.S("Ids"));
                break;

        }
    }


    private string GetVal(string fieldName)
    {
        if (drr != null)
        {
            return drr[fieldName].ToString();
        }
        else
        {
            return string.Empty;
        }
    }

    /// <summary>
    /// 初始化课时信息   或者显示添加信息
    /// </summary>
    public void InitialPeriodInfo()
    {
        //getselect(CourseID);
        if (action.ToLower() == "add")
        {
            Dictionary<string, string> PeriodInfo = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            Kesion.Course.Course.InitalCoursePeriodFace(PeriodInfo, 0);   //中转站赋值
            Context.Items["courseperiod"] = PeriodInfo;
            this.PeriodPlace.Controls.Add(base.LoadControl("~/Config/Control/SystemCourse/CoursePeriodFace.ascx"));

        }
        else if (action.ToLower() == "edit")
        {

            Dictionary<string, string> PeriodInfo = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            using (DataTable dt = DataFactory.GetDataTable("select * from KS_CourseFacePeriod where periodid=" + Utils.StrToInt(KSCMS.S("periodid"))))
            {
                if (dt.Rows.Count > 0)
                {
                    DataRow dr = dt.Rows[0];
                    Kesion.Course.Course.InitalCoursePeriodFace(PeriodInfo, 1, dr);//中转站赋值
                    ParentID = Utils.StrToInt(dr["parentid"].ToString());
                }
            }
            Context.Items["courseperiod"] = PeriodInfo;
            this.PeriodPlace.Controls.Add(base.LoadControl("~/Config/Control/SystemCourse/CoursePeriodFace.ascx"));

        }
    }

    /// <summary>
    /// 初始化章节时
    /// </summary>
    /// <param name="courseid">课程信息</param>
    private string  getselect(int courseid,int parentid)
    {
        string info = "";
        if (courseid != 0)
        {
            using (DataTable dt = DataFactory.GetDataTable("select PeriodName, periodid from KS_CourseFacePeriod where parentid=0 and addtype!=2 and courseid=" + courseid + ""))
            {
                if (dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        info += "<option value='" + dr["periodID"].ToString() + "' " + (Utils.StrToInt(dr["periodID"].ToString()) == parentid ? " selected='selected'" : "") + "  >" + dr["PeriodName"].ToString() + "</option>";
                    }
                }
            }
        }
        return info;
    }

    /// <summary>
    /// 信息保存操作
    /// </summary>
    public void SaveInfo()
    {
        Hashtable ht = new Hashtable();
        ht.Add("PeriodName", KSCMS.S("TxtName"));//标题的名称
        ht.Add("Intro", Utils.ChkSQL(KSCMS.S("Intro")));//课时简介
        ht.Add("tcname", KSCMS.S("tcname"));//教师名称
        ht.Add("tcid", 0);//教师id
        ht.Add("StartTime", Utils.StrToDateTime(KSCMS.S("StartTime")).ToString("yyyy-MM-dd"));//开始时间
        ht.Add("EndTime", Utils.StrToDateTime(KSCMS.S("EndTime")).ToString("yyyy-MM-dd"));//结束时间
        ht.Add("IsFree", Utils.StrToInt(KSCMS.S("IsFree")));//是否收费
        ht.Add("Money", KSCMS.S("Money"));//价格
        ht.Add("Score", KSCMS.S("Score"));//积分
        ht.Add("Addtype", 2);//时
        ht.Add("parentid",Utils.StrToInt(KSCMS.S("DrpChatpter")));//父ID
                                                                  //新增
        if (Utils.StrToInt(KSCMS.S("status")) == 0)
        {
            ht.Add("CourseID", CourseID);//课程id
            ht.Add("username", "admin");
            ht.Add("userid", "0");
            ht.Add("adddate", DateTime.Now.ToString("yyyy-MM-dd"));
            CommonData.Insert("KS_CourseFacePeriod", ht);
            
            Kesion.APPCode.Public.CountInfo(CourseID, "faceCountPid");

            Msg.Alert("添加课时成功！", BasicField.GetUserUrl("teacher/faceperiods","CourseId-" + CourseID) );
        }
        else
        {//修改

            CommonData.Update("KS_CourseFacePeriod", ht, " where PeriodID=" + Utils.StrToInt(KSCMS.S("status")));
            Msg.Alert("修改课时成功！", BasicField.GetUserUrl("teacher/faceperiods","CourseId-" + CourseID) );
        }
    }


    #region       对课时的操作信息

    /// <summary>
    /// 上移
    /// </summary>
    private void PeriodMoveUP()
    {
        using (DataTable dt = DataFactory.GetDataTable("select top 1 CourseID,PeriodID,orderid  from KS_CourseFacePeriod  Where  parentid=" + ParentID + " and PeriodID =" + PeriodID ))
        {
            if (dt.Rows.Count > 0)
            {
                DataRow dr = dt.Rows[0];
                int minorderid = Utils.StrToInt(DataFactory.GetOnlyValue("select top 1 min(orderid) from KS_CourseFacePeriod Where  parentid=" + ParentID + " and CourseID=" + dr["courseid"].ToString()));
                int proid = Utils.StrToInt(DataFactory.GetOnlyValue("select top 1 PeriodID from KS_CourseFacePeriod Where CourseID=" + dr["courseid"].ToString() + "and  parentid=" + ParentID + " and  orderid<" + dr["orderid"].ToString() + " order by orderid desc"));
                DataFactory.ExecuteNonQuery("update KS_CourseFacePeriod set orderid=orderid+1 where parentid=" + ParentID + " and  PeriodID=" + proid);

                DataFactory.ExecuteNonQuery("update KS_CourseFacePeriod set orderid=orderid-1 where  parentid=" + ParentID + " and PeriodID=" + PeriodID + " and orderid>" + minorderid + "");
            }
        }
        Msg.Alert("恭喜，上移成功"  );

    }

    /// <summary>
    /// 下移
    /// </summary>
    private void PeriodMoveDOWN()
    {
        using (DataTable dt = DataFactory.GetDataTable("select top 1 CourseID,PeriodID,orderid  from KS_CourseFacePeriod Where  parentid=" + ParentID + " and PeriodID =" + PeriodID))
        {
            if (dt.Rows.Count > 0)
            {
                DataRow dr = dt.Rows[0];
                int maxorderid = Utils.StrToInt(DataFactory.GetOnlyValue("select top 1 max(orderid) from KS_CourseFacePeriod Where  parentid=" + ParentID + " and CourseID=" + dr["courseid"].ToString()));
                int proid = Utils.StrToInt(DataFactory.GetOnlyValue("select top 1 PeriodID from KS_CourseFacePeriod Where  parentid=" + ParentID + " and CourseID=" + dr["courseid"].ToString() + "and  orderid>" + dr["orderid"].ToString() + " order by orderid asc"));
                DataFactory.ExecuteNonQuery("update KS_CourseFacePeriod set orderid=orderid+1 where  parentid=" + ParentID + " and orderid<" + maxorderid + " and  PeriodID=" + PeriodID);

                DataFactory.ExecuteNonQuery("update KS_CourseFacePeriod set orderid=orderid-1 where  parentid=" + ParentID + " and PeriodID=" + proid + " and orderid<>1");
            }
        }
        Msg.Alert("恭喜，下移成功"  );

    }

    #endregion
    
        /// <summary>
        /// 删除面授课时信息 
        /// </summary>
        /// <param name="Ids">被删除的课时集合</param>
        public void DelPeriodInfo(string Ids)
        {
            if (Ids != "0")
            {
                using (DataTable dt = DataFactory.GetDataTable("select * from  KS_CourseFacePeriod where Periodid in (" + Utils.FilterIDs(Ids) + ")"))
                {
                    if (dt.Rows.Count > 0)
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            if (Utils.StrToInt(dr["addtype"].ToString()) !=2) //章
                            {
                                DelPeriodFromParentID(Utils.StrToInt(dr["PeriodID"].ToString()));//删除章节下面的  节   与课时信息
                            }
                            //删除当前课时   章   节    的信息  
                            DataFactory.ExecuteNonQuery("delete from KS_CourseFacePeriod where Periodid=" + Utils.StrToInt(dr["PeriodID"].ToString()));
                        }
                        //在更新课程的课时数量信息

                       Msg.Alert("数据删除成功！",KSCMS.GetComeUrl());
                    }
                }
            }
            else {
                Msg.Alert("参数传递错误！请检查您的操作！",KSCMS.GetComeUrl());
            }
        }


        /// <summary>
        /// 根据父ID进行删除子项内容
        /// </summary>
        /// <param name="ParentID">父ID</param>
        public void DelPeriodFromParentID(int ParentID)
        {
            if (ParentID > 0)
            {
                using (DataTable dt = DataFactory.GetDataTable("select * from KS_CourseFacePeriod where parentid=" + ParentID))
                {
                    if (dt.Rows.Count > 0)
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            if (Utils.StrToInt(dr["addtype"].ToString()) == 1) //节
                            {
                                //删除该节下面的课时信息
                                DataFactory.ExecuteNonQuery("delete from KS_CourseFacePeriod where parentid=" + Utils.StrToInt(dr["PeriodID"].ToString()));
                            }
                            //删除当前课时  或者当前节点信息
                            DataFactory.ExecuteNonQuery("delete from KS_CourseFacePeriod where Periodid=" + Utils.StrToInt(dr["PeriodID"].ToString()));
                        }
                    }
                }
            }
        }

</script>

<div class="t_tybox">
    
<%if (KSCMS.S("do") != "add" && KSCMS.S("do") != "edit")
    { %>
    <div class="tytitle"><h4>课时管理</h4>
		<a onclick="add( <%=CourseID %>,1,0)"  href="javascript:void(0);" class="addbtn" ><b></b>添加章</a>
		<a onclick="add(<%=CourseID %>,2,0)"  href="javascript:void(0);" class="addbtn"><b></b>添加节</a>
		<a href="<%=BasicField.GetUserUrl("teacher/faceperiods", "do-add,parentid-0,courseid-"+CourseID) %>" class="addbtn"><b></b>添加课时</a>
	<a href="<%=BasicField.GetUserUrl("teacher/courselist") %>" class="addbtn">返回</a>
   	</div>
    <div class="clear blank20"></div>  
    <div class="part_now">当前课程： </div>
    <div class="clear blank10"></div> 
     
    <div class="courseKeshi">
        	<div class="lineY"></div>
            <ul id="myloop">
            
        	</ul>
        </div>
    <%}
    else
    { %>
    <form name="aspnetForm" method="post" action="<%=BasicField.GetUserUrl("teacher/FacePeriods","do-"+KSCMS.S("do"))%>" id="aspnetForm">
        <input type="hidden" name="action" value="save" />
        <div class="t_tybox">
	 		<div class="ty_title">添加课时</div>     
         	<table width="100%" border="0" cellpadding="0" cellspacing="0" class="border"> 
                <tr>
                    <td class="lefttd" height="30" align="right"><strong>所属章节</strong></td>
                    <td class="tag_left">
                        <select name="DrpChatpter" id="DrpChatpter" class="textbox">
                            <option value="0"  <%=ParentID %> >--请选择章节信息--</option>
                            <%=getselect(CourseID,ParentID) %>
                        </select> 
                    </td>
                </tr>
                <asp:PlaceHolder ID="PeriodPlace" runat="server"></asp:PlaceHolder>
            </table>
		  	<input type="hidden" value="<%=CourseID %>" name="courseid" /> 
            <div class="clear blank10"></div>
            <div class="cz_btn nofloat" style="padding-left:195px">
                <span><input type="submit" name="Button2" value="确定保存" onclick="return (CheckForm());" id="Button2" class="button" /></span>
                <span><input type="button" class="button" onclick="window.history.go(-1);"value=" 返 回 "></span>
            </div>
            <div class="clear blank20"></div>
        </div>
    </form>

    <%} %>
</div>
<script>
    $(document).ready(function () {
        getmyPeriod();
    });

    function getmyPeriod() {
        $.ajax({
            type: 'post',
            dateType: 'json',
            url: "/plus/course/CourseAjax.ashx?action=getfaceperiod&about=top&intendant=true",
            data: { courseID: <%=CourseID %>},
            success: function (msg) { 
                        var info = JSON.parse(msg);
                        if (info.status == "success") {
                            var length = info.data.length;
                            for (var i = 0; i < length; i++) {
                                var period = info.data[i];
                                if (period.AddType == 0) {//章
								var infocontent = "<li class='chapter'><div class='menubtn'></div>" + period.periodname;
                                    infocontent += "<div class='rButton'><a href='javascript:;' onclick='edit(<%=CourseID %>," + period.periodid + ",1," + period.ParentID + ")' class='icon icon-edit' ><span>编辑</span></a>";
                                    infocontent += "<div class='addButton'><div class='icon icon-add'><span>添加</span></div><div class='box'><a href='javascript:;' onclick='add(<%=CourseID %>,2," + period.periodid + ")' >添加节</a>";
                                    infocontent += "<a href='" + period.addperiodurl + "' >添加课时</a></div></div>"; 
									infocontent += "<a href='" + period.delurl + "' onclick='return confirm(确定要删除信息么！);' class='icon icon-delete' ><span>删除</span></a></div>";
                                	infocontent += "</li>";
									
                                } else if (period.AddType == 1) {//节
								var infocontent = "<div class='box'><li class='section'><div class='menubtn'></div>" + period.periodname;
                                    infocontent += "<div class='rButton'><a href='javascript:;' onclick='edit(<%=CourseID %>," + period.periodid + ",2," + period.ParentID + ")'  class='icon icon-edit'><span>编辑</span></a>";
                                    infocontent += "<div class='addButton'><div class='icon icon-add'><span>添加</span></div><div class='box'><a href='" + period.addperiodurl + "' ><span>添加课时</span></a></div></div>"; 
									infocontent += "<a href='" + period.delurl + "' onclick='return confirm(确定要删除信息么！);' class='icon icon-delete' ><span>删除</span></a></div>";
                                	infocontent += "</li>";
									
                                } else {//时
								var infocontent = "<div class='box'><li class='keshi'><img src='../../admin/images/ks-img0.png'>" + period.periodname;
                                    infocontent += "<div class='rButton'><a href='" + period.editurl + "'  class='icon icon-edit'><span>编辑</span></a>";
                                    infocontent += "<input type='button' onclick='moveup(" + period.periodid + "," + period.ParentID +")' value='上移'>";
                                    infocontent += "<input type='button' onclick='movedown(" + period.periodid + "," + period.ParentID+")' value='下移'>";
									infocontent += "<a href='" + period.delurl + "' onclick='return confirm(确定要删除信息么！);' class='icon icon-delete' ><span>删除</span></a></div>";
                                	infocontent += "</li></div></div>";
                                }
                                $("#myloop").append(infocontent);
                            }
                        }


						var num = $("#myloop li").length;
	    				if (num == 0) {
	    					$("#myloop").prev(".lineY").hide();
	    					$("#myloop").html('<div class="empty">您还未添加任何课时</div>')
	    				};

	    				$("#myloop li").hover(function () {
	    					$(this).find(".rButton").show();
	    				}, function () {
	    					$(this).find(".rButton").hide();
	    				});

	    				$(".addButton").click(function () {
	    					$(this).toggleClass("addOn");
	    				});

	    				$(".rButton .icon").hover(function () {
	    					$(this).find("span").show();
	    				}, function () {
	    					$(this).find("span").hide();
	    				});
	    				$(".rButton").click(function () {
	    					doNone(click());
	    				});

	    				//展开收缩
	    				click();
	    				function click() {
	    					$(".chapter,.section").click(function () {
	    						$(this).find(".menubtn").toggleClass("menubtn2");
	    						$(this).next(".box").stop().slideToggle(300);
	    					});
	    				};
	    				//是否添加按钮
	    				$(".menubtn").each(function () {
	    					var num = $(this).parent().next(".box").length;
	    					if (num == 0) {
	    						$(this).hide();
	    					};
	    				});
	    				$(".chapterBox").each(function () {
	    					var i = $(this).index() + 1;
	    					if (i > 10) {
	    						$(this).find(".chapter .menubtn").addClass("menubtn2");
	    						$(this).find(".chapter").siblings(".box").hide();
	    					};
	    				});
                    }
        });
    }

    function add(id, type, parentid) {
        openWin('添加章节', '/plus/course/AddCoursePeriod.aspx?action=faceadd&about=top&type=' + type + '&parentid=' + parentid + '&Courseid=' + id, true, 600, 400);
    }
    function edit(id, Periodid, type, parentid) {
        openWin('修改章节', '/plus/course/AddCoursePeriod.aspx?action=faceedit&about=top&type=' + type + '&Courseid=' + id + '&parentid=' + parentid + '&Periodid=' + Periodid, true, 600, 400);
    }
    function moveup(id, parentid) {
        location.href = '<%= BasicField.GetUserUrl("teacher/faceperiods","do-moveup,CourseId-"+CourseID)%>,Periodid-' + id + ",parentid-" + parentid;
    }
    function movedown(id, parentid) {
        location.href = '<%= BasicField.GetUserUrl("teacher/faceperiods","do-movedown,CourseId-"+CourseID)%>,Periodid-' + id + ",parentid-" + parentid;
    }

    //弹窗的方法
    var box = '';
    function openWin(title, url, isreload, width, height) {
        if (width == null) width = 760;
        if (height == null) height = 450;
        box = $.dialog.open(url, {
            id: 'topbox', lock: true, title: title, width: width, height: height, close: function () {
            }
        });
    }
</script>
