<%@ Page Language="C#" StylesheetTheme="" EnableTheming="false" Inherits="PowerEasy.Foundation.Web.UI.DynamicPage"%>
<%@ Import Namespace="PowerEasy.Module.Shop.BusinessLogic" %>
<%@ Import Namespace="PowerEasy.Framework.Common" %>
<%@ Import Namespace="PowerEasy.Module.General.Enumerations.Accessories" %>
<%@ Import Namespace="PowerEasy.Foundation" %>
<%@ Import Namespace="PowerEasy.Module.Shop.BusinessLogic" %>
<%@ Import Namespace="PowerEasy.Module.Shop.Model" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
    {
        string payOnlineShopID;
        string payOnlineKey;
        string v_mid, v_oid, md5string;

        string v_amount = "0";
        bool updateDeliverStatus=false;
        bool updateOrderStatus=false;
        int payOnlinestatus=1;
        int payPlatformId = 15;  //财付通中介支付
        PowerEasy.Module.General.Model.Accessories.PayPlatformInfo payPlatform = PowerEasy.Module.General.BusinessLogic.Accessories.PayPlatform.GetPayPlatformById(payPlatformId);
        if (payPlatform.IsDisabled || payPlatform.MD5 == "3056" || string.IsNullOrEmpty(payPlatform.MD5))
        {
            LblMsg.Text = Resources.DynamicPageResources.PayOnline_PayResult99bill_ToPayNo;
            return;
        }
        payOnlineShopID = payPlatform.AccountsId;
        payOnlineKey = payPlatform.MD5;
        v_mid = payPlatform.AccountsId;

        string attach = StringHelper.Trim(Request["attach"]);
        string buyer_id = StringHelper.Trim(Request["buyer_id"]);
        string cft_tid = StringHelper.Trim(Request["cft_tid"]);
        string chnid = StringHelper.Trim(Request["chnid"]);
        string cmdno = StringHelper.Trim(Request["cmdno"]);
        string mch_vno = StringHelper.Trim(Request["mch_vno"]);
        string retcode = StringHelper.Trim(Request["retcode"]);
        string seller = StringHelper.Trim(Request["seller"]);
        string status = StringHelper.Trim(Request["status"]);
        string total_fee = StringHelper.Trim(Request["total_fee"]);
        string trade_price = StringHelper.Trim(Request["trade_price"]);
        string transport_fee = StringHelper.Trim(Request["transport_fee"]);
        string version = StringHelper.Trim(Request["version"]);
        StringBuilder buf = new StringBuilder();
        AddParameter(buf, "attach", attach);//attach	是	字符串	[1,200]	该参数财付通不做处理。回调时原样返回。为商户可能的个性化应用预留。
        AddParameter(buf, "buyer_id", buyer_id);//buyer_id	是	字符串	[1,65]	买家财付通帐号
        AddParameter(buf, "cft_tid", cft_tid);//cft_tid	是	字符串	[28,32]	财付通交易单号
        AddParameter(buf, "chnid", chnid);//chnid	否	字符串	[1,65]	平台提供者的财付通账号
        AddParameter(buf, "cmdno", cmdno);//cmdno	是	整数	[1,4]	任务代码，填写为12
        AddParameter(buf, "mch_vno", mch_vno);//mch_vno	否	整数	[12]	商家的定单号，此参数仅在对账时提供。YYYYMMDDXXXX
        AddParameter(buf, "retcode", retcode);//retcode	是	整数	[10,1]	0,成功，其它值，标识失败
        AddParameter(buf, "seller", seller);//seller	是	字符串	[1,65]	收款方财付通账号
        AddParameter(buf, "status", status); //status	是	整数	[1,4]	交易状态：
        AddParameter(buf, "total_fee", total_fee);//total_fee	是	整数	[1,12]	订单总价，单位为分
        AddParameter(buf, "trade_price", trade_price);//trade_price	是	整数	[1,12]	商品总价格，单位为分
        AddParameter(buf, "transport_fee", transport_fee);//transport_fee	是	整数	[1,12]	物流价格，单位为分
        AddParameter(buf, "version", version);//version	是	整数	[1,4]	版本号，取值如下：1：先前版本。2：本次更新的版本。对于旧版本，不此字段，对于新版本，此字段必填。
        AddParameter(buf, "key", payOnlineKey);

        md5string = DataCrypto.MD5(buf.ToString());
        //sign	是	字符串	[32,32]	Md5签名信息，签名方法如下：
        //1、	对所有请求字段，其值为空的不加入MD5验证
        //2、	对所有请求字段，按字段名的ASCII顺序进行连接，连接方式同URL参数连接方式。
        //Key=总是附加在签名串的最后，不参与ASCII排序。   
        string md5_sign = StringHelper.Trim(Request["sign"]);
        
        StringBuilder message = new StringBuilder();
        bool payResult = false;
        if (chnid == v_mid && md5string.ToUpper() == md5_sign.ToUpper())
        {
            //认证签名成功
            Response.Write("retcode:" + retcode + "<br/>");
            //返回码判断
            if (retcode == "0")
            {
                Response.Write("status:" + status + "<br/>");

                //按状态处理相关业务逻辑
                switch (Int32.Parse(status))
                {
                    case 1:
                        //交易创建
                        break;
                    case 2:
                        //收获地址填写完毕
                        break;
                    case 3:
                        //买家付款成功，注意判断订单是否重复的逻辑
                        message.Append(Resources.DynamicPageResources.PayOnline_PayResultTenpayMed_ToPayYes);
                        payResult = true;
                        v_oid = attach;
                        v_amount = Convert.ToString(DataConverter.ToDecimal(total_fee) / 100);
                        payOnlinestatus = 2;
                        break;
                    case 4:
                        //卖家发货成功
                        message.Append("卖家已发货，等待买家确认收货！");
                        payResult = true;
                        v_oid = attach;
                        v_amount = Convert.ToString(DataConverter.ToDecimal(total_fee) / 100);
                        payOnlinestatus = 4;
                        updateDeliverStatus = true;
                        break;
                    case 5:
                        //买家收货确认，交易成功
                        message.Append("买家收货确认，交易成功！");
                        payResult = true;
                        v_oid = attach;
                        v_amount = Convert.ToString(DataConverter.ToDecimal(total_fee) / 100);
                        payOnlinestatus = 3;
                        updateDeliverStatus = true;
                        updateOrderStatus = true;
                        break;
                    case 6:
                        //交易关闭，未完成超时关闭
                        break;
                    case 7:
                        //修改交易价格成功
                        break;
                    case 8:
                        //买家发起退款
                        break;
                    case 9:
                        //退款成功
                        break;
                    case 10:
                        //退款关闭
                        break;
                    default:
                        //error	
                        message.Append(Resources.DynamicPageResources.PayOnline_PayResultTenpayMed_ToPayNo);
                        break;
                }
            }
            else
            {
                //失败，请不要按成功处理
                message.Append(Resources.DynamicPageResources.PayOnline_PayResultTenpayMed_ToPayNo);
            }
        }
        else
        {
            message.Append(Resources.DynamicPageResources.PayOnline_PayResultTenpayMed_ToPayNo);
        }
        if (payResult)
        {
            PayOnline payOnline = new PayOnline();
            PayOnlineState payOnlineState = payOnline.UpdateOrder(attach, DataConverter.ToDecimal(v_amount), "", payOnlinestatus, "", updateDeliverStatus, updateOrderStatus);
            if (payOnlineState == PayOnlineState.Ok)
            {
                message.Append(payOnline.Message);
            }
            else
            {
                message.Append(PayOnline.GetStateDescription(payOnlineState));
            }
        }
       LblMsg.Text = message.ToString();
       PowerEasy.Module.Shop.BusinessLogic.PayOnline.TestLog(false, Resources.DynamicPageResources.PayOnline_PayResultTenpayMed_FastToPay, status, md5_sign.ToUpper(), md5string.ToUpper());
   }
    
    /// <summary>
    /// 添加参数,惹参数值不为空串,则添加。反之,不添加。
    /// </summary>
    private StringBuilder AddParameter(StringBuilder buf, String parameterName, String parameterValue)
    {
        if (null == parameterValue || "".Equals(parameterValue))
        {
            return buf;
        }

        if ("".Equals(buf.ToString()))
        {
            buf.Append(parameterName);
            buf.Append("=");
            buf.Append(parameterValue);
        }
        else
        {
            buf.Append("&");
            buf.Append(parameterName);
            buf.Append("=");
            buf.Append(parameterValue);
        }
        return buf;
    }

    protected void BtnShowOrder_Click(object sender, EventArgs e)
    {
        int orderId = Convert.ToInt32(PEContext.Current.Context.Session["OrderID"]);
        if (orderId > 0)
        {
            if (PEContext.Current.User.Identity.IsAuthenticated)
            {
                DynamicResponseRedirect("../User/Shop/ShowOrder.aspx?OrderId=" + orderId.ToString());
            }
            else
            {
                OrderInfo orderInfo = Order.GetOrderById(orderId);
                DynamicResponseRedirect("OrderForm.aspx?OrderNum=" + orderInfo.OrderNum + "&Name=" + orderInfo.ContacterName);
            }
        }

    }

    protected void BtnReturn_Click(object sender, EventArgs e)
    {
        ShopConfig shopConfig = SiteConfig.ShopConfig;
        string returnUrl = shopConfig.AgainBuyUrl;
        if (string.IsNullOrEmpty(returnUrl))
        {
            returnUrl = "~/Category.aspx?id=4";
        }
        DynamicResponseRedirect(returnUrl);
    }

    protected void BtnGotoUserCenter_Click(object sender, EventArgs e)
    {
        DynamicResponseRedirect("~/User/Default.aspx");
    }

    protected void BtnShowPayRecord_Click(object sender, EventArgs e)
    {
        DynamicResponseRedirect("~/User/Info/PaymentLog.aspx");
    }
    
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title><asp:Localize ID="Localize1" Text="<%$ Res: PayOnline_PayResultTenpayMed_Page , 财付通中介支付 %>" runat="server" /></title>
</head>
<body>
    <form id="form1" runat="server">
    <!--支付成功消息-->
    <div class="ebuycar_order">
        <div class="orderinfo_show">
            <ul class="ebuy_complete">
                <li><span class="p_orderform_mess">
                    <pe:ExtendedLabel HtmlEncode="false" ID="LblMsg" runat="server" ></pe:ExtendedLabel>
                </span></li>
            </ul>
        </div>
        <div class="orderinfo_button">
            <asp:Button ID="BtnReturn" runat="server" OnClick="BtnReturn_Click" CssClass="inputbutton"
                Text="<%$ Res: Shop_OrderSuccess_BtnReturn,返回商店首页 %>" />
            <asp:Button ID="BtnShowOrder" runat="server" OnClick="BtnShowOrder_Click" CssClass="inputbutton"
                Text="<%$ Res: Shop_OrderSuccess_BtnShowOrder,查看订单明细 %>" />
            <asp:Button ID="BtnShowPayRecord" runat="server" OnClick="BtnShowPayRecord_Click" CssClass="inputbutton"
            Text="查看支付明细" />
            <asp:Button ID="BtnGotoUserCenter" runat="server" OnClick="BtnGotoUserCenter_Click"
                CssClass="inputbutton" Text="<%$ Res: Shop_OrderSuccess_BtnGotoUserCenter,进入会员中心 %>" />
            <asp:HiddenField ID="HdnContacterName" runat="server" />
            <asp:HiddenField ID="HdnOrderNum" runat="server" />
        </div>
    </div>    
    </form>
</body>
</html>
