using Alipay.AopSdk.Core;
using Alipay.AopSdk.Core.Domain;
using Alipay.AopSdk.Core.Request;
using Alipay.AopSdk.Core.Util;
using Hncore.Infrastructure.Common;
using Hncore.Infrastructure.Serializer;
using Hncore.Infrastructure.WebApi;
using Hncore.Pass.PaymentCenter.Model;
using Hncore.Pass.PaymentCenter.Pay.WxPay;
using Hncore.Pass.PaymentCenter.WxPay.WechatJsPay;
using Hncore.Pass.Vpn.Domain;
using Hncore.Pass.Vpn.Request.Product;
using Hncore.Pass.Vpn.Response.Product;
using Hncore.Pass.Vpn.Service;
using Home.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;
using Hncore.Infrastructure.Extension;
namespace Home.Controllers
{

    public class productController : MvcBaseController
    {
        string Ali_APP_ID ="";
        string Ali_APP_PRIVATE_KEY = "";      
        string ALIPAY_PUBLIC_KEY = "";

        string Wx_AppId = "";
        string Wx_MchId = "";
        string Wx_MchKey = "";      

        ProductService m_ProductService;
        ProductPackageService m_ProductPackageService;
        private ProductOrderService m_ProductOrderService;
        private IConfiguration m_Configuration;
        private WxPayClient m_WxPayClient;
        ProductAccountService m_ProductAccountService;
        WxAppUserService m_WxAppUserService;
        UserService m_UserService;
        ProductUserPriceService m_ProductUserPriceService;
        ProductPriceSchemeService m_ProductPriceSchemeService;
        public productController(ProductService _ProductService
            , ProductOrderService _ProductOrderService
            , ProductPriceSchemeService _ProductPriceSchemeService
            , ProductPackageService _ProductPackageService
            , WxPayClient _WxPayClient
            ,ProductAccountService _ProductAccountService
            , WxAppUserService _WxAppUserService
            ,UserService _UserService
            , ProductUserPriceService _ProductUserPriceService
            , IConfiguration _Configuration)
        {
            m_ProductService = _ProductService;
            m_ProductOrderService = _ProductOrderService;
            m_ProductPriceSchemeService = _ProductPriceSchemeService;
            m_ProductPackageService = _ProductPackageService;
            m_Configuration = _Configuration;
            m_WxPayClient = _WxPayClient;
            Ali_APP_ID = m_Configuration["Aliyun:Pay:AppId"];
            Ali_APP_PRIVATE_KEY = m_Configuration["Aliyun:Pay:PrivateKey"];
            ALIPAY_PUBLIC_KEY = m_Configuration["Aliyun:Pay:PublicKey"];//支付宝的公钥，而不是应用的公钥

            Wx_AppId = m_Configuration["WxApps:AppID"];
            Wx_MchId = m_Configuration["WxApps:MchId"];
            Wx_MchKey = m_Configuration["WxApps:MchKey"];          

            m_ProductAccountService = _ProductAccountService;
            m_WxAppUserService = _WxAppUserService;
            m_UserService = _UserService;
            m_ProductUserPriceService = _ProductUserPriceService;
        }

        [HttpGet]
        public async Task<IActionResult> Index()
        {
            var respList = await m_ProductService.ProductWithPackage(1);
            
            var userInfo = this.Request.GetUserInfo();
            if (userInfo != null)
            {
                
                //从user表获取用户信息
                var user_Info = await m_UserService.GetById(userInfo.UserId);
                var ExpiredProductAccountCount = user_Info.ExpiredProductAccountCount;

                //判断测试卡使用次数是否超过限定次数 false表示免费没用完 true表示免费测试已经用完
                var test_flag = false;
                if ((user_Info.TestCountLimit!=0 && user_Info.TestCountLimit<=user_Info.UseTestCount) || (user_Info.TestCountLimit ==0 && user_Info.UseTestCount>2)) {
                    test_flag = true;
                }
                

                if((user_Info.agent_id == 0||(user_Info.agent_id != 0 && user_Info.discount_id != 0)) && user_Info.discount_id >= 0){
                //根据折扣设置价格

                    var discount  = await m_ProductPriceSchemeService.GetById(user_Info.discount_id);
                    var dis_price = 1000000.0M;
                    foreach(var product in respList)
                    {
                        product.Product.Content = "0";
                        product.Packages.ForEach(m => {

                            if (discount != null)
                            {
                                dis_price = m.LinePrice * discount.discount / 100;
                            }
                            if(dis_price<m.Price){
                                m.Price = dis_price;
                                m.Title = discount.Remark;
                            } else {
                               m.Title = "0";
                            }
                            if(m.Price<m.MinPrice){
                                m.Price = m.MinPrice;
                            }
                            if (ExpiredProductAccountCount == 0 && m.Id == 1012){
                                m.Price = 0.1M;
                            }
                            //判断测试卡是否收费
                            if (test_flag && (m.IsTest == 1)) {
                                m.Price = 1.0M;
                                m.IsTest =0;
                            }
                        });
                        
                        //判断测试卡是否收费
                        if (test_flag) {
                            product.Product.Content = "1";
                        }
                    }  
                } else {
                //根据会员价
                    var userPrices = await m_ProductUserPriceService.GetProductUserPrice(userInfo.UserId);
                    
                    foreach(var product in respList)
                    {
                        product.Product.Content = "0";
                        product.Packages.ForEach(m => {
                            m.Title = "0";

                            var userPrice = userPrices.FirstOrDefault(p => p.PackageId == m.Id && p.ProductId == m.ProductId);
                            if (userPrice != null && userPrice.UserPrice > 0)
                            {
                                m.Price = userPrice.UserPrice;
                            }
                            if (ExpiredProductAccountCount == 0 && m.Id == 1012){
                                m.Price = 0.1M;
                            }
                            //判断测试卡是否收费
                            if (test_flag && (m.IsTest == 1)) {
                                m.Price = 1.0M;
                                m.IsTest =0;
                            }
                        });
                        
                        //判断测试卡是否收费
                        if (test_flag) {
                            product.Product.Content = "1";
                        }
                    }  
                }
            } else {
                foreach(var product in respList)
                {
                    product.Product.Content = "0";
                    product.Packages.ForEach(m => {
                        m.Title = "0";
                        
                        
                    if (m.Id == 1012){
                        m.Price = 0.1M;
                    }
                    });
                }  
            }
            return View(respList);
        }

        [HttpPost,UserAuth]
        public async Task<ApiResult> CreateOrder([FromBody]CreateOrderRequest request)
        {
            var userId = this.Request.GetUserInfo().UserId;
            var ret = await m_ProductOrderService.CreateOrder(request, userId);
            if (ret.Code != ResultCode.C_SUCCESS)
            {
                return ret;
            }
            if (ret.Data.OtherPayAmount == 0)
            {
                await m_ProductOrderService.ProcessOrderAccount(ret.Data);
                return new ApiResult("00");
            }

            var data = new OrderPayModel()
            {
                OrderInfo = ret.Data,
            };           
            if (ret.Data.PayType == PayType.Wechat)
            {
                var url = await CreateWxPayOrder(ret.Data);
                data.PayData = url;
                return new ApiResult(data);
            }
            else
            {
                var body = await CreateAliPayOrder(ret.Data);
                data.PayData = body;
            }
            return new ApiResult(data);
        }

        [HttpPost,AllowAnonymous]
        public async Task<ApiResult> ApiCreateOrder([FromBody]CreateOrderRequest request)
        {
            request.UseAccountAmount = 1;
            request.CouponId = 0;
            //通过apikey获取用户信息
            var userEntity = m_UserService.Query(m => m.apikey == request.apikey).FirstOrDefault();
            if (userEntity == null)
            {
                return new ApiResult(ResultCode.C_INVALID_ERROR, "apikey不正确");
            }
            var userId = userEntity.Id;
            var ret = await m_ProductOrderService.CreateOrder(request, userId);

            if (ret.Code != ResultCode.C_SUCCESS)
            {
                return ret;
            }
            if (ret.Data.OtherPayAmount == 0)
            {
                await m_ProductOrderService.ApiProcessOrderAccount(ret.Data,"api开通");
                return new ApiResult("00");
            }

            return new ApiResult(ResultCode.C_INVALID_ERROR, "未知错误！联系客服解决！");
        }


        #region 微信支付
        private async Task<string> CreateWxPayOrder(ProductOrderEntity request)
        {
            string callBackUrl = m_Configuration["NotifyUrl"];
            var mchInfo = new MchInfo()
            {
                MchId = Wx_MchId,
                Key = Wx_MchKey
            };
            var createOrderRes = "";
            var pName=request.Accounts.Split(",").FirstOrDefault();
            var oName = $"{request.ProductName}-{request.PackageName}";
            if (pName.Has()) oName = $"{oName}-{pName}";
            if (request.PayChannel == PayChannel.WxPc)
            {
                var payRequest = new WxScanPayCreateOrderRequest()
                {
                    AppId = Wx_AppId,
                    Body = oName,
                    MchId = Wx_MchId,
                    NotifyUrl = callBackUrl,
                    OutTradeNo = request.OrderNo,
                    StoreId = 2,
                    TenantId = 1157,
                    TotalFee = (int)(request.OtherPayAmount * 100),
                    ProductId = request.ProductId.ToString(),
                    TimeExpire=DateTime.Now.AddMinutes(15).ToString("yyyyMMddHHmmss")
                };
                createOrderRes = await m_WxPayClient.ScanPayCreateOrderAsync(payRequest, mchInfo);
            }
            else if (request.PayChannel == PayChannel.WxH5)
            {
                var payRequest = new WxH5PayCreateOrderRequest()
                {
                    AppId = Wx_AppId,
                    Body = oName,
                    MchId = Wx_MchId,
                    NotifyUrl = callBackUrl,
                    OutTradeNo = request.OrderNo,
                    StoreId = 2,
                    TenantId = 1157,
                    TotalFee = (int)(request.OtherPayAmount * 100),
                    ProductId = request.ProductId.ToString(),
                    TimeExpire = DateTime.Now.AddMinutes(15).ToString("yyyyMMddHHmmss")
                };
                createOrderRes = await m_WxPayClient.H5PayCreateOrderAsync(payRequest, mchInfo);
            }
            else
            {
                var wxUserInfo = await m_WxAppUserService.GetWxUser(Wx_AppId, request.UserId);
                var payRequest = new WxJsPayCreateOrderRequest()
                {
                    AppId = Wx_AppId,
                    Body = oName,
                    MchId = Wx_MchId,
                    NotifyUrl = callBackUrl,
                    OutTradeNo = request.OrderNo,
                    StoreId = 2,
                    TenantId = 1157,
                    TotalFee = (int)(request.OtherPayAmount * 100),
                    UserOpenId = wxUserInfo.Openid,
                    TimeExpire = DateTime.Now.AddMinutes(15).ToString("yyyyMMddHHmmss")
                };
                createOrderRes = await m_WxPayClient.JsPayCreateOrderAsync(payRequest, mchInfo);
            }
            return createOrderRes;
        }

        [HttpPost, AllowAnonymous]
        public async Task<string> WxOrderCallBack()
        {
            try
            {
                string xml = "";
                LogHelper.Trace("微信支付回调开始", "Notify");
                if (Request.Body.CanSeek)
                {
                    Request.Body.Position = 0;
                }

                using (System.IO.StreamReader reader = new System.IO.StreamReader(Request.Body))
                {
                    xml = reader.ReadToEnd();
                }

                LogHelper.Trace("微信支付回调，原始数据：", $"{xml}");

                WxPayChecker payData = new WxPayChecker();


                payData.FromXmlNoCheckSign(xml);

                if (!payData.IsSet("out_trade_no"))
                {
                    return FailXml();
                }

                // 给支付平台的订单号为支付记录id
                string orderId = payData["out_trade_no"];

                string TransactionId = payData["transaction_id"];

                var order = await m_ProductOrderService.GetOrderByNo(orderId);         
                if(order.OrderState== OrderStatus.Complete|| order.OrderState == OrderStatus.PayOk)
                    return SuccessXml();

                var queryRet = await m_WxPayClient.OrderQuery(new WxJsPayOrderQueryRequest()
                {
                    AppId = Wx_AppId,                 
                    NonceStr = payData.GenerateNonceStr(),
                    TransactionId = TransactionId
                }, new MchInfo() { MchId = Wx_MchId, Key = Wx_MchKey });
                if (!queryRet) return FailXml();


                payData.MchKey = Wx_MchKey;
                if (!payData.CheckSign()) return FailXml();
                order.OrderState = OrderStatus.PayOk;
                order.TradeNo = TransactionId;
                order.UpdateTime = DateTime.Now;
                await m_ProductOrderService.Update(order);
                await m_ProductOrderService.ProcessOrderAccount(order);
            }
            catch (Exception e)
            {
                LogHelper.Error("微信支付通知处理失败", e);

                return FailXml();
            }
            return SuccessXml();
        }

        public string FailXml()
        {
            return "<xml><return_code>FAIL</return_code> </xml>";
        }

        private string SuccessXml()
        {
            return "<xml><return_code>SUCCESS</return_code> </xml>";
        }

        #endregion


        #region 阿里支付
        private async Task<string> CreateAliPayOrder(ProductOrderEntity request)
        {
            string callBackUrl = m_Configuration["Aliyun:Pay:NotifyUrl"];
            string ReturnUrl = m_Configuration["Aliyun:Pay:ReturnUrl"];

            var pName = request.Accounts.Split(",").FirstOrDefault();
            var oName = $"{request.ProductName}-{request.PackageName}";
            if (pName.Has()) oName = $"{oName}-{pName}";
            if (request.PayChannel == PayChannel.AliPc)
            {
                // 组装业务参数model
                AlipayTradePagePayModel model = new AlipayTradePagePayModel
                {
                    Body = request.PackageName,
                    Subject = oName,
                    TotalAmount = decimal.Round(decimal.Parse(request.OtherPayAmount.ToString()),2).ToString(),
                    OutTradeNo = request.OrderNo,
                    ProductCode = "FAST_INSTANT_TRADE_PAY",//QUICK_WAP_PAY
                    TimeoutExpress="15m"
                };

                AlipayTradePagePayRequest aliRequest = new AlipayTradePagePayRequest();
                // 设置同步回调地址
                aliRequest.SetReturnUrl(ReturnUrl);
                // 设置异步通知接收地址
                aliRequest.SetNotifyUrl(callBackUrl);
                // 将业务model载入到request
                aliRequest.SetBizModel(model);

                var _aopClient = new DefaultAopClient("https://openapi.alipay.com/gateway.do", Ali_APP_ID, Ali_APP_PRIVATE_KEY);

                var response = await _aopClient.PageExecuteAsync(aliRequest);

                return response.Body;

            }
            else if (request.PayChannel == PayChannel.AliH5)
            {
                Ali_APP_ID = m_Configuration["Aliyun:PayH5:AppId"];
                Ali_APP_PRIVATE_KEY = m_Configuration["Aliyun:PayH5:PrivateKey"];
                ALIPAY_PUBLIC_KEY = m_Configuration["Aliyun:PayH5:PublicKey"];

                callBackUrl = m_Configuration["Aliyun:PayH5:NotifyUrl"];
                ReturnUrl = m_Configuration["Aliyun:PayH5:ReturnUrl"];              

                // 组装业务参数model
                AlipayTradeWapPayModel model = new AlipayTradeWapPayModel
                {
                    Body = request.PackageName,
                    Subject = oName,
                    TotalAmount = request.OtherPayAmount.ToString(),
                    OutTradeNo = request.OrderNo,
                    ProductCode = "QUICK_WAP_PAY",
                    QuitUrl =this.Request.GetUrl(),
                    TimeoutExpress = "15m"
                };

                AlipayTradeWapPayRequest aliRequest = new AlipayTradeWapPayRequest();
                // 设置同步回调地址
                aliRequest.SetReturnUrl(ReturnUrl);
                // 设置异步通知接收地址
                aliRequest.SetNotifyUrl(callBackUrl);
                // 将业务model载入到request
                aliRequest.SetBizModel(model);

                var _aopClient = new DefaultAopClient("https://openapi.alipay.com/gateway.do", Ali_APP_ID, Ali_APP_PRIVATE_KEY);

                var response = await _aopClient.PageExecuteAsync(aliRequest);

                return response.Body;
            }
            return "";
        }

        /// <summary>
        /// 支付同步回调
        /// </summary>
        [HttpGet, AllowAnonymous]
        public IActionResult AliReturn()
        {
            /* 实际验证过程建议商户添加以下校验。
            1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
            2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
            3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
            4、验证app_id是否为该商户本身。
            */


            Dictionary<string, string> sArray = GetRequestGet();
            if (sArray.Count != 0)
            {
                bool flag = AlipaySignature.RSACheckV2(sArray, ALIPAY_PUBLIC_KEY, "utf-8", "RSA2", false);
                if (flag)
                {
                    var ordereNo = sArray["out_trade_no"];
                   // var order = await m_ProductOrderService.GetOrderByNo(ordereNo);
                    Console.WriteLine($"同步验证通过，订单号：{sArray["out_trade_no"]}");
                    ViewData["PayResult"] = "同步验证通过";
                }
                else
                {
                    Console.WriteLine($"同步验证失败，订单号：{sArray["out_trade_no"]}");
                    ViewData["PayResult"] = "同步验证失败";
                }
            }
            return Redirect("~/User/MyAccounts");
        }

        [HttpPost, AllowAnonymous]
        public async Task AliNotify()
        {
            /* 实际验证过程建议商户添加以下校验。
            1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
            2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
            3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
            4、验证app_id是否为该商户本身。
            */
            Dictionary<string, string> sArray = GetRequestPost();
           
            LogHelper.Info("AliNotify", AlipaySignature.GetSignContent(sArray));
            if (sArray.Count != 0)
            {
           //     bool flag = AlipaySignature.RSA2Check(sArray, ALIPAY_PUBLIC_KEY);
                bool flag = AlipaySignature.RSACheckV2(sArray, ALIPAY_PUBLIC_KEY, "utf-8", "RSA2", false);
                if (flag)
                {
                    //交易状态
                    //判断该笔订单是否在商户网站中已经做过处理
                    //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                    //请务必判断请求时的total_amount与通知时获取的total_fee为一致的
                    //如果有做过处理，不执行商户的业务程序

                    //注意：
                    //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
                    try
                    {
                        var ordereNo = sArray["out_trade_no"];
                        var order = await m_ProductOrderService.GetOrderByNo(ordereNo);
                        if (order.OrderState == OrderStatus.Complete|| order.OrderState == OrderStatus.PayOk)
                        {
                            await Response.WriteAsync("success");
                            return;
                        }                        

                        order.OrderState = OrderStatus.PayOk;
                        order.TradeNo = sArray["trade_no"];
                        order.UpdateTime = DateTime.Now;
                        await m_ProductOrderService.Update(order);
                        await m_ProductOrderService.ProcessOrderAccount(order);

                        Console.WriteLine(Request.Form["trade_status"]);

                        await Response.WriteAsync("success");
                    }catch(Exception ex)
                    {
                        LogHelper.Error("AliNotify.Exception", ex.Message);
                        await Response.WriteAsync("fail");
                    }
                    
                }
                else
                {
                    LogHelper.Error("AliNotify.Error", "签名校验失败");
                    await Response.WriteAsync("fail");
                }
            }
        }


        /// <summary>
        /// 支付同步回调
        /// </summary>
        [HttpGet, AllowAnonymous]
        public IActionResult AliReturnH5()
        {
            /* 实际验证过程建议商户添加以下校验。
            1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
            2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
            3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
            4、验证app_id是否为该商户本身。
            */           
            ALIPAY_PUBLIC_KEY = m_Configuration["Aliyun:PayH5:PublicKey"];


            Dictionary<string, string> sArray = GetRequestGet();
            if (sArray.Count != 0)
            {
                bool flag = AlipaySignature.RSACheckV2(sArray, ALIPAY_PUBLIC_KEY, "utf-8", "RSA2", false);
                if (flag)
                {
                    var ordereNo = sArray["out_trade_no"];
                    // var order = await m_ProductOrderService.GetOrderByNo(ordereNo);
                    Console.WriteLine($"同步验证通过，订单号：{sArray["out_trade_no"]}");
                    ViewData["PayResult"] = "同步验证通过";
                }
                else
                {
                    Console.WriteLine($"同步验证失败，订单号：{sArray["out_trade_no"]}");
                    ViewData["PayResult"] = "同步验证失败";
                }
            }
            return Redirect("~/User/MyAccounts");
        }

        [HttpPost, AllowAnonymous]
        public async Task AliNotifyH5()
        {
            /* 实际验证过程建议商户添加以下校验。
            1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
            2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
            3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
            4、验证app_id是否为该商户本身。
            */
            ALIPAY_PUBLIC_KEY = m_Configuration["Aliyun:PayH5:PublicKey"];
            Dictionary<string, string> sArray = GetRequestPost();
            LogHelper.Info("AliNotify", AlipaySignature.GetSignContent(sArray));
            if (sArray.Count != 0)
            {
                //     bool flag = AlipaySignature.RSA2Check(sArray, ALIPAY_PUBLIC_KEY);
                bool flag = AlipaySignature.RSACheckV2(sArray, ALIPAY_PUBLIC_KEY, "utf-8", "RSA2", false);
                if (flag)
                {
                    //交易状态
                    //判断该笔订单是否在商户网站中已经做过处理
                    //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                    //请务必判断请求时的total_amount与通知时获取的total_fee为一致的
                    //如果有做过处理，不执行商户的业务程序

                    //注意：
                    //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
                    try
                    {
                        var ordereNo = sArray["out_trade_no"];
                        var order = await m_ProductOrderService.GetOrderByNo(ordereNo);
                        if (order.OrderState == OrderStatus.Complete || order.OrderState == OrderStatus.PayOk)
                        {
                            await Response.WriteAsync("success");
                            return;
                        }
                           

                        order.OrderState = OrderStatus.PayOk;
                        order.TradeNo = sArray["trade_no"];
                        order.UpdateTime = DateTime.Now;
                        await m_ProductOrderService.Update(order);
                        await m_ProductOrderService.ProcessOrderAccount(order);

                        Console.WriteLine(Request.Form["trade_status"]);

                        await Response.WriteAsync("success");
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Error("AliNotify.Exception", ex.Message);
                        await Response.WriteAsync("fail");
                    }

                }
                else
                {
                    LogHelper.Error("AliNotify.Error", "签名校验失败");
                    await Response.WriteAsync("fail");
                }
            }
        }




        private Dictionary<string, string> GetRequestGet()
        {
            Dictionary<string, string> sArray = new Dictionary<string, string>();

            ICollection<string> requestItem = Request.Query.Keys;
            foreach (var item in requestItem)
            {
                sArray.Add(item, Request.Query[item]);

            }
            return sArray;

        }


        private Dictionary<string, string> GetRequestPost()
        {
            Dictionary<string, string> sArray = new Dictionary<string, string>();

            ICollection<string> requestItem = Request.Form.Keys;
            foreach (var item in requestItem)
            {
                sArray.Add(item, Request.Form[item]);

            }
            return sArray;

        }

        #endregion



        //[HttpGet]
        //public async Task<IActionResult> Success()
        //{
        //    return Content("Success");
        //}

        //[HttpGet]
        //public async Task<IActionResult> ErrorInfo()
        //{
        //    return Content("Error");
        //}

        [HttpGet, UserAuth]
        public async Task<IActionResult> TestIndex(int id)
        {
            var userId = this.Request.GetUserInfo().UserId;
            var product = new ProductEntity();
            var package = new ProductPackageEntity();
            if (id==1034||id==1040){
                package = await m_ProductPackageService.Query(m => m.Id == id).FirstOrDefaultAsync();
                product = await m_ProductService.GetById(package.ProductId);
            } else {
                product = await m_ProductService.GetById(id);
                package = await m_ProductPackageService.Query(m => m.IsTest == 1 && m.ProductId == id).FirstOrDefaultAsync();
            }
            var restTimes = await m_ProductAccountService.GetRestTestCount(userId);

            return View("Test", new PackageInfoResponse()
            {
                Package = package,
                Product = product,
                RestTimes = restTimes
            });
        }


        [HttpGet, UserAuth]
        public async Task<IActionResult> Test(int id)
        {
            var product = new ProductEntity();
            var package = new ProductPackageEntity();
            if (id==1034||id==1040){
                package = await m_ProductPackageService.Query(m => m.Id == id).FirstOrDefaultAsync();
                product = await m_ProductService.GetById(package.ProductId);
            } else {
                product = await m_ProductService.GetById(id);
                package = await m_ProductPackageService.Query(m => m.IsTest == 1 && m.ProductId == id).FirstOrDefaultAsync();
            }
            var restTimes = 0;
            var userInfo = this.Request.GetUserInfo();
            if (userInfo != null)
            {
                var userId = userInfo.UserId;
                restTimes = await m_ProductAccountService.GetRestTestCount(userId);
            }
            return View("Test", new PackageInfoResponse()
            {
                Package = package,
                Product = product,
                RestTimes = restTimes
            });
        }


        [HttpGet]
        public async Task<IActionResult> Soft()
        {
            var ret = await m_ProductService.Query(true).ToListAsync();
            return View(ret);
        }

        [HttpGet]
        public async Task<IActionResult> Routeros()
        {
            return View();
        }

        [HttpGet, AllowAnonymous]
        public async Task<ApiResult> IsPay(string orderNo)
        {
           var orderInfo=await m_ProductOrderService.GetOrderByNo(orderNo);
            if (orderInfo.OrderState == OrderStatus.PayOk || orderInfo.OrderState == OrderStatus.Complete)
                return new ApiResult(1);
            else
                return new ApiResult(0);
        }

        [HttpGet,UserAuth]
        public async Task<IActionResult> Buy(int id)
        {
            var userId = this.Request.GetUserInfo().UserId;
            var package = await m_ProductPackageService.GetById(id);
            var product = await m_ProductService.GetById(package.ProductId);

            //从user表获取用户信息
            var user_Info = await m_UserService.GetById(userId);
            var ExpiredProductAccountCount = user_Info.ExpiredProductAccountCount; 

            var dis_price = 1000000M;
            if((user_Info.agent_id == 0||(user_Info.agent_id != 0 && user_Info.discount_id != 0)) && user_Info.discount_id >= 0){
            //根据折扣设置价格
                var discount  = await m_ProductPriceSchemeService.GetById(user_Info.discount_id);
                if (discount != null)
                {
                    dis_price = package.LinePrice * discount.discount / 100;
                }
            } else {
            //根据会员价
                var userPrice = await m_ProductUserPriceService.GetPackageUserPrice(package.Id, userId);
                if (userPrice != null && userPrice.UserPrice > 0)
                {
                    dis_price = userPrice.UserPrice;
                }
            }
            if(dis_price<package.Price){
                package.Price = dis_price;
            }
            if(package.Price<package.MinPrice){
                package.Price = package.MinPrice;
            }

            if (ExpiredProductAccountCount == 0 &&package.Id == 1012){
                package.Price = 0.1M;
            }

            return View("buy", new PackageInfoResponse()
            {

                Package = package,
                Product = product
            });
        }

        [HttpGet]
        public async Task<IActionResult> ReBuyIndex(string accounts,int productId=0)
        {
            ViewBag.accounts = "";
            ViewBag.errorTip = "";
            var model = new ProductWithPackageResponse();
            if (accounts.NotHas())
            {
                ViewBag.errorTip = "请选择账号";
                return View(model);
            }
            var accountList = await m_ProductAccountService.GetAccounts(accounts);

            if (productId > 0)
                accountList = accountList.Where(m => m.ProductId == productId).ToList();
            var productIds = accountList.Select(m => m.ProductId);
            var connectCountList = accountList.Select(m => m.ConnectCount);
            if (productIds.Distinct().Count() != 1 || connectCountList.Distinct().Count() != 1)
            {
                ViewBag.errorTip = "续费账号必须为同一种产品且相同的连接数";
                return View(model);
            }
            ViewBag.accounts = accounts;
            var id = productIds.First().Value;

            //0 无状态 1：尊享 2：高级 3：普通
            var pro_type_flag = 0;
            var pro_type_temp = 0;
            if (productId == 14) {

                
                
                accountList.ForEach(m => {
                    
                    
                    if (m.PackageId<1034) {
                        pro_type_flag = 1;
                    }
                    if (m.PackageId>1034&&m.PackageId<1040) {
                        pro_type_flag = 2;
                    }
                    if (m.PackageId>1040&&m.PackageId<1046) {
                        pro_type_flag = 3;
                    }
                    
                    if (pro_type_temp==0){
                        pro_type_temp = pro_type_flag;
                    }
                    if (pro_type_temp!=pro_type_flag){
                        ViewBag.errorTip = "天天不同类型不能同时续费";
                    }

                });
                
                if (ViewBag.errorTip == "天天不同类型不能同时续费"){
                    return View(model);
                }
            }

            


            var respList = await m_ProductService.GetOneProductWithPackage(id);

            var resp = new ProductWithPackageResponse();

            var return_list =  new ProductWithPackageResponse();
            return_list.Product = respList.Product;

            var package_temp = new List<ProductPackageEntity>();

            var userInfo = this.Request.GetUserInfo();
            if (userInfo != null)
            {

                
                //从user表获取用户信息
                var user_Info = await m_UserService.GetById(userInfo.UserId);

                if((user_Info.agent_id == 0||(user_Info.agent_id != 0 && user_Info.discount_id != 0)) && user_Info.discount_id >= 0){
                //根据折扣设置价格

                    var discount  = await m_ProductPriceSchemeService.GetById(user_Info.discount_id);
                    var dis_price = 1000000.0M;

                        respList.Packages.ForEach(m => {

                            

                            if (discount != null)
                            {
                                dis_price = m.LinePrice * discount.discount / 100;
                            }
                            if(dis_price<m.Price){
                                m.Price = dis_price;
                                m.Title = discount.Remark;
                            } else {
                                m.Title = "9.5";
                                if (m.ProductId == 1||m.ProductId == 2){
                                    m.Title = "7.5";
                                }
                                if (m.ProductId == 18){
                                    m.Title = "7.5";
                                }
                                if (m.ProductId == 6||m.ProductId == 5){
                                    m.Title = "9";
                                }
                                if (m.ProductId == 23||m.ProductId == 13||m.ProductId == 14||m.ProductId == 17){
                                    m.Title = "8";
                                }
                            }
                            if(m.Price<m.MinPrice){
                                m.Price = m.MinPrice;
                            }

                            if (m.ProductId == 14){
                                if (pro_type_temp ==1 && m.Id<1034) {
                                    package_temp.Add(m);
                                }
                                if (pro_type_temp ==2 && m.Id>1034&&m.Id<1040) {
                                    package_temp.Add(m);
                                }
                                if (pro_type_temp ==3 && m.Id>1040&&m.Id<1046) {
                                    package_temp.Add(m);
                                }
                            }else {
                                package_temp.Add(m);
                            }
                            
                        });

                } else {
                //根据会员价
                    var userPrices = await m_ProductUserPriceService.GetProductUserPrice(id, userInfo.UserId);
                    respList.Packages.ForEach(m =>
                    {
                        

                        m.Title = "9.5";
                        if (m.ProductId == 1||m.ProductId == 2){
                            m.Title = "7.5";
                        }
                        if (m.ProductId == 18){
                            m.Title = "7.5";
                        }
                        if (m.ProductId == 6||m.ProductId == 5){
                            m.Title = "9";
                        }
                        if (m.ProductId == 23||m.ProductId == 13||m.ProductId == 14||m.ProductId == 17){
                            m.Title = "8";
                        }
                        var userPrice = userPrices.FirstOrDefault(p => p.PackageId == m.Id);
                        if (userPrice != null && userPrice.UserPrice > 0)
                        {
                            m.Price = userPrice.UserPrice;
                        }

                        if (m.ProductId == 14){
                            if (pro_type_temp ==1 && m.Id<1034) {
                                package_temp.Add(m);
                            }
                            if (pro_type_temp ==2 && m.Id>1034&&m.Id<1040) {
                                package_temp.Add(m);
                            }
                            if (pro_type_temp ==3 && m.Id>1040&&m.Id<1046) {
                                package_temp.Add(m);
                            }
                        }else {
                            package_temp.Add(m);
                        }
                    });
                }

               
            }
            return_list.Packages = package_temp;
            return View(return_list);
        }

        [HttpGet,UserAuth]
        public async Task<IActionResult> ReBuy(int packageId, string accounts)
        {
            var package = await m_ProductPackageService.GetById(packageId);
            var product = await m_ProductService.GetById(package.ProductId);

            var account = "";
            if (accounts.IndexOf(",") == -1)
            {
                account = accounts;
            }
            else
            {
                account = accounts.Split(',')[0];
            }
            var accountEntity = await m_ProductAccountService.GetProductAccountInfo(package.ProductId, account);

            var userId = this.Request.GetUserInfo().UserId;

            var user_Info = await m_UserService.GetById(userId);
            var dis_price = 1000000M;
            if((user_Info.agent_id == 0||(user_Info.agent_id != 0 && user_Info.discount_id != 0)) && user_Info.discount_id >= 0){
            //根据折扣设置价格
                var discount  = await m_ProductPriceSchemeService.GetById(user_Info.discount_id);
                if (discount != null)
                {
                    dis_price = package.LinePrice * discount.discount / 100;
                }
            } else {
            //根据会员价
                var userPrice = await m_ProductUserPriceService.GetPackageUserPrice(packageId, userId);
                if (userPrice != null && userPrice.UserPrice > 0)
                {
                    dis_price = userPrice.UserPrice;
                }
            }
            if(dis_price<package.Price){
                package.Price = dis_price;
            }
            
            if(package.Price<package.MinPrice){
                package.Price = package.MinPrice;
            }
            

            var model = new PackageInfoResponse()
            {
                Package = package,
                Product = product
            };
            ViewBag.accounts = accounts;
            ViewBag.orderType = accounts.Split(",").Count() > 1 ? 4 : 3;
            ViewBag.ConnectCount = accountEntity == null ? 1 : accountEntity.ConnectCount;
            return View(model);
        }
    }
}
