using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Linq;
using Mall.Common;
using Mall.Common.API;
using Mall.Common.Pay.WeChatPat;
using Mall.Common.Pay.WeChatPat.Model;
using Mall.Common.Plugin;
using Mall.Model.Extend.Product;
using Mall.Model.Extend.User;
using Mall.Module.User;
using Mall.WebApi.Filter;
using Mall.WeChat.Helper;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Mall.WebApi.Controllers.AppletWeChat
{

    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class WeChatPayController : BaseController
    {
        private IHttpContextAccessor _accessor;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="accessor"></param>
        public WeChatPayController(IHttpContextAccessor accessor)
        {
            _accessor = accessor;
        }

        /// <summary>
        /// 商户小程序处理类
        /// </summary>
        private Module.User.MiniProgramModule programModule = new Module.User.MiniProgramModule();
        private readonly UserModule userModule = new UserModule();
        /// <summary>
        /// 微信支付
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ApiResult GetPayInfo()
        {
            var request = RequestParm;
            var userInfo = AppletUserInfo; // new AppletUserInfo(); 
            if (userInfo == null)
            {
                return ApiResult.Failed("请登录");
            }

            //var userModel = userModule.GetMemberUserInfo(21233);

            //if (userInfo != null)
            //{
            //    userInfo = new Common.AppletUserInfo();
            //    userInfo.TenantId = userModel.TenantId;
            //    userInfo.MallBaseId = userModel.MallBaseId;
            //    userInfo.UserId = userModel.Id;
            //}
            RB_Goods_Order_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Order_Extend>(request.msg.ToString());
            string sPayInfo = string.Empty;
            if (!demodel.OrderPayType.HasValue)
            {
                return ApiResult.Failed("请选择支付方式！");
            }
            var model = new Module.Product.OrderModule().GetOrderInfo(demodel.OrderId);
            if (model == null)
            {
                return ApiResult.Failed("订单信息不存在！");
            }

            if (model.OrderStatus == Common.Enum.Goods.OrderStatusEnum.Cancel)
            {
                return ApiResult.Failed("订单已取消");
            }
            if ((int)model.OrderStatus > 1)
            {
                return ApiResult.Failed("订单已支付");

            }
            string sOrderNo = (System.DateTime.Now.ToString("yyyyMMddHHmmssfff")) + model.OrderId;
            //根据订单号获取微信支付配置信息
            RB_MiniProgram_Extend miniProgram = new RB_MiniProgram_Extend();  //2020年5月26号新增
            miniProgram = programModule.GetMiniProgramModule(new RB_MiniProgram_Extend { MallBaseId = userInfo.MallBaseId, TenantId = userInfo.TenantId });
            App_Code.PayUtil payUtil = new App_Code.PayUtil();
            switch ((int)demodel.OrderPayType)
            {
                case 1://微信支付     _accessor.HttpContext.Connection.RemoteIpAddress.ToString()
                    sPayInfo = App_Code.PayUtil.GetMinUnifiedOrder(sOrderNo, demodel.GoodsName, model.Income.Value, model.UserId.ToString(), demodel.OpenId, Config.sTenpayNotify, miniProgram, _accessor, System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList.FirstOrDefault(address => address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)?.ToString());
                    break;
                default:
                    break;
            }
            return ApiResult.Success("", sPayInfo);
        }





        public ApiResult TestReturn()
        {
            RB_MiniProgram_Extend miniProgram = new RB_MiniProgram_Extend();  //2020年5月26号新增
            miniProgram = new RB_MiniProgram_Extend { MiniAppId = "wxacd9f8cc3480d29e", WeChatApiSecret = "936110e2c2214340b9829a3608bde6b0", WeChatPayMerchants = "1562277941" }; // programModule.GetMiniProgramModule(new RB_MiniProgram_Extend { MallBaseId = 1, TenantId =1 });
            string RefundOrderNo = "2020052916044326411";
            var pram = new Common.Pay.WeChatPat.PayParam()
            {
                TotalFee = Convert.ToInt32(0.01 * 100),
                RefundFee = Convert.ToInt32(0.01 * 100),
                OrderNumber = "202005291604432641",
                RefundNumber = RefundOrderNo
            };
            var Robj = new App_Code.PayUtil().Refund(pram, miniProgram, _accessor);
            return ApiResult.Success("", Robj);
        }


        public ApiResult TestTransfersOrder()
        {
            RB_MiniProgram_Extend miniProgram = new RB_MiniProgram_Extend();  //2020年5月26号新增
            miniProgram = new RB_MiniProgram_Extend { MiniAppId = "wxacd9f8cc3480d29e", WeChatApiSecret = "936110e2c2214340b9829a3608bde6b0", WeChatPayMerchants = "1562277941" }; // programModule.GetMiniProgramModule(new RB_MiniProgram_Extend { MallBaseId = 1, TenantId =1 });
            string RefundOrderNo = "20200529160443264111";

            var Robj = App_Code.PayUtil.GetTransfersOrder(RefundOrderNo, Convert.ToDecimal("0.01"), "21233", "ow_7I5XC1-RGwwk8QANBmWKYKmOc", miniProgram, _accessor); ;
            return ApiResult.Success("", Robj);
        }


        public ApiResult TestNativeOrder()
        {
            RB_MiniProgram_Extend miniProgram = new RB_MiniProgram_Extend();  //2020年5月26号新增
            miniProgram = new RB_MiniProgram_Extend { MiniAppId = "wxacd9f8cc3480d29e", WeChatApiSecret = "936110e2c2214340b9829a3608bde6b0", WeChatPayMerchants = "1562277941" }; // programModule.GetMiniProgramModule(new RB_MiniProgram_Extend { MallBaseId = 1, TenantId =1 });
            string RefundOrderNo = System.DateTime.Now.ToString("yyyyMMddHHmmssfff");

            var Robj = App_Code.PayUtil.GetNativeOrder(RefundOrderNo, Convert.ToDecimal("0.01"), "测试商品", "21233", miniProgram, System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList.FirstOrDefault(address => address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)?.ToString(), _accessor); ;
            return ApiResult.Success("", Robj);
        }
    }
}