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.Entity.User;
using Mall.Model.Extend.Product;
using Mall.Model.Extend.User;
using Mall.Module.MarketingCenter;
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();
        private readonly RechargeModule rechargeModule = new RechargeModule();
        private readonly UserVipModule userVipModule = new UserVipModule();
        private readonly UserCommonModule userCommonModule = new UserCommonModule();
        #region 商品支付
        /// <summary>
        /// 微信支付
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetPayInfo()
        {
            var request = RequestParm;
            var userInfo = AppletUserInfo;
            if (userInfo == null)
            {
                return ApiResult.Failed("请登录");
            }
            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);
        }
        #endregion


        #region 余额充值
        /// <summary>
        /// 微信支付
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetRechargePayInfo()
        {
            var request = RequestParm;
            var userInfo = AppletUserInfo;
            if (userInfo == null)
            {
                return ApiResult.Failed("请登录");
            }
            RB_Member_BalanceRecharge demodel = JsonConvert.DeserializeObject<RB_Member_BalanceRecharge>(request.msg.ToString());
            string sPayInfo = string.Empty;
            if (!demodel.PayWay.HasValue)
            {
                return ApiResult.Failed("请选择支付方式");
            }

            //查询充值信息
            if (!demodel.Balance.HasValue)
            {
                return ApiResult.Failed("请输入充值金额");
            }
            //查询用户的openId
            var userModel = userModule.GetMemberUserEntityModule(new RB_Member_User_Extend { MallBaseId = userInfo.MallBaseId, TenantId = userInfo.TenantId, Id = userInfo.UserId });

            if (userModel == null)
            {
                return ApiResult.Failed("用户不存在");
            }
            string payGoodsName = "余额充值";
            var rechargeRulesModel = rechargeModule.GetRechargeRulesList(new Model.Extend.MarketingCenter.RB_Recharge_Rules_Extend { MallBaseId = userInfo.MallBaseId, TenantId = userInfo.TenantId, ID = demodel.RechargeRulesId }).FirstOrDefault();
            if (rechargeRulesModel == null)
            {
                return ApiResult.Failed("选择的充值规则不存在");
            }
            if (demodel.RechargeRulesId > 0)
            {
                if (demodel.Balance.Value != Convert.ToDecimal(rechargeRulesModel.Money))
                {
                    return ApiResult.Failed("充值金额与设定的金额不符");
                }
                demodel.GiveIntegral = rechargeRulesModel.GiveIntegral;
                demodel.GiveMoney = rechargeRulesModel.GiveMoney;
                demodel.RechargeRulesId = rechargeRulesModel.ID;
            }
            else
            { //自定义
                var rechareSettings = rechargeModule.GetRechargeSettingsList(new Model.Entity.MarketingCenter.RB_Recharge_Settings { MallBaseId = userInfo.MallBaseId, TenantId = userInfo.TenantId }).FirstOrDefault();

                if (rechareSettings.IsExploitMoney == 0)
                {
                    return ApiResult.Failed("暂未开启自定义金额");
                }
            }

            Random R = new Random();
            int Rstr = R.Next(111, 999);
            demodel.OrderNo = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Rstr;
            demodel.RechargeType = 1;
            demodel.UserId = userInfo.UserId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.TenantId = userInfo.TenantId;
            //新增充值记录
            int rechargeId = rechargeModule.AddBalanceRecharge(demodel);
            if (rechargeId == 0)
            {
                return ApiResult.Failed("在线充值失败");
            }
            string sOrderNo = (System.DateTime.Now.ToString("yyyyMMddHHmmssfff")) + rechargeId;
            //根据订单号获取微信支付配置信息
            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.PayWay)
            {
                case 1://微信支付     
                    sPayInfo = App_Code.PayUtil.GetMinUnifiedOrder(sOrderNo, payGoodsName, Convert.ToDecimal(rechargeRulesModel.Money), userInfo.UserId.ToString(), userModel.OpenId, Config.sTenpayRechargeNotify, 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);
        }
        #endregion



        #region 会员购买

        /// <summary>
        /// 微信支付
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ApiResult GetMemberBuyPayInfo()
        {
            var request = RequestParm;
            var userInfo = AppletUserInfo;
            if (userInfo == null)
            {
                return ApiResult.Failed("请登录");
            }
            RB_Member_Buy_Extend demodel = JsonConvert.DeserializeObject<RB_Member_Buy_Extend>(request.msg.ToString());
            string sPayInfo = string.Empty;
            if (!demodel.PayWay.HasValue)
            {
                return ApiResult.Failed("请选择支付方式");
            }

            //查询充值信息
            if (!demodel.GradeId.HasValue)
            {
                return ApiResult.Failed("请选择您需要购买的会员等级");
            }
            //查询用户的openId
            var userModel = userModule.GetMemberUserEntityModule(new RB_Member_User_Extend { MallBaseId = userInfo.MallBaseId, TenantId = userInfo.TenantId, Id = userInfo.UserId });

            if (userModel == null)
            {
                return ApiResult.Failed("用户不存在");
            }
            string payGoodsName = "会员等级购买";
            var rechargeRulesModel = userModule.GetMemberGradeList(new RB_Member_Grade_Extend { MallBaseId = userInfo.MallBaseId, TenantId = userInfo.TenantId, Grade = demodel.GradeId }).FirstOrDefault();
            if (rechargeRulesModel == null)
            {
                return ApiResult.Failed("您选择的会员等级不存在");
            }

            if (userModel.MemberGrade >= rechargeRulesModel.Grade)
            {
                return ApiResult.Failed("购买会员等级低于您当前会员等级");
            }
            if (rechargeRulesModel.IsMemberBuy == 1)
            {
                if (rechargeRulesModel.MemberBuyMoney != demodel.Money)
                {
                    return ApiResult.Failed("会员购买支付金额有误，请稍后重试");
                }
                demodel.GradeName = rechargeRulesModel.Name;
            }
            else
            {
                return ApiResult.Failed("当前会员等级不能购买");
            }
            Random R = new Random();
            int Rstr = R.Next(111, 999);
            demodel.OrderNo = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Rstr;
            demodel.UserId = userInfo.UserId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.TenantId = userInfo.TenantId;
            demodel.PayState = 0;
            demodel.Status = 0;
            demodel.CreateDate = DateTime.Now;
            //新增充值记录
            int memberBuyId = userModule.AddMemberBuy(demodel);
            if (memberBuyId == 0)
            {
                return ApiResult.Failed("购买会员失败");
            }
            string sOrderNo = (System.DateTime.Now.ToString("yyyyMMddHHmmssfff")) + memberBuyId;
            //根据订单号获取微信支付配置信息
            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.PayWay)
            {
                case 1://微信支付     
                    sPayInfo = App_Code.PayUtil.GetMinUnifiedOrder(sOrderNo, payGoodsName, Convert.ToDecimal(rechargeRulesModel.MemberBuyMoney), userInfo.UserId.ToString(), userModel.OpenId, Config.sTenpayMemberBuyNotify, 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);
        }

        #endregion




        #region 会员vip购买
        /// <summary>
        /// 微信支付
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ApiResult GetVIPBuyPayInfo()
        {
            var request = RequestParm;
            var userInfo = AppletUserInfo;
            if (userInfo == null)
            {
                return ApiResult.Failed("请登录");
            }
            RB_Vip_Buy_Extend demodel = JsonConvert.DeserializeObject<RB_Vip_Buy_Extend>(request.msg.ToString());
            string sPayInfo = string.Empty;
            if (demodel.PayWay == 0)
            {
                return ApiResult.Failed("请选择支付方式");
            }

            //查询充值信息
            if (demodel.GradeId == 0)
            {
                return ApiResult.Failed("请选择您需要购买的会员等级");
            }
            //查询用户的openId
            var userModel = userModule.GetMemberUserEntityModule(new RB_Member_User_Extend { MallBaseId = userInfo.MallBaseId, TenantId = userInfo.TenantId, Id = userInfo.UserId });

            if (userModel == null)
            {
                return ApiResult.Failed("用户不存在");
            }

            //获取会员的分享商记录
            var distributorModel = userModule.GetDistributorInfoList(new RB_Distributor_Info_Extend { MallBaseId = userInfo.MallBaseId, TenantId = userInfo.TenantId, UserId = userModel.Id }).FirstOrDefault();

            if (distributorModel == null)
            {
                return ApiResult.Failed("请先申请成为分销商");
            }
            string payGoodsName = "VIP会员购买";
            var rechargeRulesModel = userModule.GetFXDistributorGradeList(new RB_Distributor_FXGrade_Extend { MallBaseId = userInfo.MallBaseId, TenantId = userInfo.TenantId, Id = demodel.GradeId }).FirstOrDefault();
            if (rechargeRulesModel == null)
            {
                return ApiResult.Failed("您选择的VIP等级不存在");
            }

            if (distributorModel.Grade > rechargeRulesModel.Grade)
            {
                return ApiResult.Failed("购买VIP等级低于您当前VIP等级");
            }
            if (rechargeRulesModel.IsCanBuy == 1)
            {
                if (rechargeRulesModel.BuyMoney != demodel.Money)
                {
                    return ApiResult.Failed("VIP购买支付金额有误，请稍后重试");
                }
                demodel.GradeName = rechargeRulesModel.GradeName;
            }
            else
            {
                return ApiResult.Failed("当前VIP等级不能购买");
            }

            //判断订单状态是否是待支付 
            var buyList = userVipModule.GetVipBuyList(new RB_Vip_Buy_Extend { UserId = userInfo.UserId, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });

            if (buyList.Where(x => x.PayState == 1).Count() == 0)
            {
                demodel.Remark = "购买";
            }
            else
            {
                demodel.Remark = "续费";
            }
            Random R = new Random();
            int Rstr = R.Next(111, 999);
            demodel.OrderNo = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Rstr;
            demodel.UserId = userInfo.UserId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.TenantId = userInfo.TenantId;
            demodel.PayState = 0;
            demodel.Status = 0;
            demodel.CreateDate = DateTime.Now;
            demodel.ExpiryDate = Convert.ToDateTime(DateTime.Now.AddYears(rechargeRulesModel.Year ?? 1).AddDays(-1).ToString("yyyy-MM-dd 23:59:59"));
            //新增充值记录
            int memberBuyId = userVipModule.AddVipBuy(demodel);
            if (memberBuyId == 0)
            {
                return ApiResult.Failed("购买VIP等级失败");
            }
            string sOrderNo = (System.DateTime.Now.ToString("yyyyMMddHHmmssfff")) + memberBuyId;
            //根据订单号获取微信支付配置信息
            RB_MiniProgram_Extend miniProgram = new RB_MiniProgram_Extend();
            miniProgram = programModule.GetMiniProgramModule(new RB_MiniProgram_Extend { MallBaseId = userInfo.MallBaseId, TenantId = userInfo.TenantId });
            App_Code.PayUtil payUtil = new App_Code.PayUtil();
            switch ((int)demodel.PayWay)
            {
                case 1://微信支付     
                    sPayInfo = App_Code.PayUtil.GetMinUnifiedOrder(sOrderNo, payGoodsName, Convert.ToDecimal(rechargeRulesModel.BuyMoney), userInfo.UserId.ToString(), userModel.OpenId, Config.sTenpayVipBuyNotify, 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);
        }
        #endregion



        #region 测试接口


        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 TestWeChatPay()
        {
            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
            };
            string sOrderNo = (System.DateTime.Now.ToString("yyyyMMddHHmmssfff")) + "1001";
            App_Code.PayUtil.GetMinUnifiedOrder(sOrderNo, "测试", Convert.ToDecimal(0.05), "1", "", Config.sTenpayNotify, miniProgram, _accessor, System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList.FirstOrDefault(address => address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)?.ToString());
            return ApiResult.Success("");
        }


        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);
        }



        public ApiResult TestVIPBuyPayOrder()
        {
            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 = userCommonModule.InsertVipBuyCommission(21233, 3, "20200720152634009282", "20200720152634009282111", Common.Enum.Goods.OrderPayTypeEnum.WeChatPay, Convert.ToDecimal(365.00), System.DateTime.Now);
            return ApiResult.Success("", Robj);
        }

        #endregion






    }
}