<%@ 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"];                //初始化用户信息，
    bool isLoadPage = true;  //定义页面是否加载
    bool ispower = false;     //判断用户权限
    public static int RoomID = 0;
    public static int type;
    public static int workID;
    public static string name;
    public static string DefaultFile = string.Empty;
    public static string photourl = string.Empty;
    public static string ClassRoomTitle = string.Empty;
    public string CourseIds = "0";

    int recordcount, pagecount;
    int CurrPage = new BasicField().GetCurrPage;
    int PageSize = 10;
    protected void Page_Load(object sender, EventArgs e)
    {
        RoomID = Utils.StrToInt(KSCMS.S("RoomID"));
        int tcid = Utils.StrToInt(DataFactory.GetOnlyValue("select TcID from KS_CosTeacher where UserID =" + __user.UserID));
        ispower = true;
        string sql1 = "";
        if (RoomID != 0)
        {
            sql1 = "select top 1 Title,courseids from KS_CosClassRoom where RoomID=" + RoomID;
            using (DataTable dt = DataFactory.GetDataTable(sql1))
            {
                if (dt.Rows.Count > 0)
                {
                    DataRow dr = dt.Rows[0];
                    ClassRoomTitle = dr["Title"].ToString();
                    CourseIds = dr["courseids"].ToString();
                }
            }
        }
        string DoMethod = KSCMS.S("do");

        switch (DoMethod)
        {
            case "del":
                deleteClassRoomStudent(KSCMS.S("StudentID"));
                break;
            case "verify":
                string studentids = KSCMS.S("studentid");

                if (!string.IsNullOrEmpty(studentids))
                {
                    string[] ids = studentids.Split(',');

                    for (int i = 0; i < ids.Length; i++)
                    {
                        CommonData.UpdateFieldStatus("KS_CosClassStudent", "verify", "studentID", Utils.StrToInt(ids[i].ToString()));
                        if (DataFactory.Exists("KS_CosClassStudent", "verify=0 and studentID=" + Utils.StrToInt(ids[i].ToString()) + ""))
                        {
                            //清除课程权限，更新xml文件
                            if (!string.IsNullOrEmpty(CourseIds))
                            {
                                DataFactory.ExecuteNonQuery("delete from KS_CosOrderItem where courseid in(" + CourseIds + ") and freeorder=1 and userid=" + Utils.StrToInt(ids[i].ToString()) + "");
                                Kesion.Course.CourseBuyRecordCache.DeleteUserAllPayCourseJson(Utils.StrToInt(ids[i].ToString()));
                            }
                        }
                    }
                }
                KSCMS.Redirect(BasicField.GetUserUrl("teacher/TcClassStudent", "roomid-" + RoomID));
                isLoadPage = false;
                return;
                break;
        }
        if (KSCMS.S("action").Equals("save"))
        {
            SaveChange();
        }
    }
    public string GetUserName(int UserID)
    {
        #region 得到用户名
        string str = string.Empty;
        str = DataFactoryUser.GetOnlyValue("select top 1 username from KS_user where userid=" + UserID).ToString();
        return str;
        #endregion
    }
    private void deleteClassRoomStudent(string WorkID)
    {
        if (WorkID == null || WorkID == "0") return;

        WorkID = Utils.FilterIDs(WorkID);
        using (DataTable dt = DataFactory.GetDataTable("select a.StudentID,a.RoomID,a.UserID,b.CourseIDs from KS_CosClassStudent a INNER JOIN KS_CosClassRoom b ON a.RoomID=b.RoomID Where a.StudentID in(" + WorkID + ")"))
        {
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    int id = Utils.StrToInt(dr["StudentID"].ToString());
                    int userid = Utils.StrToInt(dr["UserID"].ToString());
                    int RoomID1 = Utils.StrToInt(dr["RoomID"].ToString());

                    DataFactory.ExecuteNonQuery("Update KS_CosLearnRecord Set IsClose=2 Where UserID=" + userid + " And CourseID in(" + Utils.FilterIDs(dr["CourseIDs"].ToString()) + ")");  //班级加的课程关闭学习记录为过期

                    Hashtable ht = new Hashtable();
                    ht.Add("StudentID", id);
                    CommonData.Delete("[KS_CosClassStudent]", ht);

                    DataFactory.ExecuteNonQuery("delete from KS_AskTopic where userid=" + userid + " and courseid=" + RoomID1);
                    DataFactory.ExecuteNonQuery("delete from KS_CoursePJ where OrderType=20 and userid=" + userid + " and courseid=" + RoomID1);
                    CourseUserPowerCache.CleanClassRoomJson(userid);  //清除学生JSON缓存
                }

                Kesion.Course.Course.CheckCount("KS_CosClassStudent", "roomid=" + RoomID + "", "studentid", 1, "KS_CosClassRoom", "buycount", "roomid=" + RoomID + "");
            }
        }
        Msg.Alert("删除成功!", BasicField.GetUserUrl("teacher/TcClassStudent", "roomid-" + RoomID));
        isLoadPage = false;
        return;

    }
    protected void SaveChange()
    {
        string user = KSCMS.S("LstB1");
        string[] UserArr = user.Split(',');
        int i = 0;
        foreach (string _User in UserArr)
        {

            if (!string.IsNullOrEmpty(_User))
            {
                if (DataFactory.Exists("KS_CosClassStudent", "RoomID=" + RoomID + " and Userid=" + _User + ""))
                {
                    Msg.Alert("对不起,你添加的学员已经存在啦!", BasicField.GetUserUrl("teacher/TcClassStudent", "roomid-" + RoomID));
                    isLoadPage = false;
                    return;
                }
                else
                {
                    Hashtable ht = new Hashtable();
                    ht.Add("RoomID", RoomID);
                    ht.Add("Userid", _User);
                    ht.Add("AddDate", DateTime.Now);
                    ht.Add("IsPj", 0);
                    ht.Add("AskCount", 0);
                    ht.Add("Isdel", 0);
                    ht.Add("verify", 1);
                    CommonData.Insert("KS_CosClassStudent", ht);
                    i++;
                }
            }
            Kesion.Course.Course.CheckCount("KS_CosClassStudent", "roomid=" + RoomID + "", "studentid", 1, "KS_CosClassRoom", "buycount", "roomid=" + RoomID + "");
        }
          Kesion.Course.CourseUserPowerCache.CleanClassRoomUserJson(RoomID); //清除用户报班的JSON缓存
        Msg.Alert("恭喜,添加学员成功!", BasicField.GetUserUrl("teacher/TcClassStudent", "roomid-" + RoomID));
        isLoadPage = false;
        return;
    }

</script>
<%
    if (!isLoadPage) return;
	if (!KSCMS.S("do").Equals("modify") && !KSCMS.S("do").Equals("add")){
%>
<script>
	function changecation()
	{
		$("#actionid").val("verify");
		return true;
	}

</script>
  <form name="myform" action="<%=BasicField.GetUserUrl("teacher/TcClassStudent") %>" method="post" id="Form1" >
      <div class="t_tybox">
          <div class="tytitle"><h4>班级学员管理</h4>
          <%if(ispower){ %>
            <a href="<%=BasicField.GetUserUrl("teacher/tcclassstudent","do-add,roomid-"+RoomID) %>" class="addbtn">+添加学员</a>
                 	<a onclick="" href="<%=BasicField.GetUserUrl("teacher/StuImport","roomid-"+RoomID) %>" class="addbtn">导入学员</a>
                <%} %>
           	<a onclick="" href="<%=BasicField.GetUserUrl("teacher/TcClassRoom") %>" class="addbtn">返回</a>
            </div>
            <div class="clear blank10"></div>
			<div class="part_now">当前班级：<%=ClassRoomTitle %></div>
			<div class="clear blank10"></div>
			
            <table id="tablist" width="100%" border="0" align="center" cellpadding="0" cellspacing="0" class="border">
              <tr align="center" class="title">             
				 <td width="6%">选择</td>
				  <td width="10%">状态</td>
                 <td width="10%">学员的用户ID</td>  
                  <td width="20%">学员的用户名</td> 
                   <td width="6%">问答数</td> 
                  <td width="6%">是否评价</td>                
                 <td width="12%">加入时间</td>
                 <td width="20%">操作</td>
              </tr>  
      <%
          string sqlParam = " KS_CosClassStudent where   RoomID=" + RoomID + "";
          using (DataTable dt = DataFactory.GetPage("*", sqlParam, "StudentID", "order by  UserID desc", CurrPage, PageSize, out recordcount, out pagecount))
          {
              if (dt.Rows.Count > 0)
              {
                  int i = 1;
                  foreach (DataRow dr in dt.Rows)
                  {
                      KSCMS.W("<TR class=\"tdbg sort bar\"><td class=\"splittd\" align=\"center\"><input class=\"cleckbtn\" type=\"checkbox\" name=\"studentid\" value=\"" + dr["StudentID"].ToString() + "\" /></td>");
                      KSCMS.W("<td class=\"Ctd\" align=\"center\">" + (ispower ? ("<a href=\"" + BasicField.GetUserUrl("teacher/TcClassStudent", "do-verify,roomid-" + RoomID + ",studentid-" + dr["studentid"].ToString()) + "\">" + (Utils.StrToInt(dr["verify"].ToString()) == 0 ? "<font color=red>未加入</font>" : "<font color=green>已加入<font>") + "</a>") : (Utils.StrToInt(dr["verify"].ToString()) == 0 ? "<font color=red>未加入</font>" : "<font color=green>已加入<font>")) + " </td>");
                      KSCMS.W("<td class=\"Ctd\" align=\"center\">" + dr["userid"].ToString() + " </td>" +
                              "<td class=\"tag_left lefticon\"> " + GetUserName(Utils.StrToInt(dr["userid"].ToString())) + " </td>" +
                              "<td class=\"Ctd\" align=\"center\"> " + dr["AskCount"].ToString() + " </td><td class=\"Ctd\" align=\"center\">" + (dr["IsPj"].ToString() == "1" ? "已评" : "未评") + "</td> "+
                              "<td width=\"135\">" + Convert.ToDateTime(dr["adddate"].ToString()).ToString("yyyy-MM-dd") + "</td>");
                      if (ispower)
                      {
                          KSCMS.W("<td><div class=\"gl_btn\"><span class=\"span5\" style=\"width:50%\">" +
                          "<a onclick=\"return(confirm(确定删除该学员以及他的问答和评价信息吗?))\"  title=\"删除\" class=\"delete\" href=\"" + BasicField.GetUserUrl("teacher/tcclassstudent", "do-del,roomid-" + RoomID + ",StudentID-" + dr["StudentID"].ToString()) + "\"><i class=\"iconfont icon-lajitong-copy\"></i>删除</a></span>" +
                            " </div></td>");
                      }
                      else
                      {
                          KSCMS.W("<td class=\"splittd\" align=\"center\">无操作权限</td>");
                      }
                      KSCMS.W("</tr>");
                      i++;
                  }
              }
              else
              {
                  KSCMS.W("<tr class=\"tdbg\"><td class=\"Ctd\" style=\"text-align:center\" colspan=\"10\" ><div class=\"empty\">暂未添加任何学员</div></td> </tr> ");
              }
          }
		   %>
           </table>
            <div class="fy_box" >
			  <%
            #region 分页
            string PageStr = "[KS:PageStr1]";
            BasicField.ReplaceFilterPage(ref PageStr, CurrPage, PageSize, pagecount, recordcount);
            KSCMS.W(PageStr);
            #endregion
         %>
            </div>
          <%if(ispower){ %>
	 <div class="cz_btn">
		  <input type="hidden" value="<%=RoomID %>" name="RoomID" />
		 <input type="hidden" id="actionid" value="del" name="do" />
        <span><input type="checkbox" name="chkall" id="chkall" onclick="CheckAll(this.form);"/>全选</span>
        <span><input type="submit" class="button" value="批量删除" onclick="return (CheckIds('del'));"></span>
		  <span><input type="submit" class="button" value="批量审核" onclick="return (changecation())"></span>
		</div>
          <%} %>
	 <div class="clear"></div>

		</for1m>

<%}else{ %>
  <form name="myform" action="<%=BasicField.GetUserUrl("teacher/TcClassStudent","") %>" method="post" id="myform" >
 <div class="t_tybox">
         <div class="ty_title">添加学员</div>
         <div class="tips" style="padding:10px 0px; font-size:14px">
        <span id="Label2">班级名称：<%=ClassRoomTitle %></span></div>
       <table width="100%" align="center" border="0" cellpadding="0" cellspacing="0" class="border"> 
				<tr>
					<td align="right" class="lefttd" height="30"><strong>用户名：</strong></td>
					<td class="righttd" valign="top">&nbsp;
						<table border="0" width='100%' class="exam_seacher">
							<tr>
								<td class="tag_left" width="320" style="line-height: 30px;">搜索用户<span class="top_c_sc clearfix"><input name="TxtSJKey" type="text" id="TxtSJKey" class="textbox" style="width:160px;" />
									<input type="button" value="搜索" class="button" onclick="searchSJ();" cssclass="button" style="margin-left: 10px; border-radius: 5px; border: 1px solid #dce2e4;" /></span>
									<br />
									<br />
									<select size="4" name="LstB2" multiple="multiple" id="LstB2" style="height:300px;width:200px;float: left; height: 200px !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;">指给下列用户：
									<br />
									<br />
									<select size="4" name="LstB1" multiple="multiple" id="LstB1" style="height:300px;width:200px;float: left; height: 200px !important; background: #fff"></select>
								</td>
							</tr>
						</table>
					</td>
				</tr> 
    </table>
	<input name="action" value="save" type="hidden" />
	<input name="roomid" value="<%=RoomID %>" type="hidden" />
    <div class="clear blank10"></div>
       <div class="cz_btn nofloat" style="padding-left:162px;">
           <span><input type="submit" name="Button2" value="确定保存" onclick="return (CheckForm());" class="button" /></span>
           <span><input type="button" class="button" onclick="window.history.go(-1);"value=" 返 回 "></span>
       </div>

       <div class="clear blank20"></div>
     </div>
	 </form>
<%} %>
<script>
	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);
		}
		if (idArr.length <= 0) {
			alert("你没有指定用户!");
			return false;
		}
		return true;
	}
	function searchSJ() {
		var key = jQuery("#TxtSJKey").val();
		if (key == '') {
			KesionJS.Alert("请输入试卷关键字！", "jQuery('#TxtSJKey').focus()");
			return false;
		} else {

			puburl = "/plus/course/CourseAjax.ashx?action=GetUser&RoomID=<%=RoomID%>&Key=" + escape(key)+"";

			jQuery.ajax({
				url: puburl, success: function (d) {

					jQuery("#LstB2").empty();
					jQuery("#LstB2").html(d);
				}
			});

		}
	}
	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;
					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;
			}
		}
	}


</script>
