<%@ 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" %>
<script runat="server" type="text/C#">
    dynamic __user = HttpContext.Current.Items["user"];                //初始化用户信息，
    private static dynamic __info = new System.Dynamic.ExpandoObject();   //初始化当前页信息
    bool isLoadPage = true;  //定义页面是否加载
    public string TableName = "KS_CosPeriod";
    public int costype = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
      
        __info.CourseId = Utils.StrToInt(KSCMS.S("CourseId"));
        __info.parentid = Utils.StrToInt(KSCMS.S("parentid"), 0);
        __info.PeriodId = Utils.StrToInt(KSCMS.S("Periodid"), 0);
        __info.MyItem = KSCMS.S("MyItem");
        __info.CourseName = DataFactory.GetOnlyValue("select top 1 name from KS_Course where courseid=" + __info.CourseId);
        __info.Jname = KSCMS.S("Jname");
        __info.Zname = KSCMS.S("Zname");
        __info.type =Utils.StrToInt(KSCMS.S("type")).ToString();
        costype = Utils.StrToInt(KSCMS.S("costype"));
        if ( costype == 2)
        {
            TableName = "KS_CosGroupPeriod";
        }

        string DoMethod = KSCMS.S("do");

        switch (DoMethod)
        {
            case "edit":
                string name = DataFactory.GetOnlyValue("select top 1 PeriodName from "+TableName+" where periodid=" + __info.PeriodId + "");
                if (KSCMS.S("type") == "2")
                {
                    __info.Jname = name;
                }
                else
                {
                    __info.Zname = name;
                }
                break;
        }
        if (KSCMS.S("action").Equals("save"))
        {
            Utils.TipsDisabled();  //检查是否演示状态
            SaveButton();
        }
        getselect(__info.CourseId);
    }
    protected void SaveButton()
    {

        __info.CourseId =Utils.StrToInt(KSCMS.S("courseid"));
        __info.parentid = Utils.StrToInt(__info.MyItem);
        if (KSCMS.S("do") == "add")
        {
            Hashtable ht = new Hashtable();
            if (KSCMS.S("type") == "2")//节
            {
                if (string.IsNullOrEmpty(__info.Jname))
                {
                    Msg.Alert("请输入节名称!");
                    isLoadPage = false;
                    return;
                }
                if (__info.parentid.ToString() == "0")
                {
                    ht.Add("Depth", 1);
                }
                else
                {
                    ht.Add("Depth", 2);
                }
                ht.Add("PeriodName", __info.Jname);
                ht.Add("Addtype", 2);
            }
            else//章
            {
                if (string.IsNullOrEmpty( __info.Zname))
                {
                    Msg.AlertDoFun("请输入章名称!", "top.location.reload();");
                    isLoadPage = false;
                    return;
                }
                //if (DataFactory.Exists(""+TableName+"", "parentid=0 and courseid=" + CourseId + " and PeriodName='" + this.Zname.Text + "'"))
                //{
                //    JS.Alert("章节名称已存在");
                //    return;
                //}
                ht.Add("Depth", 1);
                ht.Add("PeriodName",  __info.Zname);
                ht.Add("Addtype", 0);
            }
            int orderid = 0;
            if (__info.parentid == 0)
            {
                orderid = Utils.StrToInt(DataFactory.GetOnlyValue("select max(orderid) from "+TableName+" where courseid=" + __info.CourseId));//章级的orderid，直接排序
            }
            else
            {
                orderid = Utils.StrToInt(DataFactory.GetOnlyValue("select max(orderid) from "+TableName+" where parentidpath like '%" + __info.parentid + ",%' and courseid=" + __info.CourseId));//节级，存在没有orderid的情况

                if (orderid == 0)
                {
                    orderid = Utils.StrToInt(DataFactory.GetOnlyValue("select top 1 orderid from "+TableName+" where periodid=" + __info.parentid + " and courseid=" + __info.CourseId));//没有orderid，查出父orderid
                }
                //   KSCMS.Die(orderid);
            }
            DataFactory.ExecuteNonQuery("update "+TableName+" set orderid=orderid+1 where orderid>" + orderid + " and courseid=" + __info.CourseId + "");
            ht.Add("orderid", orderid + 1);
            ht.Add("courseid", __info.CourseId);
            ht.Add("parentid", __info.parentid);
            int Root = 0;
            string TRoot = DataFactory.GetOnlyValue("select Max(root) from "+TableName+"");
            if (TRoot.Equals("0"))
            {
                Root = 1;
            }
            else
            {
                Root = Utils.StrToInt(TRoot) + 1;
            }

            ht.Add("Root", Root);
            ht.Add("AddDate", DateTime.Now);
            ht.Add("UserName", new TemporaryVar().UserName);
            ht.Add("IsFree", 1);//是否免费
            ht.Add("timeCount", 0);//课时总时长
            CommonData.Insert(""+TableName+"", ht);

            int newPid = CommonData.GetMaxId(""+TableName+"", "periodid");
            string parentidpath = newPid.ToString();

            if (__info.parentid != 0)
            {
                string bigparent = DataFactory.GetOnlyValue("select top 1 parentidpath from "+TableName+" where courseid=" + __info.CourseId + " and periodid=" + __info.parentid + "");//获取父级的上级 合集路径
                parentidpath = bigparent + "," + parentidpath;
            }
            DataFactory.ExecuteNonQuery("update "+TableName+" set parentidpath='" + parentidpath + "' where periodid=" + newPid);//更新路径合集
            CheckAndFixClass(__info.parentid);//更新子child数量

            //Msg.AlertDoFun("", "top.location.reload();");
            Msg.AlertDoFun("恭喜添加成功!", "top.location.href='" + BasicField.GetUserUrl("teacher/CsZj", "courseid-" + __info.CourseId + ",costype-" + costype) + "';");
            isLoadPage = false;
            return;
        }
        else
        {
            Hashtable ht = new Hashtable();
            if (KSCMS.S("type") == "2")//节
            {
                if (string.IsNullOrEmpty(KSCMS.S("jname")))
                {
                    Msg.AlertDoFun("请输入节名称!", "top.location.href='" + BasicField.GetUserUrl("teacher/CsZj", "courseid-" + __info.CourseId + ",costype-" + costype) + "';");
                    isLoadPage = false;
                    return;
                }
                ht.Add("PeriodName", KSCMS.S("jname"));
            }
            else//章
            {
                if (string.IsNullOrEmpty(KSCMS.S("zname")))
                {
                    Msg.AlertDoFun("请输入章名称!", "top.location.href='" + BasicField.GetUserUrl("teacher/CsZj", "courseid-" + __info.CourseId + ",costype-" + costype) + "';");
                    isLoadPage = false;
                    return;
                }
                ht.Add("PeriodName", KSCMS.S("zname"));
            }
            CommonData.Update(""+TableName+"", ht, "where PeriodId=" + __info.PeriodId);
            Msg.AlertDoFun("恭喜修改成功!","top.location.href='"+ BasicField.GetUserUrl("teacher/CsZj", "courseid-" + __info.CourseId + ",costype-" + costype) + "';");

            isLoadPage=false;
            return;
        }
    }
    private void CheckAndFixClass(int parentID)
    {
        #region 更新child
        int Child = Convert.ToInt32(DataFactory.GetOnlyValue("select count(1) from "+TableName+" where parentidpath like '%" + parentID + ",%' and courseid=" + __info.CourseId + ""));
        DataFactory.ExecuteNonQuery("update "+TableName+" set Child=" + Child + " where periodid=" + parentID);
        #endregion
    }
    private string getselect(int courseid)
    {
        StringBuilder sb = new StringBuilder();
        if (courseid != 0)
        {
            DataTable dt = DataFactory.GetDataTable("select PeriodName, periodid from "+TableName+" where parentid=0 and addtype=0 and courseid=" + courseid + "");
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    string select="";
                    if (__info.parentid == Utils.StrToInt(dr["periodID"].ToString()))
                    {
                        select = "selected";
                    }

                    sb.AppendFormat("<option value=\"{0}\" {2}>{1}</option>", dr["periodID"].ToString(), dr["PeriodName"].ToString(), select);
                }
            }
        }
        return sb.ToString();
    }
</script>
<%
    if (!isLoadPage) return;
%>
	<form name="aspnetForm" method="post" action="<%=BasicField.GetUserUrl("teacher/csaddzj","do-"+KSCMS.S("do")+",courseid-"+__info.CourseId+",parentid-"+__info.parentid+",periodid-"+__info.PeriodId+",type-"+__info.type+"")+",frame-no" %>" id="aspnetForm">
<div class="t_tybox" style="padding-right:0;">
         <script src="/admin/include/main.js"></script>
      		   
              <table width="100%" border="0" cellpadding="1" cellspacing="1" class="border">  
			           <input name="action" type="hidden" value="save" />   
					         <input name="courseid" type="hidden" value="<%=__info.CourseId %>" />   
							   <input name="costype" type="hidden" value="<%=costype %>" />                                     
                    <tr style="display:<%=__info.type=="2"?"none":""%>">
                    <td class="lefttd" height="30" align="right" >
                       章标题:
                    </td>
                    <td class="righttd">
                       <span id="AddOne">
                        <input name="Zname" type="text" id="Zname" value="<%=__info.Zname %>" class="textbox" style="width:200px;" />
                        <span class="tips">*请输入章标题，</span>
                       </span>                     
                         </td>
                  </tr> 
				  <tbody style="display:<%=__info.type=="2"?"":"none"%>">

				   <tr>
                    <td class="lefttd" height="30" align="right" >
                       选择分类:
                    </td>
                    <td class="righttd">
                       <span id="Span2">
                        <select name="MyItem" <%=KSCMS.S("do")=="add"?"":"disabled" %> id="MyItem" style="width:211px">
		<option value="0">-无（作为一级分类）-</option>
		<%=getselect(__info.CourseId) %>

                        </select>
                        <span class="tips"></span>
                       </span>                     
                         </td>
                  </tr>       

				   <tr>
                    <td class="lefttd" height="30" align="right" >
                       节标题:
                    </td>
                    <td class="righttd">
                       <span id="Span1">
                        <input name="Jname" type="text" id="Jname" value="<%=__info.Jname %>" class="textbox" style="width:200px;" />
                        <span class="tips">*请输入节标题，</span>
                       </span>                     
                         </td>
                  </tr>  
				  
				  </tbody>         
           </table>

      
     <div style="clear:both;text-align:center">
    <br />
          <input type="submit" name="Button1" value="确定添加" id="Button1" class="ty_button" style="margin-left:16px"/>
       </div>

</div>

    </form>    	

