using System;
using System.Web.Routing;
using System.Collections.Generic;

using BrnShop.Core;
using BrnShop.PayPlugin.Alipay.Code;

namespace BrnShop.PayPlugin.Alipay
{
    /// <summary>
    /// 插件服务类
    /// </summary>
    public class PluginService : IPayPlugin
    {
        /// <summary>
        /// 插件配置控制器
        /// </summary>
        /// <value></value>
        public string ConfigController
        {
            get { return "AdminAlipay"; }
        }
        /// <summary>
        /// 插件配置动作方法
        /// </summary>
        /// <value></value>
        public string ConfigAction
        {
            get { return "Config"; }
        }
        /// <summary>
        /// 插件配置路由数据
        /// </summary>
        /// <value></value>
        public RouteValueDictionary ConfigRouteValues
        {
            get { return new RouteValueDictionary() { { "area", "Admin" } }; }
        }
        /// <summary>
        /// 付款方式(0代表货到付款,1代表在线付款,2代表线下付款)
        /// </summary>
        /// <value></value>
        public int PayMode
        {
            get { return 1; }
        }
        /// <summary>
        /// 是否允许账户充值(只对在线付款有效)
        /// </summary>
        /// <value></value>
        public bool AllowRecharge
        {
            get { return PluginUtils.GetPluginSet().AllowRecharge == 1; }
        }
        /// <summary>
        /// 支付返回控制器
        /// </summary>
        /// <value></value>
        public string ReturnController
        {
            get { return "Alipay"; }
        }
        /// <summary>
        /// 支付返回动作方法
        /// </summary>
        /// <value></value>
        public string ReturnAction
        {
            get { return "Return"; }
        }
        /// <summary>
        /// 支付返回路由数据
        /// </summary>
        /// <value></value>
        public RouteValueDictionary ReturnRouteValues
        {
            get { return null; }
        }
        /// <summary>
        /// 支付通知控制器
        /// </summary>
        /// <value></value>
        public string NotifyController
        {
            get { return "Alipay"; }
        }
        /// <summary>
        /// 支付通知动作方法
        /// </summary>
        /// <value></value>
        public string NotifyAction
        {
            get { return "Notify"; }
        }
        /// <summary>
        /// 支付通知路由数据
        /// </summary>
        /// <value></value>
        public RouteValueDictionary NotifyRouteValues
        {
            get { return null; }
        }
        /// <summary>
        /// 获得支付手续费
        /// </summary>
        /// <param name="productAmount">商品合计</param>
        /// <param name="buyTime">购买时间</param>
        /// <param name="partUserInfo">购买用户</param>
        /// <returns></returns>
        public decimal GetPayFee(decimal productAmount, DateTime buyTime, PartUserInfo partUserInfo)
        {
            return 0M;
        }
        /// <summary>
        /// 如果付款方式为在线付款则返回付款请求的url,否则返回空字符串
        /// </summary>
        /// <param name="notifyUrl">通知url</param>
        /// <param name="returnUrl">返回url</param>
        /// <param name="pluginInfo">插件信息</param>
        /// <param name="partUserInfo">购买用户</param>
        /// <param name="orderInfo">订单信息</param>
        /// <returns></returns>
        public string GetRequestUrl(string notifyUrl, string returnUrl, PluginInfo pluginInfo, PartUserInfo partUserInfo, OrderInfo orderInfo)
        {
            //支付类型,必填,不能修改
            string paymentType = "1";

            //服务器异步通知页面路径,需http://格式的完整路径,不能加?id=123这类自定义参数
            notifyUrl = string.Format("http://{0}{1}", BSPConfig.ShopConfig.SiteUrl, notifyUrl);

            //页面跳转同步通知页面路径,需http://格式的完整路径,不能加?id=123这类自定义参数,不能写成http://localhost/
            returnUrl = string.Format("http://{0}{1}", BSPConfig.ShopConfig.SiteUrl, returnUrl);

            //收款支付宝帐户
            string sellerEmail = AlipayConfig.Seller;

            //合作者身份ID
            string partner = AlipayConfig.Partner;

            //交易安全检验码
            string key = AlipayConfig.Key;

            //商户订单号
            string outTradeNo = orderInfo.Oid.ToString();

            //订单名称
            string subject = "";

            //付款金额
            string totalFee = orderInfo.SurplusMoney.ToString();

            //订单描述
            string body = "";

            //防钓鱼时间戳,若要使用请调用类文件submit中的query_timestamp函数
            string anti_phishing_key = "";

            //客户端的IP地址,非局域网的外网IP地址,如:221.0.0.1
            string exter_invoke_ip = "";

            //把请求参数打包成数组
            SortedDictionary<string, string> sParaTemp = new SortedDictionary<string, string>();
            sParaTemp.Add("partner", partner);
            sParaTemp.Add("_input_charset", key);
            sParaTemp.Add("service", "create_direct_pay_by_user");
            sParaTemp.Add("payment_type", paymentType);
            sParaTemp.Add("notify_url", notifyUrl);
            sParaTemp.Add("return_url", returnUrl);
            sParaTemp.Add("seller_email", sellerEmail);
            sParaTemp.Add("out_trade_no", outTradeNo);
            sParaTemp.Add("subject", subject);
            sParaTemp.Add("total_fee", totalFee);
            sParaTemp.Add("body", body);
            sParaTemp.Add("anti_phishing_key", anti_phishing_key);
            sParaTemp.Add("exter_invoke_ip", exter_invoke_ip);

            return AlipaySubmit.BuildRequestUrl(sParaTemp, AlipayConfig.Gateway, AlipayConfig.InputCharset, AlipayConfig.SignType, AlipayConfig.Key, AlipayConfig.Code);
        }
    }

    /// <summary>
    /// 插件工具类
    /// </summary>
    public class PluginUtils
    {
        private static object _locker = new object();//锁对象
        private static PluginSetInfo _pluginsetinfo = null;//插件设置信息
        private static string _plugindatafilepath = "/Plugins/BrnShop.PayPlugin.Alipay/PluginData.config";//数据文件路径

        /// <summary>
        ///获得插件设置
        /// </summary>
        /// <returns></returns>
        public static PluginSetInfo GetPluginSet()
        {
            if (_pluginsetinfo == null)
            {
                lock (_locker)
                {
                    if (_pluginsetinfo == null)
                    {
                        _pluginsetinfo = (PluginSetInfo)IOHelper.DeserializeFromXML(typeof(PluginSetInfo), IOHelper.GetMapPath(_plugindatafilepath));
                    }
                }
            }
            return _pluginsetinfo;
        }

        /// <summary>
        /// 保存插件设置到数据数据文件中
        /// </summary>
        public static void SavePluginSet(PluginSetInfo pluginSetInfo)
        {
            lock (_locker)
            {
                IOHelper.SerializeToXml(pluginSetInfo, IOHelper.GetMapPath(_plugindatafilepath));
                _pluginsetinfo = null;
                AlipayConfig.ReSet();
            }
        }

    }
}