using RFrameGenerate.Model;
using RFramework.SQLServer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RFrameGenerate.DAL.Interface;
using RFrameGenerate.Model.PageModel;
using Wechat;

namespace RFrameGenerate.BLL.Recharge
{
    public class RechargeManage
    {
        public static Result SubmitOrder(string name, string phone, decimal amount, out string orderNo)
        {
            orderNo = string.Empty;
            if (string.IsNullOrEmpty(name)) return new Result(false, "姓名不能为空！");

            if (string.IsNullOrEmpty(phone)) return new Result(false, "手机不能为空！");

            if (amount <= 0.0m) return new Result(false, "充值金额不能小于等于0");

            var member = MemberManage.GetMemberByGuid(Common.CurrentUser.GetCurrUserGuid());

            if (member == null) return new Result(false, "不存在会员信息！");

            orderNo = OrderManage.GetOrderNO();

            using (var query = Factory.CreateT_BAS_Recharge())
            {
                query.Add(new T_BAS_Recharge()
                {
                    RechargeGuid = Guid.NewGuid(),
                    PayWay = "微信支付",
                    Name = name,
                    Phone = phone,
                    Amount = amount,
                    MemberGuid = member.MemberGuid,
                    MemberOpenID = member.MemberOpenID,
                    MerchantGuid = Common.CurrentManage.MerchantGuid,
                    State = DictionaryConst.RechargeState.Unpaid,
                    InnerState = DictionaryConst.RechargeInnerState.Unpaid,
                    Type = DictionaryConst.RechargeType.Recharge,
                    OrderTime = DateTime.Now,
                    OrderNo = orderNo,
                    Remark = "会员充值",
                });
            }
            return new Result(true);
        }

        public static T_BAS_Recharge GetOrder(string orderNO)
        {
            using (var query = Factory.CreateT_BAS_Recharge())
            {
                return query.GetFirstData(m => m.OrderNo == orderNO && m.MerchantGuid == Common.CurrentManage.MerchantGuid, isFilterMerchant: false);
            }
        }

        public static string GetMemberOpenID(string orderNO)
        {
            var order = GetOrder(orderNO);

            if (order == null) return string.Empty;

            return order.MemberOpenID;
        }

        public static Result UpdatePayWayAndInnerState(string orderNO)
        {
            try
            {
                using (var tran = new SqlRTransaction())
                {
                    var qeury = Factory.CreateT_BAS_Recharge(tran);
                    var queryMerchantPay = Factory.CreateT_BAS_MerchantsPayWay(tran);
                    var payway = queryMerchantPay.GetFirstData(a => a.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid);
                    if (payway == null)
                        return new Result(false, "支付失败,商家未配置微信支付,请联系商家!");

                    qeury.Update(a => new object[] { a.MerchantPayWayGuid == payway.MerchantPayWayGuid, a.InnerState == DictionaryConst.RechargeInnerState.Paying }, b => b.OrderNo == orderNO);
                }
                return new Result(true);
            }
            catch (Exception ex)
            {
                return new Result(false, ex.Message);
            }
        }

        public static PT_BAS_PayWayByOrderNo GetPayWayByOrderNO(string orderNO)
        {
            using (var query = Factory.CreateProcedure())
            {
                return query.GetPayWayByRechargeOrderNo(orderNO);
            }
        }

        #region 回调处理函数

        public static Result PaySuccess(string orderNO, string total, string appid, string openid, string transaction_id)
        {

            //LogManage.Log("充值呀:" + orderNO);
            //return new Result(true);


            decimal totalAmount = decimal.Parse(total) / 100;//实际支付
            if (totalAmount <= 0)
                return new Result(false, "支付金额不能小于或等于0");

            if (string.IsNullOrEmpty(orderNO)) return new Result(false, "订单号为空！");

            SqlRTransaction tran = null;
            IQuery<T_BAS_Member> queryMember = null;
            IQuery<T_BAS_Recharge> queryRecharge = null;
            IQuery<T_BAS_RechargeRecord> queryRecord = null;
            IQuery<T_BAS_Orders> queryOrder = null;

            var prev = "Recharge";
            var flag = false;
            var isSuccess = false;

            var lockObj = LockManage.GetLock(prev, orderNO);

            if (lockObj.Verity()) return new Result(true);

            try
            {
                System.Threading.Monitor.Enter(lockObj, ref flag);

                if (lockObj.Verity()) return new Result(true);

                tran = new SqlRTransaction();

                queryMember = Factory.CreateT_BAS_Member(tran);
                queryRecharge = Factory.CreateT_BAS_Recharge(tran);
                queryRecord = Factory.CreateT_BAS_RechargeRecord(tran);
                queryOrder = Factory.CreateT_BAS_Orders(tran);

                tran.BeginTransaction();

                #region 逻辑处理

                #region a) 验证信息

                var order = queryRecharge.GetFirstData(m => m.OrderNo == orderNO, false, null, DAL.Enums.OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                if (order == null)
                    return new Result(true, "不存在此订单号：" + orderNO);
                if (order.State == DictionaryConst.RechargeState.Paided)
                    return new Result(true, "订单已处理：DictionaryConst.RechargeState.Paided " + orderNO);

                var member = queryMember.GetFirstData(m => m.MemberGuid == order.MemberGuid, false, null, DAL.Enums.OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                if (member == null)
                   return new Result(true,"不存在会员:" + order.MemberGuid);

                if (appid != "wx1efed944cad6ca0f" && appid != "wxd5e10229829c4d76" && appid != "wxf35069f2f61ab219")
                {
                    if (order.Amount != totalAmount)
                        return new Result(true, "支付金额不等于微信回调的金额");
                }
                #endregion
                

                #region b)更新订单

                queryRecharge.Update(m => new object[] 
                { 
                    m.TransactionID == transaction_id, 
                    m.State == DictionaryConst.RechargeState.Paided,
                    m.InnerState == DictionaryConst.RechargeInnerState.Success,
                }, v => v.RechargeGuid == order.RechargeGuid, false);

                #endregion

                #region c)更新会员信息
                var amount = member.Amount + order.Amount;
                var balance = member.Balance + order.Amount;

                queryMember.Update(m => new object[] { m.Amount == amount, m.Balance == balance }, v => v.MemberGuid == member.MemberGuid, false);

                #endregion

                #region d)插入流水表

                queryRecord.Add(new T_BAS_RechargeRecord()
                {
                    RechargeRecordGuid = Guid.NewGuid(),
                    TradeAmount = order.Amount,
                    SrcMemberAmount = member.Amount,
                    SrcMemberBalance = member.Balance,
                    MemberAmount = amount,
                    MemberBalance = balance,
                    MemberGuid = member.MemberGuid,
                    OrderNo = order.OrderNo,
                    MerchantGuid = order.MerchantGuid,
                    OperateTime = DateTime.Now,
                    Type = DictionaryConst.RechargeType.Recharge,
                    SMerchantGuid = order.MerchantGuid,
                });
                #endregion

                //添加会员账户记录 Bing 160423
                MemberAccountManage.AddMemberAccount(member.MemberGuid, MemberAccountConst.TradingType.用户充值, order.RechargeGuid, totalAmount, tran, member.Balance, order.MerchantGuid, "用户充值");


                #endregion

                tran.Commit();
                isSuccess = true;
                return new Result(true);
            }
            catch (Exception ex)
            {
                if (tran != null) tran.Rollback();
                Wechat.LogManage.Log("RechargeManage.PaySuccess\r\n" + ex.Message);
                Wechat.LogManage.Log("RechargeManage.PaySuccess\r\n" + ex.Source);
                Wechat.LogManage.Log("RechargeManage.PaySuccess\r\n" + ex.StackTrace);
                return new Result(false, ex.Message);
            }
            finally
            {
                #region 释放资源

                if (queryMember != null)
                {
                    queryMember.Dispose();
                    queryMember = null;
                }
                if (queryRecharge != null)
                {
                    queryRecharge.Dispose();
                    queryRecharge = null;
                }
                if (queryRecord != null)
                {
                    queryRecord.Dispose();
                    queryRecord = null;
                }
                if (tran != null) tran.Dispose();

                if (tran != null && tran.SqlConnection.State != System.Data.ConnectionState.Closed) tran.SqlConnection.Close();

                #endregion

                LockManage.ReleaseLock(prev, orderNO, true, isSuccess);

                if (flag) System.Threading.Monitor.Exit(lockObj);
            }
        }

        public static Result VerifyFailed(string orderNO, string total, string appid, string openid, string transaction_id)
        {
            using (var query = Factory.CreateT_BAS_Recharge())
            {
                var order = query.GetFirstData(m => m.OrderNo == orderNO, false, null, DAL.Enums.OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);

                if (order == null) return new Result(false, "不存在此订单号：" + orderNO);

                query.Update(m => new object[] 
                { 
                    m.InnerState == DictionaryConst.RechargeInnerState.VerityFaile,
                    m.TransactionID == transaction_id 
                },
                v => v.RechargeGuid == order.RechargeGuid);

                return new Result(true);
            }
        }

        public static Result ExecuteFaile(string orderNO, string total, string appid, string openid, string transaction_id)
        {
            using (var query = Factory.CreateT_BAS_Recharge())
            {
                var order = query.GetFirstData(m => m.OrderNo == orderNO, false, null, DAL.Enums.OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);

                if (order == null) return new Result(false, "不存在此订单号：" + orderNO);

                query.Update(m => new object[] 
                { 
                    m.InnerState == DictionaryConst.RechargeInnerState.Faile,
                    m.TransactionID == transaction_id 
                },
                v => v.RechargeGuid == order.RechargeGuid);

                return new Result(true);
            }
        }

        #endregion
    }
}
