<%@ 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="Kesion.UCenter" %>
<%@ Import Namespace="Kesion.XML" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Xml" %>
<script runat="server" type="text/C#">

    dynamic __user = HttpContext.Current.Items["user"];                //初始化用户信息
    bool isLoadPage = true;  //定义页面是否加载

    public static int flag = 0;

    int recordcount, pagecount;
    int CurrPage = new BasicField().GetCurrPage;
    int PageSize = 10;

    protected void Page_Load(object sender, EventArgs e)
    {
        flag = Utils.StrToInt(KSCMS.S("flag"));
     
         if (!string.IsNullOrEmpty(KSCMS.S("ID")))
            {
                AddToFavorite();
            }

        if (KSCMS.S("action") == "cancel")
        {
            isLoadPage = false;
            RemoveFromFavorite();
            return;
        }


    }


    private void AddToFavorite()
    {
        #region 加入收藏夹
        var  IsLogin = CheckUserLogin.Check();
        if (IsLogin != "success")
        {
            Msg.AlertDoFun("登录后才能使用本功能!","top.showuserlogin();");
            return;
        }
        int InfoID = Utils.StrToInt(KSCMS.S("id"));
        int ModelID = Utils.StrToInt(KSCMS.S("modelid"));
        if (InfoID != 0)
        {
            if (!DataFactory.Exists("[KS_Favorite]", "UserName='" + __user.UserName + "' and InfoID=" + InfoID + " and ChannelID=" + ModelID))
            {
                Hashtable ht = new Hashtable();
                ht.Add("UserName", __user.UserName);
                ht.Add("InfoID", InfoID);
                ht.Add("ChannelID", ModelID);
                ht.Add("AddDate", DateTime.Now.ToString());
                CommonData.Insert("[KS_Favorite]", ht);
                UpdateFavNum(ModelID, InfoID);
            }
        }
        Msg.Alert("恭喜，加入收藏夹成功!");
        #endregion
    }

    private void UpdateFavNum(int channelId, int infoId)
    {
        #region 更新收藏数
        if (channelId != 998) //非问吧
        {
            #region 增加积分
            int favAddScore = Utils.StrToInt(MyCache.GetModelSetting(channelId, 16));
            int favAddInputerScore = Utils.StrToInt(MyCache.GetModelSetting(channelId, 17));
            int maxScorePerDay = Utils.StrToInt(MyCache.GetModelSetting(channelId,20));
            if (favAddScore > 0 || favAddInputerScore > 0)
            {
                using (DataTable dt = DataFactory.GetDataTable(string.Format("select top 1 title,inputer from {0} where infoid={1}", MyCache.GetCacheModel(channelId, 3), infoId)))
                {
                    if (dt.Rows.Count > 0)
                    {
                        string title = dt.Rows[0]["title"].ToString();
                        string inputer = dt.Rows[0]["inputer"].ToString();
                        int HasAddScore = 0;
                        int modelid = Utils.StrToInt("-3333" + channelId);
                        if (maxScorePerDay > 0)
                        {
                            HasAddScore = Utils.StrToInt(DataFactory.GetOnlyValue("select sum(score) from KS_LogScore Where InOrOutFlag=1 and ChannelID=" + modelid + " and year(AddDate)=" + DateTime.Now.Year + " and month(AddDate)=" + DateTime.Now.Month + " and day(AddDate)=" + DateTime.Now.Day));
                        }
                        if (HasAddScore < maxScorePerDay || maxScorePerDay == 0)  //未达到一天允许增加的积分数，才继续
                        {
                            if (favAddScore > 0 && new TemporaryVar().UserName != inputer)
                            {
                                #region 收藏文档赠送会员积分
                                if (!DataFactory.Exists("KS_LogScore", "InOrOutFlag=1 and ChannelID=" + modelid + " and infoid=" + infoId + " and username='" + new TemporaryVar().UserName + "'"))
                                {
                                    Charge.ScoreInOrOut(modelid, infoId, new TemporaryVar().UserID, 1, favAddScore, "system", "对文档[" + title + "]进行收藏奖励！");
                                }
                                #endregion
                            }
                            if (favAddInputerScore > 0 && inputer != new TemporaryVar().UserName)
                            {
                                #region 投稿的文章被赞加积分
                                string remark = "您发表的文档[" + title + "]被用户[" + new TemporaryVar().UserName + "]收藏奖励！";
                                if (!DataFactory.Exists("KS_LogScore", "ChannelID=" + modelid + " and infoid=" + infoId + " and username='" + inputer + "' and remark='" + remark + "'"))
                                {
                                    if (DataFactory.Exists("KS_Admin", "username='" + inputer + "'") == false && DataFactoryUser.Exists("KS_User", "username='" + inputer + "'"))  //非管理员发的稿件才赠送积分
                                    {
                                        Charge.ScoreInOrOut(modelid, infoId, new TemporaryVar().UserID, 1, favAddInputerScore, "system", remark);
                                    }
                                }
                                #endregion
                            }
                        }


                    }
                }
            }
            #endregion

            int favNum = Utils.StrToInt(DataFactory.GetOnlyValue("select count(1) From KS_Favorite Where ChannelID=" + channelId + " and infoid=" + infoId));
            if (channelId == -5)
            {
                DataFactory.ExecuteNonQuery("Update KS_ProFightGroup Set FavNum=" + favNum + " WHERE ID=" + infoId);
            }
            else
            {
                if (MyCache.GetCacheModel(channelId, 4) == "4")
                {
                    DataFactory.ExecuteNonQuery("Update KS_ProductList Set FavNum=" + favNum + " WHERE InfoID=" + infoId);
                    DataFactory.ExecuteNonQuery("Update " + MyCache.GetCacheModel(channelId, 3) + " Set FavNum=" + favNum + " WHERE InfoID=" + infoId);
                }
                else
                {
                    DataFactory.ExecuteNonQuery("Update KS_InfoList Set FavNum=" + favNum + " WHERE InfoID=" + infoId);
                    DataFactory.ExecuteNonQuery("Update " + MyCache.GetCacheModel(channelId, 3) + " Set FavNum=" + favNum + " WHERE InfoID=" + infoId);

                }
            }
        }
        #endregion
    }

    private void RemoveFromFavorite()
    {
        #region 取消收藏
        if (KSCMS.S("ids") != "")
        {
            string ids = Utils.FilterIDs(KSCMS.S("ids"));

            using(DataTable dt=DataFactory.GetDataTable("select * From [KS_Favorite] Where ID in("+ids+")"))
            {
                if (dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        int channelId = Utils.StrToInt(dr["channelid"].ToString());
                        if (dr["channelId"].ToString() != "998") //非问吧
                        {
                            #region 没有在规定的时间内取消收藏扣积分
                            DateTime addDate = Convert.ToDateTime(dr["adddate"].ToString());
                            string userName = dr["username"].ToString();
                            int FavScoreLimitTime = Utils.StrToInt(MyCache.GetModelSetting(channelId, 18));
                            int FavDelScore = Utils.StrToInt(MyCache.GetModelSetting(channelId, 19));
                            int modelid = Utils.StrToInt("-3333" + channelId);
                            if (FavScoreLimitTime > 0 && FavDelScore > 0)
                            {
                                if (addDate.AddHours(FavScoreLimitTime) > DateTime.Now)
                                {
                                    if (!DataFactory.Exists("KS_LogScore", "InOrOutFlag=2 and ChannelID=" + modelid + " and infoid=" + Utils.StrToInt(dr["infoId"].ToString()) + " and username='" + new TemporaryVar().UserName + "'"))
                                    {
                                        using (DataTable dtt = DataFactory.GetDataTable(string.Format("select top 1 title,inputer from {0} where infoid={1}", MyCache.GetCacheModel(channelId, 3), dr["infoId"].ToString())))
                                        {
                                            if (dtt.Rows.Count > 0)
                                            {
                                                string title = dtt.Rows[0]["title"].ToString();
                                                Charge.ScoreInOrOut(modelid, Utils.StrToInt(dr["infoId"].ToString()), new TemporaryVar().UserID, 2, FavDelScore, "system", "文档[" + title + "]没有在规定的时间内取消收藏扣除！");

                                            }
                                        }
                                    }
                                }
                            }
                            #endregion
                        }

                        Hashtable ht = new Hashtable();
                        ht.Add("id", dr["id"].ToString());
                        CommonData.Delete("[KS_Favorite]", ht);
                        UpdateFavNum(Utils.StrToInt(dr["channelid"].ToString()), Utils.StrToInt(dr["infoid"].ToString()));
                    }
                }
            }

        }

        Response.Redirect(BasicField.GetUserUrl("other/favorite","flag-"+KSCMS.S("flag")));
        #endregion
    }

    public static string GetPhoto(string photourl)
    {
        if (string.IsNullOrEmpty(photourl))    photourl = "../sysimg/nopic.gif";
        return photourl;
    }
    public static string GetSubject(int ChannelID,int ClassID,int InfoID,string FileName,string TurnUrl, string Subject)
    {
        string TitleStr;
        TitleStr = string.Format("<a href='{1}' target='_blank'>{0}</a>",Subject,Kesion.HtmlTags.BasicField.GetItemUrl(ChannelID,ClassID,InfoID,FileName,TurnUrl));
        return TitleStr;
    }
    public static string GetAddTime(DateTime Time)
    {
        return Utils.FormatHumanizedTime(Time);

    }

</script>
<%
    if (!isLoadPage) return;
%>

 <div class="r_tybox nomar">
<div class="r_title"><h4>收藏管理</h4>
 <div class="tabs">
     <ul>
        <ul>
              <%if (BaseFun.CheckModulePower("edu"))
             { %>
               <li><a href='<%=BasicField.GetUserUrl("other/mycollect", "optype-cos") %>'>课程收藏</a> </li>
              <li><a href='<%=BasicField.GetUserUrl("other/mycollect") %>'>教师收藏</a></li>
              <%}
                  if (BaseFun.CheckModulePower("plus.group"))
                  {%>
              <li><a href='<%=BasicField.GetUserUrl("other/mycollect", "optype-group") %>'>小组收藏</a></li>
                  <%
               }
               if (BaseFun.CheckModulePower("exam"))
                { %>
              <li><a href='<%=BasicField.GetUserUrl("other/mycollect", "optype-sj") %>'>试卷收藏</a></li>
                 <%} %>
         <li><a href="<%=BasicField.GetUserUrl("other/mycollect","optype-article") %>">内容收藏</a></li>
              <%if (BaseFun.CheckModulePower("plus.ask"))
                  { %>
             <li class='puton'><a href='<%=BasicField.GetUserUrl("other/favorite","flag-1") %>'>问题收藏</a></li>
                 <%} %>
         
     </ul>
       </div>

</div>
        
    	<div class="clear"></div>
        <div class="tips" style="padding-left:30px">这里显示的是您感兴趣的信息，对收藏已久没有价值的信息您可以进行取消收藏操作！</div>
        <form name="myform" action="{$GetCurrUrl}" method="post" id="myform">
        <input type="hidden" name="action" value="cancel"/>


        <%
            if (KSCMS.S("flag") != "1")
            {
              %>
             <table id="tablist" width="100%" border="0" align="center" cellpadding="2" cellspacing="1" class="border">
              <tr class="title">
        	        <td width="50" align="center">选择</td>
        	        <td width="110" align="center"> 图片</td>
                    <td align="center"> 标题 </td>
                    <td width="100" align="center">收藏时间 </td>
	                <td align="center" width="70">操作</td>
                </tr>
     <%
         string selectField = string.Empty;
         string modelTable = string.Empty;
         string param = string.Empty;
         string key = string.Empty;
         if (KSCMS.S("flag") == "3")
         {
             selectField = "f.id,subject,ClassID,PhotoUrl defaultPic,F.AddDate,I.AddDate As PubDate,I.ClassID,I.Id as InfoID,singleprice,FightGroupPrice";
             param = "[KS_ProFightGroup] I Inner Join [KS_Favorite] F On I.ID=F.InfoID Where f.ChannelID=-5 and F.UserName='" + Utils.ChkSQL(__user.UserName) + "'";
             key = "I.id";
         }
         else
         {
             if (KSCMS.S("flag") == "2")
             {
                 selectField = "id,title,ClassID,defaultPic,F.AddDate,I.hits,I.AddDate As PubDate,I.ClassID,I.InfoID,I.ChannelID,I.FileName,I.TurnUrl,I.Price_Member,I.Price";
                 modelTable = "KS_ProductList";

             }

             else
             {
                 selectField = "id,title,ClassID,defaultPic,F.AddDate,I.hits,I.AddDate As PubDate,I.ClassID,I.InfoID,I.ChannelID,I.FileName,I.TurnUrl,1 as price_member,2 as price";
                 modelTable = "KS_InfoList";

             }
             key = "I.infoid";
             param = "[" + modelTable + "] I Inner Join [KS_Favorite] F On I.InfoID=F.InfoID Where i.channelid=f.channelid and F.UserName='" + Utils.ChkSQL(__user.UserName) + "'";
         }
         using (DataTable dt = DataFactory.GetPage(selectField, param, key, "order by F.AddDate desc", CurrPage, PageSize, out recordcount, out pagecount))
         {
             if (dt.Rows.Count > 0)
             {
                 foreach(DataRow dr in dt.Rows)
                 {
                     KSCMS.W(@"<tr class=""tdbg"">
                      <td class=""splittd"" align=""center""><input type=""checkbox"" name=""ids"" value=""" + dr["ID"].ToString() + @""" /></td>
                      <td class=""splittd"" align=""center""><img width=""102"" height=""79"" onerror=""this.src='/sysimg/nopic.gif'"" src=""" + GetPhoto(Convert.ToString(dr["DefaultPic"].ToString())) + @""" /></td>
                      <td class=""splittd"">" +
                  (KSCMS.S("flag") == "3" ? dr["subject"].ToString() : GetSubject(Convert.ToInt16(dr["ChannelID"].ToString()), Utils.StrToInt(dr["ClassID"].ToString()), Utils.StrToInt(dr["InfoID"].ToString()), Convert.ToString(dr["FileName"].ToString()), Convert.ToString(dr["TurnUrl"].ToString()), Convert.ToString(dr["Title"].ToString()))) + @"
                      <div style=""margin-top:10px;color:#999999;"">
                      分类:" + MyCache.GetCacheClass(Convert.ToInt32(dr["ClassID"].ToString()), 1) + @"&nbsp;&nbsp;
                      发布时间:" + GetAddTime(Convert.ToDateTime(dr["PubDate"].ToString())) + @"&nbsp;&nbsp;" + (KSCMS.S("flag") == "3" ? "" : "点击数:" + dr["Hits"].ToString() + "人次") +
                    (KSCMS.S("flag") == "3" ? "单买价：<span style='text-decoration:line-through'>￥" + Utils.StrToFloat(dr["singleprice"].ToString()).ToString("F2") + @"元</span> &nbsp;&nbsp;拼团价：<span style='color:#ff3300;font-weight:bold'>￥" + Utils.StrToFloat(dr["FightGroupPrice"].ToString()).ToString("F2") + "元" : KSCMS.S("flag") == "2" ? "市场价：<span style='text-decoration:line-through'>￥" + Utils.StrToFloat(dr["price"].ToString()).ToString("F2") + "元</span> &nbsp;&nbsp;商城价：<span style='color:#ff3300;font-weight:bold'>￥" + Utils.StrToFloat(dr["price_member"].ToString()).ToString("F2") + "元" : "") + @"</span>
                      </div>
                      </td>

                      <td class=""splittd"" align=""center"">
                      <span style=""color:#ff6600;"">" +
                Utils.FormatHumanizedTime(Convert.ToDateTime(dr["AddDate"].ToString())) + @"
                      </span>
                      </td>
                      <td class=""splittd"" align=""center"">" +
                       (KSCMS.S("flag") == "2" ? @"<a href=""/?c=mall&a=orderinfo&newwin=1&id=" + dr["InfoID"].ToString() + @""" class=""deletebtn"" target=""_blank"">购买</a>" : "") + @"
                           <a href=""javascript:;"" class=""deletebtn"" onclick=""$.dialog.confirm('确定取消该收藏吗?',function(){ location.href='" + BasicField.GetUserUrl("other/Favorite", "flag-" + Utils.StrToInt(KSCMS.S("flag")) + ",action-cancel,ids-" + dr["ID"].ToString()) + @"'; },function(){});"">取 消</a>
          
                      </td>
       
                  </tr> ");

                 }
             }
             else
             {
                 KSCMS.W(@" <tr class=""tdbg emptycss"">
                        <td class=""splittd empty"" style=""text-align:center"" colspan=""10"">
                          您还没有收藏任何信息哦！
                        </td>
                   </tr> ");

             }
         }
             %>
              </table>
             <%
            }
            else if (flag==1)  //问吧
            {%>

     <table id="tablist" width="100%" border="0" align="center" cellpadding="2" cellspacing="1" class="border">
      <tr class="title">
        	<td width="50" align="center">选择</td>
            <td align="center">问题</td>
            <td width="100" align="center">收藏时间 </td>
            <td align="center">是否解决</td>
            <td align="center" nowrap>悬赏分</td>
	        <td align="center" width="70">操作</td>
        </tr>
       <%
           using (DataTable dt = DataFactory.GetPage("f.id,topicid,i.title,i.reward,i.verify,i.issolve,i.ClassID,F.AddDate,I.hits,I.AddDate As PubDate", "[KS_AskTopic] I Inner Join [KS_Favorite] F On I.TopicID=F.InfoID Where F.UserName='" + Utils.ChkSQL((new TemporaryVar()).UserName) + "'", "I.topicid", "order by F.AddDate desc,I.TopicID", CurrPage, PageSize, out recordcount, out pagecount))
           {
               if (dt.Rows.Count > 0)
               {
                   foreach(DataRow dr in dt.Rows)
                   {
                       KSCMS.W(@"<tr class=""tdbg"">
          <td class=""splittd"" align=""center""><input class=""cleckbtn"" type=""checkbox"" name=""ids"" value=""" + dr["ID"].ToString() + @""" /></td>
          <td class=""splittd"" style=""text-align:left"">
            <a href=""" + BaseFun.GetRewriteUrl("askview", Convert.ToInt32(dr["TopicID"].ToString())) + @""" target=""_blank"">" + dr["Title"].ToString() + @"</a>
           <div class=""tips2"">提问时间：" + Utils.FormatHumanizedTime(Convert.ToDateTime(dr["PubDate"].ToString())) + @" 是否审核：" + (Convert.ToString(dr["verify"].ToString()) == "1" ? "<span style='color:green'>已审核</span>" : "<span style='color:red'>未审核</span>") + @" 分类：" + MyCache.GetCacheAskCategory(Convert.ToInt32(dr["ClassID"].ToString()), "classname") + @"</div>
           
          </div>
          </td>
          <td class=""splittd"" align=""center"">
          <span style=""color:#ff6600;"">" + Utils.FormatHumanizedTime(Convert.ToDateTime(dr["AddDate"].ToString())) + @"
          </span>
          </td> 
          <td class=""splittd"" style=""text-align:center"">" + (Convert.ToString(dr["IsSolve"].ToString()) == "1" ? "<span style='color:green'>已解决</span>" : Convert.ToInt16(dr["IsSolve"].ToString()) == 2 ? "已关闭" : "<span style='color:red'>未解决</span>") + @"</td>
          <td class=""splittd"" style=""text-align:center""><font color=red>" + Convert.ToSingle(Convert.ToString(dr["reward"].ToString())).ToString() + @"
</font> 分</td>
          <td class=""splittd"" align=""center"">
          <a href=""javascript:;"" class=""deletebtn"" onclick=""$.dialog.confirm('确定取消该收藏吗?',function(){ location.href='" + BasicField.GetUserUrl("other/Favorite", "flag-1,action-Cancel,ids-" + dr["ID"].ToString()) + @"';},function(){});"">取 消</a>
          </td>
       
      </tr> ");
                   }
               }else
               {
                   KSCMS.W(@" <tr class=""tdbg emptycss"">
                        <td class=""splittd empty"" style=""text-align:center"" colspan=""10"">
                          您还没有收藏任何问题哦！
                        </td>
                   </tr> ");
               }
           }
       %>
     

    
    </table>
         <%
            }
         %>
        <div class="r_padbox nopadtop">
            <div class="clear"></div>
            <div class="cz_btn">
                <span class="mt5"><input type="checkbox" name="chkall" id="chkall" onclick="CheckAll(this.form);"/>全选&nbsp;</span>
                <span><input type="submit" ID="btnDelete" class="button green-bt bt-auto" onmousedown="return(GetIDS());"  value="取消选中的收藏" style="width:auto;padding:0 10px" /></span>
             </div>
	    </div>
</form>

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