<%@ Control Language="C#" %>
<%@ Import Namespace="Kesion.Cache" %>
<%@ Import Namespace="Kesion.Publics" %>
<%@ Import Namespace="Kesion.BLL" %>
<%@ Import Namespace="Kesion.HtmlTags" %>
<%@ Import Namespace="System.Data" %>
<script runat="server" type="text/C#">

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

    string action = string.Empty;
    int recordcount, pagecount;
    int CurrPage = new BasicField().GetCurrPage;
    int PageSize = 6;

    private static int flag = 0;

    protected void Page_Load(object sender, EventArgs e)
    {

        action = KSCMS.S("action");
        flag = Utils.StrToInt(KSCMS.S("flag"));

        switch (action)
        {
            case "doaddcoupon":
                isLoadPage = false;
                DoAddCoupon();
                return;
            default:
                break;
        }


    }
    /// <summary>
    /// 限制使用范围
    /// </summary>
    /// <param name="RangeType"></param>
    /// <param name="limitType"></param>
    /// <param name="limitProIds"></param>
    /// <param name="limitClassIds"></param>
    /// <returns></returns>
    public string GetLimitTips(int RangeType,int limitType,string limitProIds,string limitClassIds)
    {
        #region 限制使用范围
        string str = string.Empty;
        if (RangeType == 1)//网授
        {
            switch (limitType)
            {
                case 1:
                    if (!string.IsNullOrEmpty(limitClassIds))
                    {
                        using (DataTable dt = DataFactory.GetDataTable("select classid,classname from KS_CosClass Where classId in(" + Utils.FilterIDs(limitClassIds) + ")"))
                        {
                            if (dt.Rows.Count > 0)
                            {
                                foreach (DataRow dr in dt.Rows)
                                {
                                    str += "<li><a href='" + BasicField.GetRewriteUrl("courselist",Utils.StrToInt(dr[0].ToString())) + "' target='_blank'>" + dr[1].ToString() + "</a></li>";

                                }
                            }
                        }
                    }
                    str = @" <p><span class=""used_info_tj"">使用限制</span>(仅限以下网授课程分类)：</p><ul>" + str + "</ul>";
                    break;
                case 2:
                    if (!string.IsNullOrEmpty(limitProIds))
                    {
                        using (DataTable dt = DataFactory.GetDataTable("select courseid,name,teachway from KS_Course Where courseid in(" + Utils.FilterIDs(limitProIds) + ")"))
                        {
                            if (dt.Rows.Count > 0)
                            {
                                foreach (DataRow dr in dt.Rows)
                                {
                                    str += string.Format("<li><a href='{0}' target='_blank'>{1}</a></li>", BasicField.GetCourseUrl(Utils.StrToInt(dr["courseid"].ToString()),Utils.StrToInt(dr["teachway"].ToString())),dr["name"].ToString());
                                }
                            }
                        }
                    }
                    str = @" <p><span class=""used_info_tj"">使用限制</span>(仅限以下网授课程)：</p></p><ul>" + str + "</ul>";
                    break;
                default:
                    str = @" <p><span class=""used_info_tj"">无限制</span></p>";
                    break;

            }

        }
        else if (RangeType == 2)
        {

            switch (limitType)
            {
                case 1:
                     if (!string.IsNullOrEmpty(limitClassIds))
                    {
                        using (DataTable dt = DataFactory.GetDataTable("select classid,classname from KS_CosClass Where classId in(" + Utils.FilterIDs(limitClassIds) + ")"))
                        {
                            if (dt.Rows.Count > 0)
                            {
                                foreach (DataRow dr in dt.Rows)
                                {
                                    str += "<li><a href='" + BasicField.GetRewriteUrl("facelist",Utils.StrToInt(dr[0].ToString()))  + "' target='_blank'>" + dr[1].ToString() + "</a></li>";

                                }
                            }
                        }
                    }
                    str = @" <p><span class=""used_info_tj"">使用限制</span>(仅限以下面授课程分类)：</p><ul>" + str + "</ul>";
                    break;
                case 2:
                     if (!string.IsNullOrEmpty(limitProIds))
                    {
                        using (DataTable dt = DataFactory.GetDataTable("select courseid,name,teachway from KS_CourseFace Where courseid in(" + Utils.FilterIDs(limitProIds) + ")"))
                        {
                            if (dt.Rows.Count > 0)
                            {
                                foreach (DataRow dr in dt.Rows)
                                {
                                    str += string.Format("<li><a href='{0}' target='_blank'>{1}</a></li>", BasicField.GetCourseUrl(Utils.StrToInt(dr["courseid"].ToString()),Utils.StrToInt(dr["teachway"].ToString())) , dr["name"].ToString());
                                }
                            }
                        }
                    }
                     str = @" <p><span class=""used_info_tj"">使用限制</span>(仅限以下面授课程)：</p></p><ul>" + str + "</ul>";
                    break;
                default:
                    str = @" <p><span class=""used_info_tj"">无限制</span></p>";
                    break;

            }



        }
        else if (RangeType == 3)
        {
            switch (limitType)
            {
                case 1:
                    if (!string.IsNullOrEmpty(limitClassIds))
                    {
                        using (DataTable dt = DataFactory.GetDataTable("select classid,classname from KS_Class Where classId in(" + Utils.FilterIDs(limitClassIds) + ")"))
                        {
                            if (dt.Rows.Count > 0)
                            {
                                foreach (DataRow dr in dt.Rows)
                                {
                                    str += "<li><a href='" + MyCache.GetClassUrl(Utils.StrToInt(dr[0].ToString())) + "' target='_blank'>" + dr[1].ToString() + "</a></li>";

                                }
                            }
                        }
                    }
                    str = @" <p><span class=""used_info_tj"">使用限制</span>(仅限以下分类)：</p><ul>" + str + "</ul>";
                    break;
                case 2:
                    if (!string.IsNullOrEmpty(limitProIds))
                    {
                        using (DataTable dt = DataFactory.GetDataTable("select infoid,classid,channelid,turnurl,title,filename from KS_ProductList Where infoid in(" + Utils.FilterIDs(limitProIds) + ")"))
                        {
                            if (dt.Rows.Count > 0)
                            {
                                foreach (DataRow dr in dt.Rows)
                                {
                                    str += string.Format("<li><a href='{0}' target='_blank'>", Kesion.HtmlTags.BasicField.GetItemUrl(dr)) + dr["title"].ToString() + " </a></li>";
                                }
                            }
                        }
                    }
                    str = @" <p><span class=""used_info_tj"">使用限制</span>(仅限以下商品)：</p></p><ul>" + str + "</ul>";

                    break;
                default:
                    str = @" <p><span class=""used_info_tj"">使用限制</span></p><ul><li>无限制</li></ul>";
                    break;
            }
        }else
        {
            str = @" <p><span class=""used_info_tj"">使用限制</span></p><ul><li>无限制</li></ul>";
        }
        return str;
        #endregion
    }

    /// <summary>
    /// 添加优惠券
    /// </summary>
    private void DoAddCoupon()
    {
        var couponNum = Utils.ChkSQL(KSCMS.S("CouponNum"));
        if (string.IsNullOrEmpty(couponNum))
        {
            Msg.Alert("对不起，请输入优惠券号!",KSCMS.GetComeUrl());
            return;
        }

        using (DataTable dt = DataFactory.GetDataTable("select top 1 * From KS_ProCouponUser Where CouponNum='" + couponNum + "'"))
        {
            if (dt.Rows.Count > 0)
            {
                DataRow dr = dt.Rows[0];
                if (!string.IsNullOrEmpty(dr["username"].ToString()))
                {
                    Msg.Alert("对不起，该优惠券已被添加!", KSCMS.GetComeUrl());
                    return;
                }
                else
                {
                    Hashtable ht = new Hashtable();
                    ht.Add("username", (new TemporaryVar()).UserName);
                    CommonData.Update("KS_ProCouponUser", ht, "Where CouponNum='" + couponNum + "'");
                    DataFactory.ExecuteNonQuery("update KS_ProCouponUser set IsExtend=1 where CouponNum='" + couponNum + "'");
                    Msg.Alert("恭喜，优惠券添加成功!", KSCMS.GetComeUrl());

                }

            }
            else
            {
                Msg.Alert("对不起，您输入的优惠券不存在!", KSCMS.GetComeUrl());
                return;

            }
        }
    }

</script>
<%
    if (!isLoadPage) return;
%>
  <div class="r_tybox t_tybox  nomar disting">
      <div class="r_title tytitle">
         <h4 class="float-none disting_show">
              <%if (Utils.StrToInt(KSCMS.S("flag")) == 0 || Utils.StrToInt(KSCMS.S("flag")) == 3)
                      {
                          Response.Write("优惠券/红包");
                      }
                      else
                      {
                      Response.Write("我的预约码");
                      }
                %>
            </h4>


      </div>

       <div class="top-sort clearfix">
          <div class="top-sort-tab ">  
            <ul>
                <%if (Utils.StrToInt(KSCMS.S("flag")) == 0 || Utils.StrToInt(KSCMS.S("flag")) == 3)
                    { %>
                <li<%=KSCMS.S("flag") == "" ? " class='puton'" : string.Empty %>><a href="<%=BasicField.GetUserUrl("basic/MyCoupon") %>">我的优惠券</a></li>
                <li<%=KSCMS.S("flag") == "3" ? " class='puton'" : string.Empty %>><a href="<%=BasicField.GetUserUrl("basic/MyCoupon", "flag-3") %>">我的红包</a></li>
                    <%} %>
              <%if (BaseFun.CheckModulePower("mall") && (Utils.StrToInt(KSCMS.S("flag"))==1 || Utils.StrToInt(KSCMS.S("flag"))==2))
                  { %>
                <li<%=KSCMS.S("flag") == "2" ? " class='puton'" : string.Empty %>><a href="<%=BasicField.GetUserUrl("basic/MyCoupon", "flag-2") %>">我的预约码</a></li>
                <li<%=KSCMS.S("flag") == "1" ? " class='puton'" : string.Empty %>><a href="<%=BasicField.GetUserUrl("basic/MyCoupon", "flag-1") %>">预约码申请</a></li>
              <%} %>
            </ul>
         </div> 
        </div>  
      <%
          if (flag == 0)
          {
              string param = "KS_ProCouponUser a inner join KS_ProCoupon b on a.couponid=b.couponid Where status=1 and CouponType=2 and a.UserName='" + (new TemporaryVar()).UserName + "'";
              DataTable dt = DataFactory.GetPage("a.*,b.couponname,b.enddate,b.facevalue,b.minamount,b.maxdiscount,b.limittype,b.limitClassIDs,b.limitProids,b.rangeType", param, "couponuserid", "order by couponuserid desc", CurrPage, PageSize, out recordcount, out pagecount);

       %>
    

         <script>
       function check() {
           if ($("#CouponNum").val() == '') {
               $.dialog.alert('请输入优惠券号!', function() {
                   $("#CouponNum").focus();
               });
           return false;
       }
       return true;
       }
   </script>
   <form name="myform" action="{$GetCurrUrl}" method="post" id="myform">
       <input type="hidden" name="action" value="doaddcoupon"/>
       <table width="100%" border="0" cellpadding="0" cellspacing="0" class="border"> 
              <tr class="tdbg">
                  <td class="lefttd" height="30" style="text-align:left">&nbsp;&nbsp;&nbsp;&nbsp;<strong>添加优惠券</strong> 券号: 
                      <input type="text" name="CouponNum" id="CouponNum" class="textbox" />
                       <span style="color:Red">*</span>
                       
                       <div style="padding:10px 0 0 120px"><input type="submit" id="BtnAddCoupon" onclick="return(check());" class="button" value="确定添加"  /></div>
                  </td>
              
              </tr>
        </table>
    </form>
    <div style="height:30px"></div>

   <%
       if (dt.Rows.Count > 0)
       {
           var i = 0;
           foreach (DataRow dr in dt.Rows)
           {
                   %>
                     <div class="coupon_box">
                          <div class="coupon_bd cp-bg-<%=i + 1 %>">
                              <div class="coupon_upper">
                                   <div class="cp_price fl"><sup><i class="rmb">￥</i></sup><%=Math.Round(Convert.ToDecimal(dr["facevalue"].ToString()), 2)%></div>
                                   <div class="clear"></div>
                                   <div class="cp_info">
                                     <p><span>名称：</span><%=dr["couponname"].ToString() %></p>
                                     <p><span>优惠券号：</span><%=dr["couponnum"].ToString() %></p>
                                     <p><span>截止时间：</span><%=Convert.ToDateTime(dr["enddate"].ToString()).ToShortDateString() %></p>
                                     <p><span>使用情况：</span><%=Convert.ToString(dr["useflag"].ToString()) == "1" ? (Math.Round(Convert.ToDecimal(dr["availablemoney"].ToString()), 2) > 0 ? "已使用，未用完" : "已用完") + ("<a style=\'color:blue\' href='javascript:;' onclick=\"KesionJS.Alert('<div class=tips>" + dr["note"].ToString() + "</div>');\" >（详情）</a>") : "未使用"%></p>  
                                   </div>
                       
                                </div>
                                <div class="used_info">
                                   <%=GetLimitTips(Utils.StrToInt(dr["rangeType"].ToString()), Convert.ToInt16(dr["limitType"].ToString()), dr["limitProIds"].ToString(), dr["limitClassIds"].ToString()) %>
                                </div>
                          </div>
                  </div>
    <%
                    i++;
                }
            }
            else
            {
                KSCMS.W(@"<div class=""empty"">没有可用的优惠券！</div><style>.cz_btn{display:none;}</style>");
            }
        }
        else if (flag == 3)  //红包
        {
            PageSize = 8;
            string param = "KS_ProCouponUser a inner join KS_ProCoupon b on a.couponid=b.couponid Where status=1 and CouponType=1 and a.UserName='" + (new TemporaryVar()).UserName + "'";
            DataTable dt = DataFactory.GetPage("a.*,b.couponname,b.enddate,b.facevalue,b.minamount,b.maxdiscount,b.limittype,b.limitClassIDs,b.limitProids,b.rangeType", param, "couponuserid", "order by couponuserid desc", CurrPage, PageSize, out recordcount, out pagecount);

    %>
    <div class="top_c_sc top_c_po">
      <span>共有：<%=recordcount %> 张红包</span>
   </div>
      <%
          if (dt.Rows.Count > 0)
          {
              var i = 0;
              foreach (DataRow dr in dt.Rows)
              {
           %>
            <div class="packet_item">
              <div class="packet_bd">
                  <div class="packet_upper">
                       <div class="cp_price"><i class="rmb">￥</i><%=Math.Round(Convert.ToDecimal(dr["facevalue"].ToString()), 2)%><span class="num"><%=dr["couponnum"].ToString() %></span></div>
                       <div class="clear"></div>
                       <div class="cp_info">
                         <p class="bt"><%=dr["couponname"].ToString() %></p>
                         <p><%= Convert.ToDateTime(dr["enddate"].ToString()).ToShortDateString() %> 到期</p>
                         <p><%= Convert.ToString(dr["useflag"].ToString()) == "1" ? (Math.Round(Convert.ToDecimal(dr["availablemoney"].ToString()), 2) > 0 ? "已使用，未用完" : "已用完") + ("<a style=\'color:blue\' href='javascript:;' onclick=\"KesionJS.Alert('<div class=tips>" + dr["note"].ToString() + "</div>');\" >（详情）</a>") : "<font color=#999999>未使用</font>"%></p>
                       </div>
                      
                    </div>
                    <div class="box_b">                                  
                         <%=GetLimitTips(Utils.StrToInt(dr["rangeType"].ToString()),Convert.ToInt16(dr["limitType"].ToString()), dr["limitProIds"].ToString(), dr["limitClassIds"].ToString()) %>
                    </div>
              </div>

          </div>
    <%
                i++;
            }
        }
        else
        {
            KSCMS.W(@"<div class=""empty"">没有可用的红包！</div>");
        }
      %>
      <%}
          else if (flag == 1)  //预约码申请
          {
              DataTable dt = DataFactory.GetPage("*", "KS_ProBookCodeType", "TypeID", "order by TypeID desc", CurrPage, PageSize, out recordcount, out pagecount);
              %>
          <div class="top_c_sc">
            <span>共有：<%=recordcount %> 张预约码</span>
           </div>
           <table id="tablist1" width="100%" border="0" align="center" cellpadding="0" cellspacing="0" class="border">
              <tr align="center" class="title">
              	<td>分类ID</td>
              	<td>分类名称</td>
              	<td>有效使用时间</td>
              	<td>开放申请</td>
                  <td>是否可申请</td>
              	<td>申请</td>        	
              </tr>
                <%
                    if (dt.Rows.Count > 0)
                    {
                        var i = 0;
                        foreach (DataRow dr in dt.Rows)
                        {
           %>
             <tr class="tdbg">
          <td class="splittd" align="center" nowrap><%=dr["TypeID"].ToString() %></td>
          <td class="splittd" align="left" nowrap> <img src='<%=dr["DefaultPic"].ToString() %>' width="45" height="45"/> <%=dr["TypeName"].ToString() %> </td>
          <td class="splittd" align="center" nowrap><%=Convert.ToDateTime(dr["BeginDate"].ToString()).ToShortDateString() %>--<%=Convert.ToDateTime(dr["EndDate"].ToString()).ToShortDateString()  %></td>
          <td class="splittd" align="center" nowrap><font color="green"><%=Convert.ToString(dr["IsOpenApply"].ToString()) == "1" ? "是" : "否" %></font></td>
           <td class="splittd" align="center" nowrap><%=Convert.ToDateTime(DateTime.Now) >= Convert.ToDateTime(dr["BeginDate"].ToString()) & Convert.ToDateTime(DateTime.Now) <= Convert.ToDateTime(dr["EndDate"].ToString()) ? "<font color='blue'>是</font>" : "<font color='red'>否</font>"%></td>
          <td class="splittd" align="center" ><%=Convert.ToDateTime(DateTime.Now) >= Convert.ToDateTime(dr["BeginDate"].ToString()) & Convert.ToDateTime(DateTime.Now) <= Convert.ToDateTime(dr["EndDate"].ToString()) ? "<a class='apply'  href='" + Kesion.HtmlTags.BasicField.GetRewriteUrl("bookcodeapply", Utils.StrToInt(dr["TypeID"].ToString())) + "' title='申请预约码地址URL' target='_blank'>申请</a>" : "---" %></td>          
      </tr>  
    <%
                i++;
            }
        }
        else
        {
            KSCMS.W(@"<tr class=""tr-nobor""><td colspan=""7""><div class=""empty"">没有申请预约码的记录！</div></td></tr><style>.cz_btn{display:none;}</style></tr>");
        }
      %>
     </table>

          <%} else if (flag==2) {  //我的预约码
                  string param = "KS_ProBookCodeType a inner join KS_ProBookCode b on a.typeid=b.typeid Where  b.UserName='" + (new TemporaryVar()).UserName + "'";
                  DataTable dt = DataFactory.GetPage("a.*,b.*", param, "ID", "order by ID desc", CurrPage, PageSize, out recordcount, out pagecount);
            %>
          <div class="top_c_sc">
            <span>共有：<%=recordcount %> 张预约码</span>
           </div>
          <table id="tablist2" width="100%" border="0" align="center" cellpadding="0" cellspacing="0" class="border">
      <tr align="center" class="title">
        	<td>预约码卡号</td>
        	<td>预约码分类</td>
        	<td>生成时间</td>
            <td>有效使用时间</td>
        	<td>使用时间</td>
        	<td>使用情况</td>
            <td>是否过期</td>
        </tr>
               <%
                    if (dt.Rows.Count > 0)
                    {
                        var i = 0;
                        foreach (DataRow dr in dt.Rows)
                        {
           %>
      <tr class="tdbg">
          <td class="splittd" align="center" nowrap><%=dr["CodeID"].ToString() %></td>
          <td class="splittd" align="center" nowrap><%=dr["typename"].ToString() %></td>
          <td class="splittd" align="center" nowrap><%=Convert.ToDateTime(dr["AddDate"].ToString()).ToShortDateString() %></td>
          <td class="splittd" align="center" nowrap><%=Convert.ToDateTime(dr["BeginDate"].ToString()).ToShortDateString() %>--<%=Convert.ToDateTime(dr["EndDate"].ToString()).ToShortDateString()  %></td>
          <td class="splittd" align="center" nowrap><%=Convert.ToString(dr["UseTime"].ToString()) == "" ? "---":Convert.ToString(dr["UseTime"].ToString())%></td>
          <td class="splittd" align="center" nowrap><%=Convert.ToString(dr["IsUsed"].ToString()) == "1" ? "<font color='red'>已使用</font>":"<font color='green'>未使用</font>"%> </td>
          <td class="splittd" align="center" nowrap><%=Convert.ToDateTime(DateTime.Now)>Convert.ToDateTime(dr["EndDate"].ToString())?"<font color='red'>已过期</font>":"<font color='gray'>否</font>"%></td>
      </tr>  
    <%
                i++;
            }
        }
        else
        {
            KSCMS.W(@"<tr class=""tr-nobor""><td colspan=""7""><div class=""empty""> 没有可用的预约码！！</div></td></tr><style>.cz_btn{display:none}</style>");
        }
      %>
     </table>
          <%} %>

    <div class="clear"></div>
    <div class="cz_btn">
      <%
          #region 分页
          if (pagecount > 0)
          {
               string PageStr=__user.GroupID==3||__user.GroupID==4?"[KS:PageStr1]": "[KS:PageStr2]";
              BasicField.ReplaceFilterPage(ref PageStr, CurrPage, PageSize, pagecount, recordcount);
              KSCMS.W(PageStr);
          }
          #endregion
           %>


    </div>

</div>
