<%@ 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"];                //初始化用户信息，
    bool isLoadPage = true;  //定义页面是否加载
    bool ispower = false;     //判断用户权限
    public  DataRow drr;
    public  int TcId = 0;
    public  int classId = 0;
    public string Type = string.Empty;
    public  string RoomID = "0";
    public  string sqlParam = string.Empty;
    public  int Provinceid = 0;
    public  int CityId = 0;
    public  string DefaultPic = string.Empty;
    public string TName = string.Empty;
    public string ClassName=string.Empty;
    public string CourseIDS = string.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {
        RoomID = KSCMS.S("roomid");
        Type = KSCMS.S("type");

        string sql = "select top 1 tcid,TName,ClassID,Provinceid,Cityid,verify from KS_CosTeacher where Field='" + (new TemporaryVar()).UserName + "'";
        if (__user.GroupID == 3)
        {
            sql = "select top 1 tcid,TName,ClassID,Provinceid,Cityid,verify from KS_CosTeacher where Field='" + DataFactory.GetOnlyValue("select top 1 Teacher from KS_CosClassroom where roomid="+RoomID+"") + "'";
        }
        using (DataTable dt = DataFactory.GetDataTable(sql))
        {
            DataRow dr;
            if (dt.Rows.Count > 0)
            {
                dr = dt.Rows[0];
                if (Utils.StrToInt(dr["verify"].ToString()) == 0)
                {
                    Msg.Alert("对不起，审核未通过不能进入!！", BasicField.GetUserUrl("teacher/Teacher"));
                    isLoadPage = false;
                    return;
                }
                TcId = Utils.StrToInt(dr["tcid"].ToString());
                classId = Utils.StrToInt(dr["ClassID"].ToString());
                TName = dr["TName"].ToString();
                ClassName = MyCache.GetCosClass(classId, "ClassName", 0);
                #region    权限校验
                //机构
                if (__user.GroupID == 3 || Utils.StrToInt(DataFactory.GetOnlyValue("select count(*) from KS_CosClassroom where BanzhuRenID =" + new TemporaryVar().UserID + " and RoomID =" + RoomID)) > 0)
                {
                    ispower = true;

                }//独立教师
                else if (__user.GroupID == 4 && new TemporaryVar().SchoolID == 0)
                {
                    ispower = true;
                }

                if (Type == "board")
                {
                    CourseIDS += DataFactory.GetOnlyValue("select top 1 BoardID from ks_cosClassRoom where roomid=" + RoomID);
                    ispower=Kesion.APPCode.Public.IsClassRoomPower(Utils.StrToInt(RoomID), TcId, "group") ;
                  
                }
                else if (Type == "pack")
                {
                    CourseIDS += DataFactory.GetOnlyValue("select top 1 PackID from ks_cosClassRoom where roomid=" + RoomID);
                    ispower=Kesion.APPCode.Public.IsClassRoomPower(Utils.StrToInt(RoomID), TcId, "checkpackage") ;
                  
                }
                else
                {
                    CourseIDS += DataFactory.GetOnlyValue("select top 1 courseids from ks_cosClassRoom where roomid=" + RoomID);
                    ispower=Kesion.APPCode.Public.IsClassRoomPower(Utils.StrToInt(RoomID), TcId, "course") ;
                  
                }

                ispower = true;

                #endregion
            }
            else
            {

                Msg.Alert("对不起，您还未完善个人资料!", BasicField.GetUserUrl("teacher/Teacher"));

                isLoadPage = false;
                return;
            }

        }
        string DoMethod = KSCMS.S("do");
        switch (DoMethod)
        {
            case "modify":
                initialEdit(Utils.StrToInt(RoomID)); //编辑
                break;
            case "del":
                deleteSj(RoomID.ToString()); //删除
                break;
        }
        if (KSCMS.S("action").Equals("save"))
        {
            SaveChange();
        }
    }
    protected void SaveChange()
    {
        Hashtable ht = new Hashtable();
        string msg = string.Empty;
        if (Type == "board")
        {
            msg = "绑定小组成功!";
            ht.Add("BoardID", KSCMS.S("LstB1")); //添加小组
        }
        else if (Type == "pack")
        {
            msg = "绑定考核成功!";
            ht.Add("PackID", KSCMS.S("LstB1")); //添加考核
        }
        else
        {
            msg = "绑定课程成功!";
            string proids = string.Empty;
            proids = KSCMS.S("LstB1");
            ht.Add("CourseIDs", proids); //添加课程
            ht.Add("CourseCount", (string.IsNullOrEmpty(proids) ? 0 : Utils.StrToInt(proids.Split(',').Length)));
        }
        CommonData.Update("KS_CosClassRoom", ht,"where roomid=" + RoomID);
        if(Type != "board" && Type != "pack")
        {
            if (!string.IsNullOrEmpty(KSCMS.S("LstB1")))
            {
                DataFactory.ExecuteNonQuery("delete from KS_CosOrderItem where FreeOrder = 1 and CourseID not in(" + KSCMS.S("LstB1") + ") and OrderType = 6 and UserID in (select UserID from KS_CosClassStudent where roomid=" + RoomID + ")");
                #region 班级学员添加新绑定的课程
                //using (DataTable dt = DataFactory.GetDataTable("select CourseID from KS_CosOrderItem where FreeOrder = 1 and CourseID not in(" + KSCMS.S("LstB1") + ") and OrderType = 6 and UserID in (select UserID from KS_CosClassStudent where roomid=" + RoomID + ")"))
                //{
                //    if(dt.Rows.Count > 0)
                //    {

                //    }
                //}
                #endregion
            }
            else
            {
                DataFactory.ExecuteNonQuery("delete from KS_CosOrderItem where FreeOrder = 1 and OrderType = 6 and UserID in (select UserID from KS_CosClassStudent where roomid=" + RoomID + ")");
            }
        }
        Msg.Alert(msg, BasicField.GetUserUrl("teacher/TcClassRoom"));
        isLoadPage = false;
        return;
    }
    private void initialEdit(int CourseId)
    {
        SqlParam[] param = new SqlParam[1];
        param[0] = new SqlParam("RoomID", CourseId);

        using (DataTable dt = CommonData.GetDataTable("[KS_CosClassRoom]", "*", param))
        {
            if (dt.Rows.Count > 0)
            {
                drr = dt.Rows[0];
                // initial(drr["CourseIDs"].ToString());
            }
        }
    }
    private void deleteSj(string RoomID)
    {
        if (RoomID == null || RoomID == "0") return;

        RoomID = Utils.FilterIDs(RoomID);
        using (DataTable dt = DataFactory.GetDataTable("select RoomID from KS_CosClassRoom Where RoomID in(" + RoomID + ")"))
        {
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    int id = Utils.StrToInt(dr["RoomID"].ToString());
                    Hashtable ht = new Hashtable();
                    ht.Add("RoomID", id.ToString());
                    DataFactory.ExecuteNonQuery("delete from KS_CosHomeWork where ClassRoomID=" + id + "");
                    CommonData.Delete("[KS_CosClassRoom]", ht);
                }
            }
        }
        Msg.Alert("恭喜,班级删除成功!", KSCMS.GetComeUrl());
        isLoadPage = false;
        return;
    }
    public string GetParam(string Fields)
    {
        string result = string.Empty;
        if (drr != null)
        {
            result = drr[Fields].ToString();
        }
        return result;
    }
    //private string initial(string selectedid)
    //{
    //    string param = string.Empty;
    //    int isbindable = Utils.StrToInt(DataFactory.GetOnlyValue("select IsBindable from KS_CosClassRoom where roomid" + KSCMS.S("roomid")));
    //    if (isbindable != 1)
    //    {
    //        string username = KSCMS.S("username");
    //        if (string.IsNullOrEmpty(username))
    //        {
    //            username = new TemporaryVar().UserName;
    //        }
    //        param += " and username = '" + username + "'";
    //    }
    //    string sqlstr = "select top 50 CourseID,Name from KS_Course where TeachWay=1 and verify=1 and IsOff=1" + param;
    //    if(Type == "board")
    //    {
    //        sqlstr = "select top 50 PackID,PackName from KS_BBSBoard";
    //    }
    //    else if(Type == "pack")
    //    {
    //        sqlstr = "select top 50 BoardID,BoardName from KS_CheckPackage";
    //    }
    //    Utils.WriteLog(sqlstr);
    //    StringBuilder sb = new StringBuilder();
    //    using (DataTable dt = DataFactory.GetDataTable(sqlstr))
    //    {
    //        if (dt.Rows.Count > 0)
    //        {
    //            foreach (DataRow dr in dt.Rows)
    //            {
    //                string choose = "";
    //                if (("," + selectedid + ",").IndexOf("," + dr[0].ToString() + ",") != -1)
    //                {
    //                    choose = "selected";
    //                }
    //                sb.AppendFormat("<option value=\"{0}\" {2}>{1}</option>", dr[0].ToString(), dr[1].ToString(), choose);
    //            }
    //        }
    //    }
    //    return sb.ToString();
    //}
</script>
<%
    if (!isLoadPage) return;
%>
<script>
	function iszhekou() {
		var ISLoad = jQuery("#ISLoad :radio[checked]").val();
		if (ISLoad == "1") {
			//折扣价
			jQuery("#Iszhekou").css("display", "");
			jQuery("#IsFixedPrice").css("display", "none");
		} else if (ISLoad == "0") {
			//免费
			jQuery("#Iszhekou").css("display", "none");
			jQuery("#IsFixedPrice").css("display", "none");
		} else {
			//固定价格
			jQuery("#Iszhekou").css("display", "none");
			jQuery("#IsFixedPrice").css("display", "");
		}
	}
	function free() {
		var checkrad = jQuery("#RadioButtonList2 :radio[checked]").val();
		if (checkrad == "0") {

			jQuery("#Tbody2").css("display", "none");

		} else {

			jQuery("#Tbody2").css("display", "");
		}
	}
	function zhekou() {
		var money = document.getElementById('Money').value;
		var Price = document.getElementById('Price_Member').value;
		var zhekou = (parseFloat(Price / money) * 10).toFixed(1);

		if (zhekou == "NaN" || zhekou <= 0) {
			zhekou = 0;
		} else if (zhekou == "Infinity" || zhekou >= 10) {
			zhekou = 10;
		}
		document.getElementById('zhekou').value = zhekou;
	}

	function CheckForm() {

		var idArr = new Array();
		var dest = document.getElementById('LstB1');
		for (var i = 0; i < dest.options.length; i++) {
			dest.options[i].selected = "true";
			idArr.push(dest.options[i].value);
		}
		return true;
	}
	function showwatermarkarea() {
		var checkrad = jQuery("#RadioButtonList3 :radio[checked]").val();
		if (checkrad == "2") {
			jQuery("#watermark0").css("display", "none");
			jQuery("#watermark2").css("display", "");
		} else if (checkrad == "1") {
			jQuery("#watermark0").css("display", "");
			jQuery("#watermark2").css("display", "none");
		}
		else {
			jQuery("#watermark0").css("display", "none");
			jQuery("#watermark2").css("display", "none");
		}
	}
	function addUser() {
		var src = document.getElementById('LstB2');
		var dest = document.getElementById('LstB1');

		for (var i = 0; i < src.options.length; i++) {
			if (src.options[i].selected) {
				var exist = false;
				for (var j = 0; j < dest.options.length; j++) {
					if (dest.options[j].value == src.options[i].value) {
						exist = true;
						break;
					}
				}
				if (!exist) {
					var opt = document.createElement('OPTION');
					opt.value = src.options[i].value;
					opt.text = src.options[i].text;
					opt.selected = true;
					dest.options.add(opt);
				}
			}
		}
	}
	function delUser() {
		var dest = document.getElementById('LstB1');

		for (var i = dest.options.length - 1; i >= 0; i--) {
			if (dest.options[i].selected) {
				dest.options[i] = null;
			}
		}
	}
	function searchCourse() {
		var key = jQuery("#TxtSJKey").val();
		if (key == '') {
            <%if(Type == "board") {%>
		    KesionJS.Alert("请输入小组关键字！", "jQuery('#TxtSJKey').focus()");
            <%}else if(Type == "pack") {%>
		    KesionJS.Alert("请输入考核关键字！", "jQuery('#TxtSJKey').focus()");
            <%}else {%>
		    KesionJS.Alert("请输入课程关键字！", "jQuery('#TxtSJKey').focus()");
            <% }%>
			return false;
		} else {
            <%if(Type == "board") {%>
		    puburl = "/plus/course/CourseAjax.ashx?action=GetClassBoard&RoomID=<%=RoomID%>&Key=" + escape(key) + ""; 
            <%}else if(Type == "pack") {%>
		    puburl = "/plus/course/CourseAjax.ashx?action=GetClassPack&RoomID=<%=RoomID%>&Key=" + escape(key) + "";
            <%}else {%>
		    puburl = "/plus/course/CourseAjax.ashx?action=GetTcCourse&from=user&RoomID=<%=RoomID%>&Key=" + escape(key) + "";
            <% }%>
		    console.log(puburl);
			jQuery.ajax({
				url: puburl, success: function (d) {
				
					jQuery("#LstB2").empty();
					jQuery("#LstB2").html(d);
				}
			});
		}
	}
</script>
<style>
.border tr td{ border-bottom:0;}
</style>
<div class="t_tybox">
  <div class="tytitle"><h4 class="h4"><%=Type=="board"?"绑定小组":Type=="pack"?"绑定考核":"绑定课程" %></h4>
 
  </div>
     <div class="clear"></div>
     <script src="/ks_inc/DatePicker/WdatePicker.js"></script>
     <script src="../../ks_inc/weiboApi.js"></script>
	    <div class="tab-page" id="sjPanel">
		  <form name="myform" action="<%=BasicField.GetUserUrl("teacher/TcClassCourse","do-"+KSCMS.S("do") + ",Type-"+Type) %>" method="post" id="Form1" >
		  <input type="hidden" value="save" name="action" />
		    <input type="hidden" value="<%=KSCMS.S("roomid") %>" name="RoomID" />
	            <table width="50%" border="0" cellpadding="0" cellspacing="0" class="border"> 
				<tr>
					<td align="right" class="lefttd" height="30"></td>
					<td class="righttd" valign="top"">&nbsp;
						<table border="0" width='100%' class="exam_seacher">
							<tr>
								<td class="tag_left" width="300" style="line-height: 30px;">
								<label style="display:inline-block;padding-top:18px"><%=Type=="board"?"搜索小组":Type=="pack"?"搜索考核":"搜索课程" %></label>
                                   
                                 <span class="top_c_sc clearfix" style="margin-bottom:15px"><input name="TxtSJKey" type="text" id="TxtSJKey" class="textbox" style="width:160px;" />

									<input type="button" value="搜索" class="button" onclick="searchCourse();" cssclass="button" style="margin-left: 10px; border-radius: 5px; border: 1px solid #dce2e4;" /></span>
									
									<select size="4" name="LstB2" multiple="multiple" id="LstB2" style="width:320px;float: left; height: 360px !important ; background: #fff"></select>
                                   
								</td>
								<td>
									<p>
										<input type="button" value=" > " onclick="addUser()" class="ty_button" />
									</p>
									<br />
									<p>
										<input type="button" value=" < " onclick="delUser()" class="ty_button" />
									</p>
								</td>
								<td class="tag_left" style="line-height: 30px;"><label style="display:inline-block;padding-top:18px"><%=Type=="board"?"绑定下列小组：":Type=="pack"?"绑定下列考核：":"绑定下列课程：" %></label>
									<br />
                                    <br />
									<select size="4" name="LstB1" multiple="multiple" id="LstB1" style="width:320px;float: left; height: 360px !important; background: #fff">
									<%
										StringBuilder sb = new StringBuilder();
										string sql2 = string.Empty;
                                        if (Type == "board")
                                        {
                                            sql2 = "select BoardID,BoardName from KS_BBSBoard where BoardID in(" + CourseIDS + ")";
                                        }
                                        else if (Type == "pack")
                                        {
                                            sql2 = "select PackID,PackName from KS_CheckPackage where PackID in(" + CourseIDS + ")";
                                        }
                                        else
                                        {
                                            sql2 = "select CourseID,Name from KS_course where courseid in(" + CourseIDS + ")";
                                        }
										using (DataTable dt2 = DataFactory.GetDataTable(sql2))
										{
											if (dt2.Rows.Count > 0)
											{
												foreach (DataRow dr2 in dt2.Rows)
												{
													sb.AppendFormat("<option value=\"{1}\" selected>{0}</option>", dr2[1].ToString(), dr2[0].ToString());
												}
											}
										}
										KSCMS.W(sb.ToString());
			  %>

									</select>
								</td>
							</tr>
						</table>
					</td>
				</tr> 
    </table>
	    <div class="cz_btn nofloat" style=" padding:0 0px 20px 175px;">
            <%if(ispower){ %>
			<span><input type="submit" name="Button2" value="确定保存" onclick="return (CheckForm());" id="Button2" class="button" /></span>
            <%} %>
			<span><input type="button" class="button" onclick="window.location.href='<%=BasicField.GetUserUrl("teacher/TcClassRoom")%>';"value=" 返 回 "></span>
	     </div>

		 </form>
	  </div>
</div>