<%@ Control Language="C#" %>
<%@ Import Namespace="Kesion.Cache" %>
<%@ Import Namespace="Kesion.Publics" %>
<%@ Import Namespace="Kesion.BLL" %>
<%@ Import Namespace="Kesion.Config" %>
<%@ Import Namespace="Kesion.Components" %>
<%@ Import Namespace="Kesion.HtmlTags" %>
<%@ Import Namespace="System.Data" %>
<script runat="server" type="text/C#">
    dynamic __user = UserManage.GetUserInfo();                //初始化用户信息，
    private static dynamic __info = new System.Dynamic.ExpandoObject();   //初始化当前页信息
    bool isLoadPage = true;  //定义页面是否加载

    private string action = string.Empty;
    private int Id = 0;
    BlogConfigInfo __configinfo = null;

    int recordcount, pagecount;
    int CurrPage = new BasicField().GetCurrPage;
    int PageSize = 10;
    protected void Page_Load(object sender, EventArgs e)
    {
        action = KSCMS.S("action");
        if (string.IsNullOrEmpty(action))
        {
            action = BasicField.GetParam("do");
            if (string.IsNullOrEmpty(action)) 
                action = KSCMS.S("do");
        }
        Id = Utils.StrToInt(BasicField.GetParam("id"));
        if (Id == 0)
        {
            Id = Utils.StrToInt(KSCMS.S("id"));
        }

        __configinfo = BlogConfigManage.Deserialize(Server.MapPath("~/config/plus/plus.space/Blog.config"));

        action = action.ToLower();
        switch (action)
        {

            case "dosave":
                DoSave();
                return;

            case "del":  //删除相册
                using (DataTable dt = DataFactory.GetDataTable("SELECT PicUrls FROM KS_UserPhotos where UserID=" + __user.UserID + " and picid = " + Id))
                {
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        string pics = dt.Rows[0]["PicUrls"].ToString();
                        Match m = null;
                        for (m = Regex.Match(pics, @"\/UploadFiles/[\w\W]+?(.jpg|.png|.gif)", RegexOptions.IgnoreCase); m.Success; m = m.NextMatch())
                        {
                            UtilsFile.DelFile(m.Value);
                        }
                    }
                }

                Hashtable ht = new Hashtable();
                ht.Add("PicID", Id);
                ht.Add("UserID", __user.UserID);

                if (CommonData.Delete("KS_UserPhotos", ht))
                {
                    DataFactory.ExecuteNonQuery("Delete From KS_UploadFiles Where ChannelID=100010 and infoid in(" + Id + ")");
                    Msg.Alert("删除成功!", KSCMS.GetComeUrl());
                }
                else
                {
                    Msg.Alert("删除失败!", KSCMS.GetComeUrl());
                }
                return;
            default:
                Initial();
                break;
        }



    }
    private void Initial()
    {
        if (Id > 0)
        {
            using (DataTable dt = DataFactory.GetDataTable("select top 1 * from KS_UserPhotos where PicId = " +Id + " and UserID = " +__user.UserID ))
            {
                if (dt.Rows.Count > 0)
                {
                    DataRow dr = dt.Rows[0];
                    __info.PicName =  dr["Title"].ToString();
                    __info.ClassID =  dr["ClassID"].ToString();
                    __info.Tags = dr["Tags"].ToString();
                    __info.Author =  dr["Author"].ToString();
                    __info.Source = dr["Source"].ToString();
                    __info.Content =Server.HtmlDecode(dr["Content"].ToString());
                    __info.PicUrls =dr["PicUrls"].ToString();
                    __info.Fund = dr["Fund"].ToString();
                    __info.PhotoUrl = dr["PhotoUrl"].ToString();
                    __info.AddTime = dr["adddate"].ToString();

                }
                else
                {
                    Msg.Alert("error", KSCMS.GetComeUrl());
                    isLoadPage = false;
                    return;
                }
            }
        }
        else
        {
            __info.PicName = "";
            __info.ClassID = "0";
            __info.Tags = "";
            __info.Author = __user.UserName;
            __info.Source = "";
            __info.Content = "";
            __info.PicUrls = "";
            __info.Fund = "0";
            __info.PhotoUrl = "";
            __info.AddTime = DateTime.Now.ToString();
        }
    }

    /// <summary>
    /// 保存
    /// </summary>
    private void DoSave()
    {

        string title = Utils.RemoveXss(KSCMS.S("PicName"));
        string tags =  Utils.RemoveXss(KSCMS.S("Tags"));
        string author =  Utils.RemoveXss(KSCMS.S("Author"));
        string scource = Utils.RemoveXss(KSCMS.S("Source"));
        string addtime = Utils.RemoveXss(KSCMS.S("AddTime"));
        string descript = Utils.RemoveXss(KSCMS.S("Content"));

        string picUrls = Utils.RemoveXss(KSCMS.S("PicUrls"));
        string picUrl = Utils.RemoveXss(KSCMS.S("PhotoUrl"));

        int photoClass = Utils.StrToInt(KSCMS.S("photoClass"));
        int fund = Utils.StrToInt(KSCMS.S("fund"));
        if (photoClass == 0)
        {
            Msg.Alert("请选择相册所属分类！");
            return;
        }else if (string.IsNullOrEmpty(title))
        {
            Msg.Alert("标题不能为空！");
            return;
        }
        else if (picUrls == "")
        {
            Msg.Alert("请上传图片！");
            return;
        }
        else if (picUrl == "")
        {
            Msg.Alert("首页缩略图不能为空！");
            return;
        }

        Hashtable ht = new Hashtable();
        ht.Add("ClassID", photoClass);
        ht.Add("Title", title);
        ht.Add("Tags", tags);
        ht.Add("Content", descript);
        ht.Add("Source", scource);
        ht.Add("Author", author);
        ht.Add("AddDate", addtime);
        ht.Add("PhotoUrl", picUrl);
        ht.Add("PicUrls", picUrls);
        ht.Add("Fund", fund);
        ht.Add("PageSize", 0);
        ht.Add("Model", 0);

        if (Id>0)
        {
            if (CommonData.Update("KS_UserPhotos", ht, "where PicID = " + Id+" and userId="+__user.UserID))
            {
                #region 关联上传文件
                string tempContent = UtilsQueryParam.Get("__VIEWSTATE,__EVENTVALIDATION", 0);
                Kesion.APPCode.Public.FileAssociation(100010, Id, tempContent, 1);
                #endregion

                Msg.Alert("更新成功！", BasicField.GetUserSpaceUrl("space/photo"));
            }
            else
            {
                Msg.Alert("更新失败！", BasicField.GetUserSpaceUrl("space/photo"));
            }
        }
        else
        {

            ht.Add("Hit", 0);
            ht.Add("UserID", __user.UserID);
            ht.Add("UserName", __user.UserName);
            ht.Add("Status", __configinfo.BlogAlbumEnCheck);
            if (CommonData.Insert("KS_UserPhotos", ht))
            {

                #region 关联上传文件
                int maxId = CommonData.GetMaxId("KS_UserPhotos", "PicID");
                string tempContent = UtilsQueryParam.Get("__VIEWSTATE,__EVENTVALIDATION", 0);
                Kesion.APPCode.Public.FileAssociation(100010, maxId, tempContent, 0);
                #endregion
                Msg.Alert("保存成功！", BasicField.GetUserSpaceUrl("space/photo"));

            }
            else
            {
                Msg.Alert("保存失败！", BasicField.GetUserSpaceUrl("space/photo"));
            }
        }

    }
</script>

<%
    if (!isLoadPage) return;
%>

<div class="r_tybox nomar">
   
     <% if (string.IsNullOrEmpty(action))
           { %>
     <div class="r_title"><h4>我的相册管理</h4>
        <div class="padnav">
           <span><a class="btn-fix per-sccess mt-set"  href="<%=BasicField.GetUserSpaceUrl("space/photo", "do-addphoto") %>">发布照片</a></span>

        </div>
     </div>
    
	
       <div class="clear"></div>
    
        <div class="tabs">
            <ul>
            <li<%=BasicField.GetParam("showType")==""?" class='puton'":string.Empty %>><a href="<%=BasicField.GetUserSpaceUrl("space/photo") %>"><span>所有记录</span></a></li>
            <li<%=BasicField.GetParam("showType")=="1"?" class='puton'":string.Empty %>><a href="<%=BasicField.GetUserSpaceUrl("space/photo","showtype-1") %>"><span>未审核的记录</span></a></li>
            <li<%=BasicField.GetParam("showType")=="2"?" class='puton'":string.Empty %>><a href="<%=BasicField.GetUserSpaceUrl("space/photo","showtype-2") %>"><span>已审核的记录</span></a></li>
            </ul>
        </div>
        <table class="border" cellspacing="0" align="Center" border="0" style="table-layout:fixed;padding:20px;width:100%;">
			<tr class="title">
             <th scope="col" style="width:50px;">ID号</th><th scope="col">标题</th><th scope="col">添加时间</th><th scope="col">状态</th><th scope="col">↓管理操作</th>
            </tr>
        <%

            string param = "where UserID =" + __user.UserID;
            switch (Utils.StrToInt(BasicField.GetParam("showtype")))
            {
                case 1:
                    param += " and status=0";
                    break;
                case 2:
                    param += " and status=1";
                    break;
            }

            using (DataTable dt = DataFactory.GetPage("*", "KS_UserPhotos "+param, "PicID", "order by PicID desc", CurrPage, PageSize, out recordcount, out pagecount))
            {
                if (dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {

                        KSCMS.W(string.Format(@"<tr class=""tdbg""><td class=""splittd"" align=""center"">{0}</td>", dr["PicID"].ToString()));
                        KSCMS.W(string.Format(@"<td class=""splittd""><a href=""{0}"" target=""_blank"" title=""{1}""><img src=""{2}"" width=""45"" height=""45"" style=""border:1px solid #ccc;padding:1px;""/>{1}</a></td>", BasicField.GetBlogAlbumUrl(Utils.StrToInt(dr["PicID"].ToString()), dr["userid"].ToString()), dr["title"].ToString(), dr["photourl"].ToString()));
                        KSCMS.W(string.Format(@"<td class=""splittd"" style=""text-align:center"">{0}</td>", dr["status"].ToString() == "1" ? "已审核" : "<span style='color:red'>未审核</span>"));
                        KSCMS.W(string.Format(@"<td class=""splittd"" style=""text-align:center"">{0}</td>", dr["adddate"].ToString()));

                        KSCMS.W(@"<td class=""splittd"" style=""text-align:center"">");
                        KSCMS.W("<a href='" + BasicField.GetUserSpaceUrl("space/photo", "do-addphoto,id-" + dr["picID"].ToString()) + "'>修改</a>");
                        KSCMS.W(@" <a onclick=""return(confirm('确认删除吗？'))"" href='" + BasicField.GetUserSpaceUrl("space/photo", "do-del,id-" + dr["picID"].ToString()) + "'>删除</a>");
                        KSCMS.W("</td>");
                        KSCMS.W("</tr>");
                    }
                }
                else
                {
                    KSCMS.W(@"<tr class=""emptycss"">
				<td colspan=""5"">您还没有发照片!</td>
			</tr>");
                }


            }

        %>
        </table>
        <div class=""></div>
        <%
            #region 分页
            string PageStr = "[KS:PageStr2]";
            BasicField.ReplaceFilterPage(ref PageStr, CurrPage, PageSize, pagecount, recordcount);
            KSCMS.W(PageStr);
            #endregion
         %>

    	
    	 
    
    <%} else if (action == "addphoto")  //发布照片
        {
      %>
    
     <% Kesion.APPCode.EditorAPI.EchoHead();%>
      <iframe src="about:blank" style="display:none;width:0px;height:0px" name="hidiframe"></iframe>
      <form name="myform" action="<%=Utils.RemoveXss(System.Web.HttpContext.Current.Request.RawUrl) %>" method="post" id="myform" target="hidiframe">
       <input type="hidden" name="action" value="dosave"/>
<script src="../../KS_Inc/DatePicker/WdatePicker.js"></script>

    	<div class="r_title"><h4>发布照片</h4></div>
        <div class="r_padbox">
    <table width="100%" border="0" cellpadding="1" cellspacing="1" class="border" >
        <tr>
            <td align="right" class="lefttd" nowrap>所属分类：</td>
            <td class="righttd" style="text-align:left">
                <select name="PhotoClass" id="PhotoClass">
                     <option value="0">-请选择相册分类-</option>
                        <%
                            using (DataTable dt = DataFactory.GetDataTable("select * from KS_PhotoClass order by OrderID asc"))
                            {
                                foreach (DataRow dr in dt.Rows)
                                {
                                    KSCMS.W(string.Format("<option value='{0}'{2}>{1}</option>", dr["classid"].ToString(), dr["className"].ToString(), __info.ClassID == dr["classId"].ToString() ? " selected" : string.Empty));
                                }
                            }
                         %>
                            </select>
            </td>
        </tr>
         <tr>
              <td align="right" class="lefttd">图片名称：</td>
             <td class="righttd" style="text-align:left"><input type="text" name="PicName" id="PicName" value="<%=__info.PicName %>" class="textbox" maxlength="255"> * </td>
         </tr>
        <tr>
            <td align="right" class="lefttd">关 键 字：</td>
            <td class="righttd" style="text-align:left"><input type="text" name="Tags" id="Tags" value="<%=__info.Tags %>" class="textbox" maxlength="255">&nbsp; <a href="javascript:GetKeyTags();">自动获得关键字Tag</a>
                </td>
        </tr>
        <tr>
            <td align="right" class="lefttd">图片作者：</td>
            <td class="righttd" style="text-align:left"><input type="text" name="Author" id="Author" value="<%=__info.Author %>" class="textbox" maxlength="255"></td>
        </tr>
        <tr>
            <td align="right" class="lefttd">图片来源：</td>
            <td class="righttd" style="text-align:left"><input type="text" name="Source" id="Source" value="<%=__info.Source %>" class="textbox" maxlength="255"></td>
        </tr>
        <tr>
            <td align="right" class="lefttd">添加时间：</td>
            <td class="righttd" style="text-align:left"><input type="text" id="AddTime" name="AddTime" value="<%=__info.AddTime %>" readonly class="textbox" onclick="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss'});"></td>
        </tr>
        

        <tr>
            <td align="right" class="lefttd">相册介绍：</td>
            <td class="righttd" style="text-align:left">
              <textarea ID="Content" name="Content" style="width:98%;height:150px;"><%=__info.Content %></textarea>
                <%
                    Kesion.APPCode.EditorAPI.EchoEditor("editor","Content", "Basic", 0, false, true, true, false);    
               %>

            </td>
        </tr>



        <tbody id="ContentArea">
	<tr class="tdbg">
		<td class="lefttd" style="text-align:right;">具体内容：</td>
        <td class="list_right_box">
        	<table style='margin-bottom:10px; display:none;' width='80%' >
            	<tr>
                	<td><input checked type='radio' value='0' onclick="jQuery('#pagenums').hide();" name='showstyle'><img src='/sysimg/default/p0.gif' title='当图片组只有一张图片时无效,设置此样式无效!'></td>
                    <td><input type='radio' value='1' name='showstyle' onclick="jQuery('#pagenums').hide();"><img src='/sysimg/default/p1.gif' title='当图片组只有一张图片时无效,设置此样式无效!'></td>
                    <td><input type='radio' value='2' name='showstyle' onclick="jQuery('#pagenums').show();"><img src='/sysimg/default/p2.gif' title='当图片组只有一张图片时无效,设置此样式无效!'></td>
                    <td><input type='radio' value='3' name='showstyle' onclick=" jQuery('#pagenums').show();"><img src='/sysimg/default/p3.gif'></td>
                </tr>
            </table>
            <div id="pagenums" style='margin:10px;font-weight:bold;display:none'>每页显示<input type="text" name="pagenum" id="pagenum" value="12" style="text-align:center;width:30px">张</div>
		<input type="hidden"  id="hidFileMaxSize" value="<%=__configinfo.BlogAlbumFileSize %>" />
<script type="text/javascript">

                var swfu;
                var pid=0,filemaxsize = 0;
                filemaxsize = parseFloat($("#hidFileMaxSize").val());
                if (filemaxsize /1024>0){
                    filemaxsize=(filemaxsize/1024).toFixed(2)+" MB";
                }else{
                    filemaxsize=filemaxsize+" KB";
                }
       
                //删除已经上传的图片
                function DelUpFiles(pid)
                {
                    jQuery("#thumbshow"+pid).remove();
                }	
                function pic_move(obj,fx){
                    var box_d=jQuery(obj).parent().parent().parent();
                    var box_fx='';
                    if (fx==1)
                    {box_fx=box_d.prev()}
                    else if(fx==2)
                    {box_fx=box_d.next()}
                    else
                    {box_fx=''}
                    if ( box_fx.length > 0 ) {
                        if(fx==1) box_fx.before(box_d.clone())
                        if(fx==2) box_fx.after(box_d.clone())
                        if(fx==1 || fx==2)box_d.remove()
                    } 
                }
		
                function addImage(bigsrc,smallsrc,text) {
                    console.log(bigsrc);
                    var newImgDiv = document.createElement("div");
                    var delstr = '';
                    delstr = '<a href="javascript:DelUpFiles('+pid+')" style="color:#ff6600">[删除]</a>';
                    newImgDiv.className = 'thumbshow';
                    newImgDiv.id = 'thumbshow'+pid;
                    document.getElementById("thumbnails").appendChild(newImgDiv);
                    newImgDiv.innerHTML = '<a href="'+bigsrc+'" target="_blank"><span id="show'+pid+'"><img src="'+smallsrc+'" /></span></a>';
                    newImgDiv.innerHTML += '<div style="margin-top:0px;text-align:left">'+delstr+' <b>注释：</b><input type="hidden" class="pics" id="pic'+pid+'" value="'+bigsrc+'|'+smallsrc+'"/><input type="text" name="picinfo'+pid+'" value="'+text+'" style="width:150px;" class="textbox"/><span><a title="左移动排序" href="javascript:;" onclick="pic_move(this,1);">←左移动</a>&nbsp;&nbsp;&nbsp;<a title="右移动排序" href="javascript:;" onclick="pic_move(this,2);">右移动→</a></span></div>';
		
                    pid++;

                }
	

               
            </script>
	    <table>
		 <tr>
		  <td style="width:100px;"><iframe id='UpFrame' name='UpFrame' src='/plus/include/UpLoad.aspx?FieldID=-1&UpType=UpPhoto&ChannelID=19998' frameborder=0 scrolling=no width='100%' height='40'></iframe></td>
		  <td style="border-bottom:0px; font-size:12px"></td>
		 </tr>
		</table>

		<label><input class="checkbtn" type="checkbox" name="AddWaterFlag" id="AddWaterFlag" value="1"  checked="checked"/>图片添加水印</label>
        <div class="clear"></div>
		<div id="divFileProgressContainer"></div>
	    <div id="thumbnails"></div>
		<input type='hidden' name='PicUrls' id='PicUrls' value="<%=__info.PicUrls %>"/> </td>
	</tr>
</tbody>

        <tr>
            <td align="right" class="lefttd" >缩 略 图：</td>
            <td class="righttd" style="text-align:left">
                &nbsp;<input type="text" name="PhotoUrl" id="PhotoUrl" class="textbox" value="<%=__info.PhotoUrl %>" maxlength="255">
                &nbsp;<input type="button" class="button" onclick="SelectUserFiles('PhotoUrl',2);" value="选择图片" />
                
                </td>
        </tr>
        <tr style="display:none">
            <td align="right" class="lefttd">
                <strong>阅读资金：</strong></td>
            <td class="righttd" style="text-align:left">
                &nbsp;<input type="text" name="Fund" id="Fund" class="textbox"  maxlength="255" value="<%=__info.Fund %>" style="width:60px;">

            </td>
        </tr>
        <tr class="tdbg">
                    <td class="lefttd" style="border-bottom:0px;">&nbsp;</td>
                    <td style="border-bottom:0px;">
                        <div class="cz_btn">
                        	<span><input type="submit" Onclick="return(CheckForm());" ID="Button2" class="button" value="OK!确定保存" /></span>
                            <span><input type="button" onclick="location.href = '<%=BasicField.GetUserSpaceUrl("space/photo")%>';" class="button" value=" 返 回 " /></span>
                         </div>
                     </td>       
                </tr>
      </table>			


    <script type="text/javascript" >
        function GetKeyTags() {
            var text = escape(jQuery("#PicName").val());
            if (text != '') {
                jQuery("#Tags").val('请稍等,系统正在自动获取tags...').attr("disabled", true);
                    jQuery.get("/plus/ajaxs.ashx", { a: "GetTags", text: text },
				      function (data) { jQuery("#Tags").val(unescape(data)).attr("disabled", false); });
                    } else { KesionJS.Alert('对不起,请先输入相册名称!', "jQuery('#PicName').focus();"); }
            }
            jQuery(document).ready(function(){
                IniPicUrl();
            })

            function IniPicUrl(){
                var PicUrls='<%=__info.PicUrls%>';
                var PicUrlArr=null;
                if (PicUrls!='')
                { 
                    PicUrlArr=PicUrls.split('|||');
                    for ( var i=1 ;i<PicUrlArr.length+1;i++){ 
                        addImage(PicUrlArr[i-1].split('|')[1],PicUrlArr[i-1].split('|')[2],PicUrlArr[i-1].split('|')[0]);
                    }
                }
            }
        function CheckForm() {

            if (jQuery("#PhotoClass").val() == '0') {
                KesionJS.Alert('请选择相册分类!', 'jQuery("#PhotoClass").focus()');
                return false
            }

            if (jQuery("#PicName").val() == '') {
                KesionJS.Alert('请填写相册标题!', 'jQuery("#PicName").focus()');
                return false
            }

            

            jQuery('#PicUrls').val('');
            var picSrcs = '';
            var src = '';
            jQuery("#thumbnails").find(".pics").each(function () {
                src = jQuery(this).next().val().replace('|||', '').replace('|', '') + '|' + jQuery(this).val()
                if (picSrcs == '') {
                    picSrcs = src;
                } else {
                    picSrcs += '|||' + src;
                }
            });
            jQuery('#PicUrls').val(picSrcs);

            jQuery('#PicUrls').val();

            if (jQuery('#PicUrls').val() == '' && !(jQuery('#TurnUrlTF')[0].checked)) {
                KesionJS.Alert('请上传图片集!', null); return false;
            }

            if (jQuery("#PhotoUrl").val() == '') {
                KesionJS.Alert('选择缩略图!', 'jQuery("#PhotoUrl").focus()');
                return false
            }
            

            return true;
        }
        </script>

     </form>
    <%} %>
     


 </div>   