<%@ 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 string from = string.Empty;
    public static string Enddate = string.Empty;
    public static int CurrPage = 1;
    public static int PageSize =10;
    string[] Days = null;
    public static string intro = string.Empty;


    protected void Page_Load(object sender, EventArgs e)
    {

        string _VIP = new Kesion.Controllers.userBasicController().GetVipConfig("VIP", 0);
        intro = new Kesion.Controllers.userBasicController().GetVipConfig("intro", 0);

        Days = string.Concat(_VIP, "\n").Split('\n');

        if (KSCMS.S("action") == "dosave")
        {
            isLoadPage = false;
            DoPay();
            return;
        }

    }


    private void DoPay()
    {
        int userType = Utils.StrToInt(KSCMS.S("userType"));
        if (string.IsNullOrEmpty(KSCMS.S("userType")))
        {
            Msg.Alert("请选择支付类型！");
            return;
        }

       string  Enddate = Utils.StrToDateTime(__user.EndDate).ToString();
       int payId = Utils.StrToInt(KSCMS.S("payId"), 0);
        
        float money = 0;
        string _OrderID = "VIP" + string.Format("{0:yyyyMMddHHmmssfffffff}", DateTime.Now);  //付款订单
        DateTime time = DateTime.Now;
        //提取RadioButtonList1 的下标 i 再查找下标所对应的值
        string[] _moneyorday = string.Concat(Days[userType].ToString(), "|").Split('|');
        int num = Utils.StrToInt(_moneyorday[0].ToString());
        money = Utils.StrToFloat(Utils.Trim(_moneyorday[1].ToString()));

        //时间判断增加
        if (Utils.StrToDateTime(Enddate) >= Utils.StrToDateTime(time))
        {
            time = Utils.StrToDateTime(Enddate).AddDays(+num);
        }
        else
        {
            time = Utils.StrToDateTime(time).AddDays(+num);
        }
        bool cos = false;
        cos = cosorder(money, _OrderID, time,num);
        if (cos)  //判断扣款
        {
            DataFactoryUser.ExecuteNonQuery("UPDATE [KS_User] SET [LoadType]=1,Enddate='" + time + "' WHERE UserId= " + __user.UserID);


            Msg.AlertDoFun("恭喜，成功升级VIP会员！", "top.location.href='"+BasicField.GetUserUrl("basic/UserVIP")+"';");

        }
        else
        {
            Msg.AlertDoFun("金额不够请充值！", "location.href='"+BasicField.GetUserUrl("basic/payonline")+"';");
        }
    }
    //  扣款处理
    protected bool cosorder(double money, string orderid, DateTime time,int day)
    {
        bool iscount = false;
        float user_pay_money = Utils.StrToFloat(KSCMS.S("user_pay_money"));
        if (money <= 0)
        {
            JS.Alert("支付金额错误！");
            return false;
        }
        else if (UserManage.GetUserInfo(new TemporaryVar().UserID).Money >= user_pay_money && user_pay_money >= money)
        {
            iscount = Charge.MoneyInOrOut(new TemporaryVar().UserID, UserManage.GetUserInfo(new TemporaryVar().UserName).RealName, money, 4, 2, orderid, "system", "用于升级VIP,截止时间：[" + time + "]", -5000, 0, 1);
        }
        else
        {
            int payId = Utils.StrToInt(KSCMS.S("payId"), 0);
            string title = money + "元购买" + day + "天";
            double totalmoney = money;
            money = money - user_pay_money;
           
            DataFactory.ExecuteNonQuery("delete from KS_RechargeRecords where username='" + new TemporaryVar().UserName + "' and ordertype=9 and status=0");
            KSCMS.Redirect("/plus/pay/PayConfirm.aspx?ordertype=9&PlatID=" + payId + "&totalmoney=" + totalmoney + "&packid=" + day + "&money=" + money + "&orderid=" + orderid + "&packname=" + title);

        }


        if (iscount)
        {
         
            #region 记录购买VIP产生的佣金
            //Hashtable ht = new Hashtable();
            //ht.Add("YjRate1", Kesion.CosODS.NewCosAgent.GetYjRate(Utils.StrToDecimal(money), 1));
            //ht.Add("YjRate2", Kesion.CosODS.NewCosAgent.GetYjRate(Utils.StrToDecimal(money), 2));
            //ht.Add("YjRate3", Kesion.CosODS.NewCosAgent.GetYjRate(Utils.StrToDecimal(money), 3));
            //CommonData.Update("KS_LogMoney", ht, "where id =" + CommonData.GetMaxId("KS_LogMoney", "id", "where channelid = -5000 and username ='" + new TemporaryVar().UserName + "'"));

            #region 生成佣金
            Hashtable htt = new Hashtable();
            #region 生成分销商佣金
             if (MyCache.GetShopCommonConfig(59) == "1" || MyCache.GetShopCommonConfig(59) == "3")//开启课程微分销
            {
                if (BaseFun.CheckTableExists("KS_AgentYJ") && Utils.InArray("3", MyCache.GetShopCommonConfig(129)) && Utils.StrToInt(DataFactory.GetOnlyValue("select count(*) from KS_User where (IsAgent = 1 or IsAgent = 3) and UserID = " + UserManage.GetUserInfo().PUserID)) > 0)
                {
                    htt.Add("UserID", new TemporaryVar().UserID);
                    htt.Add("UserName", new TemporaryVar().UserName);
                    htt.Add("OrderID", orderid);
                    htt.Add("Cname", money + "元购买" + day + "天");
                    htt.Add("Type", 4);
                    htt.Add("AddDate", DateTime.Now.ToString());
                    htt.Add("UnitPrice", Utils.StrToDecimal(money.ToString()));
                    htt.Add("Price", Utils.StrToDecimal(money.ToString()));
                    htt.Add("Discount", Utils.StrToDecimal(money.ToString()));
                    htt.Add("Status", 1);
                    htt.Add("YjRate1", Utils.StrToDecimal(Kesion.ODS.AgentClass.GetAgentYJ(Utils.StrToDecimal(money.ToString()), 1, 1)));
                    htt.Add("YjRate2", Utils.StrToDecimal(Kesion.ODS.AgentClass.GetAgentYJ(Utils.StrToDecimal(money.ToString()), 2, 1)));
                    htt.Add("YjRate3", Utils.StrToDecimal(Kesion.ODS.AgentClass.GetAgentYJ(Utils.StrToDecimal(money.ToString()), 3, 1)));
                    htt.Add("Rate1", Utils.StrToDecimal(MyCache.GetShopCommonConfig(130)));
                    htt.Add("Rate2", Utils.StrToDecimal(MyCache.GetShopCommonConfig(131)));
                    htt.Add("Rate3", Utils.StrToDecimal(MyCache.GetShopCommonConfig(132)));
                    Kesion.ODS.AgentClass.AddAgentYJ(htt);
                }
            }
            #endregion
            #region 生成代理商佣金
            if (new Kesion.AgODS.AgConfig().GetAgConfig(0).Equals("1"))//开启代理商
            {
                if (BaseFun.CheckTableExists("KS_AgYJ"))
                {
                    if (new Kesion.AgODS.AgConfig().GetAgConfig(12).Equals("1") && Utils.StrToInt(DataFactory.GetOnlyValue("select count(*) from KS_User where IsAg = 1 and (UserID = " + UserManage.GetUserInfo().PUserID + " or UserID = " + UserManage.GetUserInfo().PPUserID + ")")) > 0)  //已开启分佣，并且上一级是分销商或代理商
                    {
                        int type = 0;
                        using (DataTable dtt = DataFactory.GetDataTable("select IsAg,GroupID from KS_User where UserID =" + UserManage.GetUserInfo().PUserID))
                        {
                            DataRow drr = dtt.Rows[0];
                            type = Utils.StrToInt(drr["GroupID"].ToString()) == 3 ? 1 : Utils.StrToInt(drr["GroupID"].ToString()) == 4 ? 1 : Utils.StrToInt(drr["IsAg"].ToString()) == 1 ? 2 : 0;
                        }
                        htt.Clear();
                        htt.Add("UserID", new TemporaryVar().UserID);
                        htt.Add("UserName", new TemporaryVar().UserName);
                        htt.Add("OrderID", orderid);
                        htt.Add("Cname", money + "元购买" + day + "天");
                        htt.Add("Type", 5);
                        htt.Add("AddDate", DateTime.Now.ToString());
                        htt.Add("Price", Utils.StrToDecimal(money.ToString()));
                        htt.Add("CourseID", 0);
                        htt.Add("Discount", Utils.StrToDecimal(money.ToString()));
                        htt.Add("Status", 1);
                        htt.Add("AgYJ1", Kesion.AgODS.Ag.GetAgRateYJ(Utils.StrToDecimal(money.ToString()), 1, type));
                        htt.Add("AgYJ2", Kesion.AgODS.Ag.GetAgRateYJ(Utils.StrToDecimal(money.ToString()), 2, type));
                        htt.Add("Rate1", Kesion.AgODS.Ag.GetAgYJRate(1, type));
                        htt.Add("Rate2", Kesion.AgODS.Ag.GetAgYJRate(2, type));
                        Kesion.AgODS.Ag.AddAgYJ(htt);
                    }
                }
            }
            #endregion
            #endregion
            
            //更新JSon
			 UserManage.CleanUserCache(new TemporaryVar().UserID);
            #endregion
            return true;
        }
        else
        {
            return false;
        }
    }
     public string GetMoney(double point, int inoroutflag, int type)
        {
            if (type == inoroutflag)
            {
                return string.Format("{0:n2}", point);
            }
            else
            {
                return "-";
            }
        }

        public string GetOpType(int type)
        {
            if (type == 1)
                return "<span class=green-color>收入</span>";
            else
                return "<span class=red-color>支出</span>";

        }
        public string GetNowMoney(double point)
        {
            return string.Format("{0:n2}", point);
        }


</script>
<%
    if (!isLoadPage) return;
%>
<div class="r_tybox nomar">
    <div class="r_title"><h4 class="disting_show">我的账户</h4>
       
    </div>
   
    <form name="myform" action="{$GetCurrUrl}" method="post" id="myform">
        <input type="hidden" name="action" value="dosave"/>

        <table cellspacing="1" cellpadding="3" class="border" width="100%" align="center" border="0">	
             <tr class="tdbg">
                 <td class="tag_left">
                     &nbsp; 您好,<%=__user.UserName %> !您的身份级别：<%=UserGroupManage.GetUserGroupInfo(__user.GroupID).GroupName %>,
                     <%
                         using (DataTable dt = DataFactoryUser.GetDataTable("select top 1 LoadType,Enddate from ks_User where userid=" + __user.UserID))
                         {
                             if (dt.Rows.Count > 0)
                             {
                                 DataRow dr = dt.Rows[0];
                                  int LoadType = Utils.StrToInt(dr["LoadType"].ToString());
                                 KSCMS.W(LoadType== 0 ? "会员级别为:普通会员" : "会员级别为：<font class=red-color>VIP会员</font> ");
                                 string Enddate = dr["EndDate"].ToString();
                                 if (LoadType != 0)
                                 {
                                   if (Utils.IsDateTime(Enddate))
                                     {
                                         if (DateTime.Now > Utils.StrToDateTime(Enddate))
                                         {
                                             
                                             Response.Write("已过期");
                                         }
                                         else
                                         {
                                             Response.Write("有效截止时间：<font class=red-color>" + Enddate + "</font>");
                                         }
                                     }
                                     else
                                     {
                                         Response.Write("");
                                     }

                                 }
                             }
                         }
                     %>
                     
                       <br />
                    &nbsp;  可用预存款 <font class=red-color><%=__user.Money.ToString("f2") %></font> 元 <a href="<%=BasicField.GetUserUrl("basic/logmoney") %>"><span class=blue-color>明细</span></a>，
                     可用<%=string.Concat(MyCache.GetCacheConfig(49), __user.Point, MyCache.GetCacheConfig(50)) %> <a href="<%=BasicField.GetUserUrl("basic/consumer") %>"><span class=blue-color>明细</span></a>
                     ，积分<font class=green-color><%=__user.Score %></font> 分 <a href="<%=BasicField.GetUserUrl("basic/logscore") %>"><span class=blue-color>明细</span></a>
                     </td>
             </tr>
             <tr class="tdbg">
                 <td class="tag_left" style="height:50px">
                    &nbsp; 选择会员类型： 
                     <br />
                     <div id="mybuyvip">
                      <br />
                         <%
                             for (int i = 0; i < Days.Length - 1; i++)
                             {
                                 string[] Day = string.Concat(Days[i].ToString(), "|").Split('|');
                                 Response.Write(string.Format(@"<label><input type=""radio"" name=""usertype"" value=""{0}""{1}>{2}", i.ToString(), (i == 0 ? " checked" : ""), Day[1].ToString() + "元购买" + Day[0].ToString() + "天VIP"));
                                 Response.Write("<input type='hidden' id='pay_money_" + i.ToString() + "' value='" +  Day[1].ToString() + "'/></label><br/>");
                             }

    %>                 </div>         
                 </td>
             </tr>
              <tr class="tdbg">
                <td class="tag_left" style="padding-left:20px;">                             
                   VIP充值介绍：<%=intro %>
                 </td>
             </tr>
                  <tr class="tdbg">
                <td class="tag_left" style="padding-left:20px;">       
                     <input id="tl_money" type="hidden" value="100" />                      
                        <%
                            string payId = "0";
                               StringBuilder sb = new StringBuilder();
                               sb.Append(new Kesion.APPCode.PayFormAPI().GetPaymentList());
                               Response.Write(sb.ToString());
                               %>
                 </td>
             </tr>
            
              <tr class="tr-nobor">
                <td class="tag_left" style="padding-left:20px;">      
                     <span>总支付金额: <span id="sf_money" class="zf-money">100</span>元</span>                                           
                     <input type="submit" class="green-bt green-bt-big m-t-10 button" value="确认支付"  />      
                 </td>
             </tr>
        
    
        </table>
                       <script>
                           var pid=<%=payId%>;
                           $(document).ready(function(){
                               var id = $("input[name='usertype']:checked").val();
                               onpaycheck(id);
                               $("#mybuyvip").find("input[name='usertype']").click(function(){
                                   pid=$(this).val()

                                   onpaycheck(pid);
                               });
                           });
                           function onpaycheck(id){
         
                               var p= $("#pay_money_"+id).val();     
                     
                               $("#sf_money").html(p);
                               $("#tl_money").val(p);
                               $("#user_pay_money").val(p);
                               $("#my_27").attr("checked","checked");
                       

                               payu();
                           }

                           function check() {
                               var userinfo="";
                               $("input[name=userinfo]").each(function(){
                                   userinfo+=$(this).val()+"@@";
                               });
                               $("#userinfos").val(userinfo);
                               if($("#showagreement").css("display")!="none")
                               {
                                   var realname=$("#realname").val();
                                   var identity=$("#identity").val();
                                   var mobile=$("#mobile").val();
                                   $("#userinfo").val(realname+"||"+identity+"||"+mobile);
                      
                               }
                               KesionJS.Confirm("此操作不可逆，确定购买选中的营销卡吗？", "jQuery('#myform').submit();", "");
                               return false;
                           }
                </script>

        </form>
    
    </div>
    <div class="r_tybox">
    	<div class="r_title"><h4>消费记录</h4></div>
        <table id="Table1" width="100%" border="0" align="center" cellpadding="0" cellspacing="0" class="border">
          <tr align="center" class="title">
        	    <td width="60" align="center">序号</td>
        	    <td width="150"  align="center">消费时间</td>       
                <td align="center"  width="110"> 支出(元) </td>
                <td align="center"  width="80">摘要</td>
                <td align="center"  width="100">余额(元)</td>
                <td align="center">备注</td>
            </tr>
        <%
            string sql = " and remark like '%用于升级VIP,截止时间%'";
            int recordcount, pagecount;
            int CurrPage = new BasicField().GetCurrPage;

            using (DataTable dt = DataFactory.GetPage("*", "[KS_LogMoney] where  userName='" + __user.UserName + "'" + sql, "id", "order by id 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"">");
                        KSCMS.W(@"<td class=""splittd"" align=""center"">" + i + "</td>");
                        KSCMS.W(@"<td class=""splittd"">" + dr["PayTime"].ToString() + "</td>");
                        KSCMS.W(@"<td class=""splittd"" align=""center"">");
                        KSCMS.W(GetMoney(Convert.ToDouble(dr["money"].ToString()), Convert.ToInt16(dr["InComeorPayout"].ToString()), 2));
                        KSCMS.W("</td>");
                        KSCMS.W(@"<td class=""splittd"" align=""center"">");
                        KSCMS.W(GetOpType(Convert.ToInt16(dr["InComeorPayout"].ToString())));
                        KSCMS.W("</td>");
                        KSCMS.W(@"<td class=""splittd"" align=""center"">");
                        KSCMS.W(GetNowMoney(Convert.ToDouble(dr["currMoney"].ToString())));
                        KSCMS.W("</td>");
                        KSCMS.W(@"<td class=""splittd"" style=""word-break:break-all"">");
                        KSCMS.W(dr["remark"].ToString());
                        KSCMS.W(@"</td>
                        </tr>   ");
                        i++;
                    }

                }else
                {
                    KSCMS.W(@" <tr class=""tr-nobor"">
                    <td class=""splittd"" style=""text-align:center"" colspan=""10"">
                      <div class=""empty"">没有消费记录！</div>
                    </td>
                   </tr><style>.cz_btn{display:none;}</style>");

                }

            }

          %>
          </table>

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

            </div>
        
    </div> 