<%@ 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="Kesion.Components" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="Kesion.Course" %>
<%@ Import Namespace="System.Collections" %>
<%@ Import Namespace="System.Web.UI" %>
<script runat="server" type="text/C#">
    dynamic __user = HttpContext.Current.Items["user"];                //初始化用户信息，

    bool isLoadPage = true;  //定义页面是否加载
    protected void Page_Load(object sender, EventArgs e)
    {
        if (KSCMS.S("action") == "dobuy")
        {
            isLoadPage = false;
            doBuy();
            return;
        }
    }
    private void doBuy()
    {
        UserInfo __info = UserManage.GetUserInfo();
        string username = UserManage.GetUserInfo().UserName;

        int packId = Utils.StrToInt(KSCMS.S("packid"), 0);

        string title = KSCMS.S("title");

        if (packId == 0 || string.IsNullOrEmpty(packId.ToString()) || string.IsNullOrEmpty(title))
        {
            Msg.Alert("选择错误", BasicField.GetUserUrl("basic/MyFeePackageBuy"));
            return;
        }
        //   KSCMS.Die(id + "|" + title);
        using (DataTable dt = DataFactory.GetDataTable("Select top 1 a.*,b.discount From KS_UserFeePackages a inner join KS_UserFeeDiscount b on a.id=b.packid Where a.status=1 and b.groupid=" + __user.GroupID + " and a.ID=" + packId))
        {
            if (dt.Rows.Count <= 0)
            {
                Msg.Alert("出错啦，找不到您要购买的营销卡！");
                return;
            }
            else
            {
                DataRow dr = dt.Rows[0];
                title = dr["title"].ToString();
                float money = Utils.StrToFloat(dr["price"].ToString());
                float realmoney = Utils.StrToFloat(dr["price"].ToString());//记录原价
                float discount = Utils.StrToFloat(dr["discount"].ToString());
                if (discount == 0) discount = 1;
                int days = Utils.StrToInt(dr["days"].ToString());
                if (money == 0 || days == 0)
                {
                    Msg.Alert("对不起，系统配置有误，不能完成购买，请联系管理员!", KSCMS.GetComeUrl());
                    return;
                }
                money = money * discount;
                float user_pay_money = Utils.StrToFloat(KSCMS.S("user_pay_money"));
                // Msg.Alert(__user.Money + "||" + money + "||" + user_pay_money);

                string realName = __user.RealName;
                if (string.IsNullOrEmpty(realName)) realName = __user.UserName;
                string orderid = "packId" + string.Format("{0:yyyyMMddHHmmssfffffff}", DateTime.Now)+"_"+packId;

                float Accmoney=0;//计算套餐升级购买
                if (dr["IsUp"].ToString() == "1")
                {
                    Accmoney = UpOrderPrice();
                }
                if (money > Accmoney)//减掉之前支付的套餐价格
                {
                    money = money - Accmoney;
                }

                //余额支付
                if (__user.Money >= money && __user.Money >= user_pay_money && user_pay_money >= money)
                {
                    if (string.IsNullOrEmpty(realName)) realName = __user.UserName;
                    bool b = Charge.MoneyInOrOut(__user.UserID, realName, money, 1, 2, dr["id"].ToString(), "system", "购买收费营销卡包[" + dr["title"].ToString() + "]!", -100, 0, 1);
                    if (b)
                    {
                        string Agreement = dr["Agreement"].ToString();
                        if (Utils.StrToInt(dr["IsIdentity"].ToString()) == 1)//开启协议
                        {
                            string userinfo = Utils.RemoveXss(KSCMS.S("userinfos"));
                            //JS.Alert(userinfo);
                            if (!string.IsNullOrEmpty(userinfo))
                            {
                                userinfo = userinfo.TrimEnd('@');
                                string[] info = Utils.SplitString(userinfo, "@@");

                                for (int i = 0; i < info.Length; i++)
                                {
                                    Agreement = Utils.ReplaceString(Agreement, "{#input" + (i + 1) + "}", "<span class='line'>" + info[i].ToString() + "</span>", true);
                                }
                                for (int i = info.Length; i <= 100; i++)
                                {
                                    Agreement = Utils.ReplaceString(Agreement, "{#input" + (i + 1) + "}", "<span class='line'></span>", true);
                                }

                            }
                        }


                         Kesion.APPCode.Public.CreateUserFee(__user.UserID, dr, orderid, money, Agreement);  //生成一张营销卡号，并做逻辑处理




                        Msg.Alert("恭喜，收费服务包购买成功！", KSCMS.GetComeUrl());
                        return;
                    }
                    else
                    {
                        Msg.Alert("扣费出错！", KSCMS.GetComeUrl());
                        return;
                    }
                }
                else
                {

                    //产生记录
                    int payId = Utils.StrToInt(KSCMS.S("payId"), 0);
                    money = money - user_pay_money;
                    if (money <= 0)
                    {
                        Msg.Alert("对不起，系统配置有误，不能完成购买，请联系管理员!", KSCMS.GetComeUrl());
                        return;
                    }
                    DataFactory.ExecuteNonQuery("delete from KS_RechargeRecords where username='" + new TemporaryVar().UserName + "' and ordertype=2 and packid=" + packId + " and status=0");
                    KSCMS.Redirect("/plus/pay/PayConfirm.aspx?from=&pack=feepackages&ordertype=2&PlatID=" + payId + "&packid=" + packId + "&money=" + money + "&orderid=" + orderid + "&packname=" + title + "&userinfo=" + KSCMS.S("userinfo") + "");
                }
            }
        }
    }




    public static string GetShiYong(string limit, int contenttf, int examtf, int coursetf, int packid)
    {
        #region 使用条件
        string str = string.Empty;
        string sql = string.Empty;

        if (Utils.StrToInt(limit) == 0)
        {
            switch (contenttf)
            {
                case 1:
                    str += " <p><span class=\"used_info_tj\">文章模块拥有所有免费查看权限</span></p></br>";
                    break;
                case 2:
                    str += " <p><span class=\"used_info_tj\">部分文章栏目下拥有免费查看权限</span><a style=\"color:red\" href=\"javascript:SeeInfo('" + packid + "')\" ></a></p></br>";
                    break;
            }
            switch (examtf)
            {
                case 1:
                    str += " <p><span class=\"used_info_tj\">考试模块拥有所有免费做题权限</span></p></br>";
                    break;
                case 2:
                    str += " <p><span class=\"used_info_tj\">部分考试栏目下拥有免费做题权限</span><a style=\"color:red\" href=\"javascript:SeeInfo('" + packid + "')\" ></a></p></br>";
                    break;
                case 3:
                    str += " <p><span class=\"used_info_tj\">指定试卷免费</span><a style=\"color:red\" href=\"javascript:SeeInfo('" + packid + "')\" ></a></p></br>";
                    break;
            }
            switch (coursetf)
            {
                case 1:
                    str += " <p><span class=\"used_info_tj\">课程模块拥有所有免费观看权限</span></p>";
                    break;
                case 2:
                    str += " <p><span class=\"used_info_tj\">部分课程栏目下拥有免费观看权限</span><a style=\"color:red\" href=\"javascript:SeeInfo('" + packid + "')\" ></a></p></br>";
                    break;
                case 3:
                    str += " <p><span class=\"used_info_tj\">指定课程免费</span><a style=\"color:red\" href=\"javascript:SeeInfo('" + packid + "')\" ></a></p></br>";
                    break;
            }

        }
        else if (limit == "1")
        {
            str = @" <p><span class=""used_info_tj"">可以查看本站的所有收费项目</span></p>";
        }


        return str;
        #endregion
    }
    public static string GetDiscount(float discount)
    {
        string str = string.Empty;
        if (discount == 1)
        {
            str = "无";
        }
        else
        {
            str = discount * 10 + "折";
        }
        return str;
    }
    public float UpOrderPrice()
    {
        #region 计算套餐升级优惠价格
        float Accmoney = 0;
        DataTable dts = DataFactory.GetDataTable("select top 1 PackID,realmoney,PayTime,packid from KS_RechargeRecords where status=1 and username='" + new TemporaryVar().UserName + "' order by AddDate Desc");
        if (dts.Rows.Count > 0)
        {
            Accmoney = Utils.StrToFloat(dts.Rows[0][1].ToString());
            int EffectDays = 0;
            int AllDays = 0;
            if (!string.IsNullOrEmpty(dts.Rows[0][2].ToString()))
            {

                //    string UserTime=  = DataFactory.GetOnlyValue("select top 1 usertime from KS_UserFeePackages a inner join KS_UserFeeSell b on a.Id=b.PackID where a.usetype=1 and b.UserID=" + new TemporaryVar().UserID + " and b.PackID=" + Utils.StrToInt(dts.Rows[0][3].ToString()) + "");
                DataTable dtt = DataFactory.GetDataTable("select top 1 PackBeginDate,PackDays from KS_UserFeePackages a inner join KS_UserFeeSell b on a.Id=b.PackID where a.usetype=1 and b.UserID=" + new TemporaryVar().UserID + " and b.PackID=" + Utils.StrToInt(dts.Rows[0][3].ToString()) + "");
                if(dtt.Rows.Count>0){
                    string UserTime=Utils.StrToDateTime(dtt.Rows[0][0].ToString()).AddDays(Utils.StrToInt(dtt.Rows[0][1].ToString())).ToString();
                    if (!string.IsNullOrEmpty(UserTime))
                    {
                        //套餐未过期
                        if (Utils.StrToDateTime(UserTime) > DateTime.Now)
                        {

                            AllDays = Utils.StrToInt(dtt.Rows[0][1].ToString());

                            TimeSpan Days = DateTime.Now.Subtract(Convert.ToDateTime(dts.Rows[0][2].ToString()));
                            if (Days.Days >= 0)//已经使用的天数
                            {
                                EffectDays = Utils.StrToInt(Days.Days);
                            }
                            if (AllDays > 0 && EffectDays >= 0)//计算最终价格
                            {
                                Accmoney = Utils.StrToFloat(Math.Round((Accmoney / AllDays) * EffectDays, 2));
                            }
                        }

                    }
                }
            }
        }
        return Accmoney;
        #endregion
    }
    public static decimal CutDecimalWithN(decimal d, int n)
    {
        string strDecimal = d.ToString();
        int index = strDecimal.IndexOf(".");
        if (index == -1 || strDecimal.Length < index + n + 1)
        {
            strDecimal = string.Format("{0:F" + n + "}", d);
        }
        else
        {
            int length = index;
            if (n != 0)
            {
                length = index + n + 1;
            }
            strDecimal = strDecimal.Substring(0, length);
        }
        return Decimal.Parse(strDecimal);
    }


</script>
<script>
    $(document).ready(function () {
        $("#buycount").find("div").each(function () {
            $(this).attr("onclick", "savecount(" + $(this).find("span").html() + ")");
        })
    })
    function countprice(id) {
        var nprice = parseFloat($("#price" + id).html());
        $("#allprice").val(nprice);
        $("#price").html(nprice);//价格
        $("#title").val($("#t" + id).html());//标题
        $("#packid").val(id);//卡片id

    }
    var box = '';
    function SeeInfo(packid,cardtype) {
        box = jQuery.dialog.open("/index.aspx?c=user&a=basic&frame=no&f=MyFeePackageDetail&packid="+packid+"&cardtype="+cardtype, { id: "loginbox", lock: true, fixed: true, title: "<div style='text-align:left'>"+(cardtype=="1"?"充值卡":"营销卡")+"使用详情</div>", width: 900, height: 500, max: false, min: false });
    }
</script>
<style>
    #buycount div {
        float: left;
        margin: 10px 0 0 20px;
    }

    .my_coupon li.study_card {
        float: left;
        background: none;
        padding: 0;
        width: auto;
        height: auto;
    }

        .my_coupon li.study_card .study_card_in {
            padding: 50px 8px 10px;
            background: url(/user/img/studycard.png) no-repeat top center;
            background-size: 100% 100%;
            width: 319px;
            height: 174px;
        }

    del {
        text-decoration: line-through;
    }

    #buycount div {
        float: left;
        margin: 10px 0 0 20px;
    }

    .my_coupon li.study_card {
        float: left;
        background: none;
        padding: 0;
        width: auto;
        height: auto;
    }

        .my_coupon li.study_card .study_card_in {
            padding: 50px 8px 10px;
            background: url(/user/img/studycard.png) no-repeat top center;
            background-size: 100% 100%;
            width: 319px;
            height: 174px;
        }

    .my_coupon li.study_card {
        float: left;
        background: none;
        padding: 0;
        width: auto;
        height: auto;
    }

        .my_coupon li.study_card .study_card_in {
            padding: 50px 8px 10px;
            background: url(/user/img/studycard.png) no-repeat top center;
            background-size: 100% 100%;
            width: 319px;
            height: 174px;
        }

    .table {
        display: table;
        width: 100%;
        border-collapse: collapse;
    }

    .table-tr {
        display: table-row;
        height: 40px;
    }

    .table-trs {
        display: table-row;
        height: 60px;
        border-bottom: solid 1px #e5e9ed;
    }

    .table-th {
        display: table-cell;
        font-weight: bold;
        height: 40px;
        text-align: center;
        vertical-align: middle;
        background-color: #F9F9F9;
        font-size: 15px;
        min-width: 80px;
    }

    .table-td {
        display: table-cell;
        height: 60px;
        text-align: center;
        vertical-align: middle;
        font-size: 14px;
        color: #8A8A8A;
    }

    .td-le {
        text-align: left;
        text-align: left;
        text-indent: 20px;
    }

    .noexpire {
        color: Green;
    }

    .expire {
        color: brown;
    }

    .td-lz {
        text-align: left;
        width: 200px;
        text-align: center;
    }

    .tan-box {
        background-color: white;
        display: none;
    }

    .zhezhao {
        width: 100%;
        height: 100%;
        background-color: #000;
        opacity: 0.2;
        position: fixed;
        left: 0;
        top: 0;
        z-index: 990;
        filter: alpha(opacity=0.2);
        -moz-opacity: 0.2;
        -khtml-opacity: 0.2;
        display: none;
    }

    .lac {
        min-height: 60px;
        width: 540px;
    }

        .lac span {
            margin-left: 20px;
            line-height: 30px;
        }

    .guan {
        position: absolute;
        top: 10px;
        right: 10px;
        width: 20px;
        height: 20px;
        cursor: pointer;
    }
    .line input{  border:0px; background:none;border-bottom:2px solid #000; }
   
   
    
</style>
<%
    if (!isLoadPage) return;
%>
<div class="r_tybox nomar disting">
    <div class="r_title">
        <h4 class="disting_show">购买营销卡</h4>
        
    </div>
     <div class="top-sort clearfix">
        <div class="top-sort-tab lf">
            <ul>
                <li><a href="<%=BasicField.GetUserUrl("basic/MyFeePackages") %>">我的营销卡</a></li>
                <li class='puton'><a href="<%=BasicField.GetUserUrl("basic/MyFeePackageBuy","show-1") %>">购买营销卡</a></li>
                <li><a href="<%=BasicField.GetUserUrl("basic/MyFeePackages","show-2") %>">线下激活</a></li>
            </ul>
        </div>
     </div>
   
    <form name="myform" id="myform" action="<%=BasicField.GetUserUrl("basic/MyFeePackageBuy") %>" method="post">
            <div id="mybuypackage">
                <table width="100%" border="0" align="center" cellpadding="0" cellspacing="0" class="border">
                    <tr class="title">
                        <td>选择</td>
                        <td>营销卡名称</td>
                        <td>类型</td>
                        <td>原价</td>
                        <td>促销价</td>
                        <td>使用期限</td>
                        <td>营销卡权限</td>
                        <td>操作</td>
                    </tr>  

                    <%
                        bool HasRecord = false;
                        int recordcount, pagecount;
                        int CurrPage = new BasicField().GetCurrPage;
                        int PageSize = 12;
                        string param = "KS_UserFeePackages a inner join KS_UserFeeDiscount b on a.id=b.packid Where a.usetype=1 and a.status=1 and b.status=1 and b.groupid=" + __user.GroupID;

                        using (DataTable dt = DataFactory.GetPage("a.*,b.discount", param, "a.id", "order by  UpOrder asc,a.id desc", CurrPage, PageSize, out recordcount, out pagecount))
                        {
                            if (dt.Rows.Count > 0)
                            {
                                HasRecord = true;
                                int i = 0;
                                float Accmoney=0;//已经购买套餐包的价格
                                foreach (DataRow dr in dt.Rows)
                                {
                                    double Oprice =  Convert.ToDouble(Utils.StrToFloat(dr["price"].ToString()).ToString());
									double NowPrice = Convert.ToDouble(CutDecimalWithN((Utils.StrToDecimal(dr["price"].ToString()) * Utils.StrToDecimal(dr["discount"].ToString())),2));

                                    if (!string.IsNullOrEmpty(dr["groupid"].ToString())&&(","+dr["groupid"].ToString()+",").IndexOf(","+new TemporaryVar().GroupID+",")==-1)
                                    {
                                        continue;//开启了指定用户组查看
                                    }
                                    //开启了套餐升级购买
                                    if (Utils.StrToInt(dr["IsUp"].ToString()) == 1&&Utils.StrToInt(dr["cardtype"].ToString())==0)
                                    { 
                                        if (i == 0)
                                        {
                                            Accmoney = UpOrderPrice();//计算老套餐可优惠的价格
                                        }
                                       
                                            if (NowPrice > Accmoney)//减掉基于原套餐包的价格
                                            {
                                                NowPrice = NowPrice - Accmoney;
                                            }
                                        
                                    }
                                    
                                    KSCMS.W("<tr>" +
                                      "<td>"+(i+1)+"<input type='hidden' name='title' id='title"+dr["id"].ToString()+"' value='" + dr["title"].ToString() + "'></td>" +
                                         "<td>" + dr["title"].ToString() + "</td>" +
                                            "<td>" + (dr["cardtype"].ToString() == "1" ? "充值卡" : "套餐") + "</td>" +
                                      "<td nowrap='nowrap'><del>" + Oprice + "</del></td>" +
                                      "<td nowrap='nowrap'><font color=\"#fe5b00\">" + NowPrice + "</font></td>" +
                                      "<td>" + (dr["cardtype"].ToString() == "1" ? "vip:" : "") + dr["days"].ToString() + "天"+(Utils.StrToInt(dr["GiveVIPDay"].ToString())==0?"":"(赠送VIP:"+Utils.StrToInt(dr["GiveVIPDay"].ToString())+"天)")+"</td>" +
                                      "<td>" + (dr["cardtype"].ToString() == "1" ? "用户组权限" : GetShiYong(dr["limit"].ToString(), Utils.StrToInt(dr["contenttf"].ToString()), Utils.StrToInt(dr["examtf"].ToString()), Utils.StrToInt(dr["coursetf"].ToString()), Utils.StrToInt(dr["id"].ToString()))) + "</td>" +
                                      " <td>  <a class=\"green-bt ro_5 quit\" onclick=\"SeeInfo(" + dr["id"].ToString() + "," + dr["cardtype"].ToString() + ")\" href=\"#\">查看详情</a>"+
                                      "   <a class=\"green-bt ro_5 quit\" href=\"javascript:;\" onclick=\"ShowPay(" + dr["id"].ToString() + ")\">购买</a></td>");
                                    KSCMS.W("<input type='hidden' id='pay_money_" + dr["id"].ToString() + "' value='" + NowPrice + "'/></tr>");
                               
                                    i++;
                                }
                              
                               
                            }
                            else
                            {
                                KSCMS.W("<tr class=\"tr-nobor\"><td colspan=\"8\"><div class=\"empty\" >没有可用的营销卡！</td></tr><style>.cz_btn{ display:none;}</style>");
                            }
                        }
                    %>
                </table>
            
            <input type="hidden" id="userinfos" name="userinfos" value="" />
            <input type="hidden" id="action" value="dobuy" name="action" />
            <input type="hidden" id="packid" value="0" name="packid" />
            <div style="display: none" id="totalprice">
                总计：<div>共支付<span id="price"></span>元</div>
            </div>
</div>
            <%if (HasRecord)
              { %>
            <div id="paypanel" style="margin-top: 5px; display: none">
                <table class="border" width="100%" align="center" border="0" cellspacing="0" cellpadding="0">
                     <tr class="tdbg">
                        <td class="splittd" style="height: 50px">&nbsp; <strong>营销卡名称：</strong>
                              <span id="showTitle"></span>
                        </td>
                    </tr>

                    <tr class="tdbg">
                        <td class="splittd" style="height: 50px">&nbsp; <strong>选择支付方式：</strong>

                            <div class="paylist">
                                <ul>
                                    <%
                  string payId = "0";
                  StringBuilder sb = new StringBuilder();
                  sb.Append(new Kesion.APPCode.PayFormAPI().GetPaymentList());
                  Response.Write(sb.ToString());
                  string orderID = string.Concat("Pack", DateTime.Now.ToString("yy"), DateTime.Now.ToString("MM"), DateTime.Now.ToString("dd"), DateTime.Now.ToString("HH"), DateTime.Now.ToString("mm"), DateTime.Now.ToString("ss"));

                                    %>
                                </ul>
                            </div>

                        </td>
                    </tr>


                </table>
                
                <script>
                   
                    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>

                <table id="showagreement" style="display: none">

                    <tr>
                        <td></td>
                        <td>
                            <input type="checkbox" class="radiobtn" id="accept" />我已阅读并接受以下协议</td>
                    </tr>
                    <tr class="tdbg">
                        <td>协议内容：
                        </td>
                        <td>
                            <div id="agreement" style="padding:5px;border:1px solid #ccc;height:300px;overflow:auto;width:800px;"></div>
                        </td>
                    </tr>
                </table>
                <div class="cz_btn  t-a-center">
                    
                    <span class="f-left">
                    <input id="tl_money" type="hidden" value="100" />
                    总支付金额: <strong id="sf_money" style="color:#F00">100</strong>元</span>
                    
                    <span class="f-right"><input type="button" value="立即支付" class="green-bt d-inline-block" onclick="CheckUserInfo();" /></span>

                </div>

            </div>

            <%} %>

            <div class="cz_btn" id="d_cz_btn">
            	<div class="f-left">
                <%
                    #region 分页
                    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>
        </form>
        <style>
            .noexpire {
                color: Green;
            }

            .expire {
                color: brown;
            }
        </style>
</div>


<script>
    function ShowPay(packid)
    {
        onpaycheck(packid);
        $("#showTitle").html($("#title" + packid).val());
        $("#packid").val(packid);
        $('#d_cz_btn').remove();   
        $("#mybuypackage").hide()
        $("#paypanel").show();
        $.ajax({
            type:'Post',
            url:'/plus/course/CourseAjax.ashx',
            data:{action:"getpackageinfo",packid:packid},
            success:function(msg){
                // alert(msg);
                if(msg=="no")//无协议，不用填写用户信息
                {
                    $("#showagreement").hide();
                }
                else
                {
                    if(msg!="0"){     
                        $("#showagreement").show();
                        $("#agreement").html(msg);
                    }
                }

            }
        });
    }
    function CheckUserInfo()
    {
        if($("#showagreement").css("display")!="none")
        {
            if(!$("#accept").attr("checked"))
            {
                alert("请阅读并接受协议！");
                return false;
            }
        }
        check();
    }

</script>


