<%@ 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="Newtonsoft.Json.Linq" %>
<%@ Import Namespace="Newtonsoft.Json" %>
<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 sqlParam = string.Empty;
	public static int VideoType = 0;
	public static string ACCESS_KEY = "";
	public static string SECRET_KEY = "";
	public static string UploadFiles = "";
	public static int v_count = 0;
	public static int t_free = 0;
	protected void Page_Load(object sender, EventArgs e)
	{
		CheckUserLogin.Run();

		VideoType = Utils.StrToInt(KSCMS.S("VideoType"),5);
        Hashtable htVidoeAccount = Kesion.BLL.Yun.GetVideoServerAccount(VideoType); //5获得保利威视账户信息
        if (htVidoeAccount != null)
       {
                ACCESS_KEY = htVidoeAccount["ACCESS_KEY"].ToString();
                SECRET_KEY = htVidoeAccount["SECRET_KEY"].ToString();
                UploadFiles = htVidoeAccount["USER_AGENT"].ToString();
        }

		string DoMethod = KSCMS.S("do");
		switch (DoMethod)
		{
			case "del":
				Delete(KSCMS.S("ids"));
				break;
			case "getvideo":
				GetVideo();
				break;
		}
	}
	private void Delete(string videoid)
	{
		//string videoid = KSCMS.S("ids");
		string str = string.Empty;
		string deleid = string.Empty;
		if (videoid == null || videoid == "0") return;

		videoid = Utils.FilterIDs(videoid);

        string sqlparm = " and AddUserID =" + new TemporaryVar().UserID;
        if (new TemporaryVar().GroupID == 3)
        {
            sqlparm = " and b.SchoolID =" + new TemporaryVar().UserID;
        }
        
        using (DataTable dt = DataFactory.GetDataTable("select b.* from KS_YunVideo a inner join KS_YunVideoItem b  on a.vid=b.vid Where    a.id in(" + videoid + ") "+sqlparm))
		{
			if (dt.Rows.Count > 0)
			{
				foreach (DataRow dr in dt.Rows)
				{
					int id = Utils.StrToInt(dr["id"].ToString());
					string vid = dr["vid"].ToString();
					str = DoDelAllVideo(VideoType, vid, id);
					if (str == "false")
					{
						deleid += id + ",";
					}
				}
				if (string.IsNullOrEmpty(deleid))
				{
					Msg.Alert("恭喜，删除视频成功", BasicField.GetUserUrl("teacher/YunVideoManage","VideoType-"+VideoType));
					isLoadPage = false;
					return;
				}
				else
				{
					Msg.Alert("抱歉，删除视频失败ID:" + deleid, BasicField.GetUserUrl("teacher/YunVideoManage", "VideoType-" + VideoType));
					isLoadPage = false;
					return;
				}
			}
			else
			{
				Msg.Alert("抱歉，删除视频失败", BasicField.GetUserUrl("teacher/YunVideoManage", "VideoType-" + VideoType));
				isLoadPage = false;
				return;
			}
		}

	}
	public string DoDelAllVideo(int VideoType, string vid, int ID, int YunType = 1)
	{

		#region 删除全部云点播的视频
		string str1 = string.Empty;

        if (VideoType == 1)
        {
            string str = string.Format("http://v.polyv.net/uc/services/rest?method=delVideoById&writetoken={0}&vid={1}", ACCESS_KEY, vid);
            string strres = Kesion.BLL.Yun.GetUserJosn(str);
            JObject json1 = JObject.Parse(strres);
            if (json1["error"].ToString() == "0")
            {
                Hashtable ht = new Hashtable();
                ht.Add("vid", vid);
                ht.Add("id", ID);
                CommonData.Delete("KS_YunVideo", ht);
                DataFactory.ExecuteNonQuery("delete from KS_YunVideoItem where Vid='" + vid + "' and AddUserID=" + new TemporaryVar().UserID + "");

                str1 = "true";
                // JS.Alert("恭喜，删除视频成功", KSCMS.GetInstallDir() + MyCache.GetCacheConfig(4) + "/Yun/KS.YunVideo.aspx?VideoType=" + VideoType + "");

            }
            else
            {
                str1 = "false";
                // JS.Alert("抱歉，删除视频失败", KSCMS.GetInstallDir() + MyCache.GetCacheConfig(4) + "/Yun/KS.YunVideo.aspx?VideoType=" + VideoType + "");
            }
        }
        else
        {
            Hashtable ht = new Hashtable();
            ht.Add("vid", vid);
            ht.Add("id", ID);
            CommonData.Delete("KS_YunVideo", ht);
            DataFactory.ExecuteNonQuery("delete from KS_YunVideoItem where Vid='" + vid + "' and AddUserID=" + new TemporaryVar().UserID + "");

        }
		return str1;
		#endregion

	}
	public string GetVideoCataName(string CataID)
	{
		#region 得到视频分类名称
		string name = string.Empty;
		int CosClassID = Utils.StrToInt(DataFactory.GetOnlyValue("select top 1 CosClassID from KS_YunCosVideoCata where CataID='" + CataID + "'"));

		if (CosClassID == 0)
		{
			name = "--";
		}

		else
		{
			name = DataFactory.GetOnlyValue("select top 1 className from KS_CosClass where type=0 and  classid=" + CosClassID);
		}
		return name;
		#endregion
	}
	protected void GetVideo()
	{
		#region 从KESION云服务获取视频

		if (string.IsNullOrEmpty(ACCESS_KEY) || string.IsNullOrEmpty(SECRET_KEY) || string.IsNullOrEmpty(UploadFiles))
		{
			Msg.Alert("对不起，获取视频失败啦，由于您的ACCESS_KEY，SECRET_KEY，UploadFiles这些为空呢,请联系平台的客服呢", BasicField.GetUserUrl("teacher/YunVideoManage", "VideoType-" + VideoType));
			isLoadPage = false;
			return;
		}
		else
		{
			DoGetVideo(VideoType);
		}
		#endregion
	}
	public void DoGetVideo(int VideoType, int get = 0, int YunType = 1)
	{
		#region 操作获取视频列表

		if (VideoType == 1)
		{
			string str = "http://v.polyv.net/uc/services/rest?method=getNewList&readtoken=" + SECRET_KEY + "&pageNum=1&numPerPage=10000";

			string strres = Kesion.BLL.Yun.GetUserJosn(str);
			JObject json1 = JObject.Parse(strres);
			if (json1["error"].ToString() == "0")
			{
				JArray ja1 = (JArray)JsonConvert.DeserializeObject(json1["data"].ToString());
				foreach (var oco in ja1)
				{
					Hashtable ht = new Hashtable();
					ht.Add("title", oco["title"].ToString());
					ht.Add("FirstImage", oco["first_image"].ToString());
					ht.Add("Ptime", oco["ptime"].ToString());
					ht.Add("Duration", oco["duration"].ToString());
					ht.Add("Times", oco["times"].ToString());
					ht.Add("SwfLink", oco["swf_link"].ToString());
					ht.Add("Tag", oco["tag"].ToString());
					ht.Add("context", oco["context"].ToString());
					ht.Add("vid", oco["vid"].ToString());
					ht.Add("VideoType", VideoType);
					ht.Add("Status", Utils.StrToInt(oco["status"].ToString()));
					// ht.Add("classid", ClassID);
					ht.Add("SourceFileSize", Utils.StrToFloat(Utils.StrToFloat(oco["source_filesize"].ToString()) / (1024 * 1024)));
					ht.Add("CataID", oco["cataid"].ToString());
					if (DataFactory.Exists("KS_YunVideo", " VideoType=" + VideoType + " and  vid='" + oco["vid"].ToString() + "'"))
					{
						CommonData.Update("KS_YunVideo", ht, "where VideoType=" + VideoType + " and  vid='" + oco["vid"].ToString() + "'");
					}
					else
					{
						CommonData.Insert("KS_YunVideo", ht);
						Hashtable ht2 = new Hashtable();
						ht2.Add("Vid", oco["vid"].ToString());
						ht2.Add("AddUserID", UserManage.GetUserInfo().UserID);
						ht2.Add("VideoType", VideoType);
						CommonData.Insert("KS_YunVideoItem", ht2);
					}
				}
				if (get == 0)
				{
					Msg.Alert("恭喜，获取视频列表成功！", BasicField.GetUserUrl("teacher/YunVideoManage", "VideoType-" + VideoType));
					isLoadPage = false;
					return;
				}
				else
				{
					//JS.Alert("恭喜，获取视频列表成功！", KSCMS.GetInstallDir() + MyCache.GetCacheConfig(4) + "/Yun/KS.GetYunVideo.aspx?VideoType=" + VideoType + "");
				}
			}
			else
			{
				if (get == 0)
				{
					Msg.Alert("抱歉，获取视频列表失败！", BasicField.GetUserUrl("teacher/YunVideoManage", "VideoType-" + VideoType));
					isLoadPage = false;
					return;
				}
			}
		}
		#endregion
	}
</script>
<%
    if (!isLoadPage) return;
%>
	<script>
		function delvideo() {

			if (confirm('删除视频，此操作不可逆，确定删除视频吗?')) {
				jQuery('#ajaxmsg').toggle();
				return true;
			}
			else {
				return false;
			}
		}

		$(function () {
			$(".emptycss").find("td").wrapInner("<div class='empty'></div>");
			$(".emptycss").removeClass("emptycss");
		});
    </script>
	<div class="t_tybox">
		<div class="tytitle clearfix">
        	<h4 class="lf">视频管理</h4>
            <div class="top_c_sc" style="margin-right:10px;">
                <form method="post" action="<%=BasicField.GetUserUrl("teacher/YunVideoManage") %>">
                    <input name="KeyWord" type="text" id="KeyWord" class="textbox coursename" onfocus="keyWordFocus();" onblur="keyWordBlur();" placeholder="搜索视频..." />
                    <input type="submit" name="Button4" value=" 搜索 " id="Button4" class="button"/>
                </form>
            </div>
        </div>
		<%if ( false )
                      { %>
     	<iframe src="/plus/yun/yuncs.aspx?type=init&id=5&a=1&VideoType=<%=VideoType%>"  id="aliyunbutton" scrolling="no" name="upframe" style="width:100%;height:60px;" frameborder="no"></iframe>          	
        <%} %>
        <div class="clear"></div>
        <form method="post" action="<%=BasicField.GetUserUrl("teacher/YunVideoManage","do-del") %>">
            <div class="listByImg">
                <ul>
                    <%
                        int recordcount, pagecount;
                        int CurrPage = new BasicField().GetCurrPage;
                        int PageSize = 10;
                        sqlParam = " KS_YunVideo a inner join KS_YunVideoItem b  on a.vid=b.vid Where  1=1 and Status!=20 ";

                        if (new TemporaryVar().GroupID==3)
                        {
                            sqlParam +=" and b.SchoolID=" + new TemporaryVar().UserID;
                        }else {
                            sqlParam +=" and b.AddUserID=" + new TemporaryVar().UserID;
                        }

                        if (!string.IsNullOrEmpty(KSCMS.S("KeyWord")))
                        {
                            if (KSCMS.S("KeyWord") != "请输入关键字！")
                            {
                                sqlParam += " and a.title like '%" +Utils.ChkSQL(KSCMS.S("KeyWord")).Trim().Replace("'", "''") + "%'";
                            }
                        }
                        if (Utils.StrToInt(KSCMS.S("cosclassid")) != 0)
                        {
                            string CataId = DataFactory.GetOnlyValue("select top 1 CataID from KS_YunCosVideoCata where CosClassID=" + Utils.StrToInt(KSCMS.S("cosclassid")) + " and VideoType=" + VideoType);
                            if (!string.IsNullOrEmpty(CataId) || CataId != "0")
                            {
                                sqlParam += " and a.CataID='" + CataId + "'";
                            }
                        }
                        using (DataTable dt = DataFactory.GetPage("a.*,b.*", sqlParam, "a.ID", "order by a.ID desc", CurrPage, PageSize, out recordcount, out pagecount))
                        {
                            if (dt.Rows.Count > 0)
                            {
                                foreach (DataRow dr in dt.Rows)
                                {
                                    KSCMS.W("<li><input  name=\"ids\" type=\"checkbox\" value=\"" + dr["ID"].ToString() + "\" /><div class=\"image\"><img src=\"" + dr["FirstImage"].ToString() + "\" onerror=\"this.src='../../sysimg/nopic.gif'\" /></div>" +
                       "<div class=\"name\"><span class=\"staus\"> " + Kesion.BLL.YunVideo.GetVideoStatus(Utils.StrToInt(dr["status"].ToString()), Utils.StrToInt(dr["VideoType"].ToString())) + "</span>" +
                       "<a href=\"#\"> " + dr["title"].ToString() + "</a><span>" + dr["Duration"].ToString() + "</span>" +
                       "<span class=\"size\">" + Utils.StrToFloat(dr["SourceFileSize"].ToString()).ToString("f2") + "MB</span></div>" +
                       "<div class=\"info\">视频ID：" + dr["vid"].ToString() + "<br />分类：" + GetVideoCataName(dr["CataID"].ToString()) + "</div>" +
                       "<div class=\"date\"><span class=\"operating\"><a href=\"" + BasicField.GetUserUrl("teacher/YunVideoManage", "do-del,Ids-" + dr["ID"].ToString() + ",VideoType-" + dr["VideoType"].ToString() + ",vid-" + dr["vid"].ToString() + "") + "\" onclick=\"return(delvideo());\" title=\"删除\">" +
                       "<i class=\"icon iconfont icon-lajitong-copy\"></i></a></span> " + dr["Ptime"].ToString() + "</div><div class=\"clear\"></div> </li>");
                                }
                            }
                            else
                            {
                                KSCMS.W("<div class=\"empty\">没有任何视频记录</div>");
                            }
                        }
                    %>
                </ul>
            </div>
            <div class="content-area">
                <div>
                    <div class="cz_btn">
                        <input type="checkbox" name="chkall" id="chkall" onclick="CheckAll(this.form);" class="checkbtn" /><label for="chkall">全选</label>
                        <%--<a id="LinkButton2" class="button" href="<%=BasicField.GetUserUrl("teacher/YunVideoManage","do-del") %>">批量删除</a>--%>
                        <input type="submit" name="delete" id="delete" style="display: none" /><label for="delete" class="ty_button">批量删除</label>
                    </div>
                    <div class="fy_box">
                        <%
                    #region 分页
                    string PageStr = "[KS:PageStr1]";
                    BasicField.ReplaceFilterPage(ref PageStr, CurrPage, PageSize, pagecount, recordcount);
                    KSCMS.W(PageStr);
                    #endregion
                        %>
                    </div>
                    <div class="clearfix"></div>
                </div>
            </div>
        </form>
    </div>
    <div style="margin-top:10px"></div>