using RFrameGenerate.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Wechat.Model;
using RFramework.SQLQuery;
using weixinopen;
using Wechat;
using RFramework.SQLServer;
using RFramework.SQLQuery.SQLExpands;
using RFrameGenerate.Common;
using RFrameGenerate.Model.PageModel;
using System.Threading.Tasks;
using System.Linq.Expressions;

namespace RFrameGenerate.BLL
{
    public class MemberAccountManage
    {

        #region 获取会员账户数据-分页
        /// <summary>
        /// 获取会员账户数据-分页
        /// </summary>
        /// <param name="gridModel"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static List<T_BAS_MemberAccount> GetPageList(GridModel gridModel, int? TradingType, string TradingMain = "", Guid? MemberGuid = null, Guid? merGuid = null)
        {
            using (var query = Factory.CreateT_BAS_MemberAccount())
            {
                if (MemberGuid == null)
                {
                    MemberGuid = CurrentUser.GetCurrUserGuid();
                }
                if (merGuid == null)
                {
                    merGuid = CurrentManage.MerchantGuid;
                }

                Expression<Func<T_BAS_MemberAccount, bool>> exp = (c => c.MemberGuid == MemberGuid && c.TradingMain.SqlLike(TradingMain) && c.MerchantGuid == merGuid && c.TradingType == TradingType);
                if (TradingType == MemberAccountConst.TradingType.提现申请)
                {
                    exp = (c => c.MemberGuid == MemberGuid && c.TradingMain.SqlLike(TradingMain) && c.MerchantGuid == merGuid && (c.TradingType == TradingType || c.TradingType == MemberAccountConst.TradingType.提现失败 || c.TradingType == MemberAccountConst.TradingType.提现成功));
                }

                var listTemp = query.GetPageList(gridModel, exp, true, c => c.TradingDate, DAL.Enums.OrderMethods.DESC, RFramework.SQLServer.Enums.LockType.Default, isFilterMerchant: false);

                return listTemp;
            }
        }
        #endregion


        #region 获取指定会员最新一条账户数据 Bing 160423 暂定
        /// <summary>
        /// 获取指定会员最新一条账户数据 Bing 160423 暂定
        /// </summary>
        /// <param name="gridModel"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static T_BAS_MemberAccount GetMemberAccountCurrNow(Guid memberGuid)
        {
            var lobj = CrowdPeriodLock.GetLock(memberGuid);
            lock (lobj)
            {
                try
                {
                    using (var query = Factory.CreateT_BAS_MemberAccount())
                    {
                        var model = query.GetFirstData(c => c.MemberGuid == memberGuid, false, c => c.TradingDate, DAL.Enums.OrderMethods.DESC, RFramework.SQLServer.Enums.LockType.Default, isFilterMerchant: false);
                        CrowdPeriodLock.SetLock(memberGuid, false);
                        return model;
                    }

                }
                catch (Exception ex)
                {
                    CrowdPeriodLock.SetLock(memberGuid, false);
                    throw ex;
                }
                //finally
                //{
                //} 
            }
        }
        #endregion


        #region 给指定会员新增一条账户数据(事务中) -Bing 160423 暂定
        /// <summary>
        /// 给指定会员新增一条账户数据(事务中) - Bing 160423 暂定
        /// <para>1.事务中，未提交;</para>
        /// <para>2.注意交易金额入账/出账;</para>
        /// <para>3.hisBalance/merGuid为空，则自动获取当前对应数据;</para>
        /// </summary>
        /// <param name="gridModel"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static void AddMemberAccount(Guid memberGuid, int tradingType, Guid? factorageSubjectGuid, decimal tradingAmount, SqlRTransaction tran, decimal?hisBalance = null, Guid? merGuid = null, string tradingMain = null, string reciprocalAccount = null, string remark = null)
        {
            var lobj = CrowdPeriodLock.GetLock(memberGuid);
            lock (lobj)
            {
                try
                {
                    var query = Factory.CreateT_BAS_MemberAccount(tran);//不可连表，临时 

                    if (hisBalance == null)
                    {
                        //var currEntity = query.GetFirstData(c => c.MemberGuid == memberGuid, false, c => c.TradingDate, DAL.Enums.OrderMethods.DESC, RFramework.SQLServer.Enums.LockType.Default, isFilterMerchant: false);
                        //if (currEntity == null)
                        //{
                        //    availableBalance = 0m;
                        //}
                        //else
                        //{
                        //    availableBalance = (currEntity.AvailableBalance ?? 0m);
                        //}

                        var queryMem = Factory.CreateT_BAS_Member(tran);
                        var memEntity = queryMem.GetFirstData(c => c.MemberGuid == memberGuid, isFilterMerchant: false);
                        //if (memEntity==null)
                        //{
                        //    availableBalance = 0M;
                        //}
                        hisBalance = memEntity.Balance;


                    }
                    if (merGuid == null)
                    {
                        merGuid = CurrentManage.MerchantGuid;
                    }

                    var entity = new T_BAS_MemberAccount()
                           {
                               MemberAccountGuid = Guid.NewGuid(),
                               MemberGuid = memberGuid,
                               TradingCode = DateTime.Now.ToString("yyyyMMddHHmmss") + string.Format("{0:D2}", tradingType),
                               TradingMain = tradingMain,
                               AvailableBalance = hisBalance + tradingAmount,
                               TradingType = tradingType,
                               FactorageSubjectGuid = factorageSubjectGuid,
                               TradingAmount = tradingAmount,
                               TradingDate = DateTime.Now,
                               ReciprocalAccount = reciprocalAccount,
                               Remark = remark,
                               MerchantGuid = merGuid
                           };

                    query.Add(entity);
                    CrowdPeriodLock.SetLock(memberGuid, false);
                }
                catch (Exception ex)
                {
                    CrowdPeriodLock.SetLock(memberGuid, false);
                    throw ex;
                }
                //finally
                //{
                //}

            }
        }
        #endregion


        #region 设置指定会员的余额提现账户类型-事务中 Bing 160423 暂定
        /// <summary>
        /// 设置指定会员的余额提现账户类型-事务中 Bing 160423 暂定
        /// </summary>
        /// <param name="gridModel"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static void SetMemberAccountType(Guid memberGuid, Guid factorageSubjectGuid, int type, SqlRTransaction tran)
        {
            var lobj = CrowdPeriodLock.GetLock(memberGuid);
            lock (lobj)
            {
                try
                {
                    var query = Factory.CreateT_BAS_MemberAccount(tran);
                    //var entity = query.GetFirstData(c => c.FactorageSubjectGuid == WithdrawGuid&&c.MemberGuid==memberGuid, isFilterMerchant: false);
                    query.Update(c => new object[] { 
                            c.TradingType==type
                        }, c => c.FactorageSubjectGuid == factorageSubjectGuid && c.MemberGuid == memberGuid, isFilterMerchant: false);
                    CrowdPeriodLock.SetLock(memberGuid, false);

                }
                catch (Exception ex)
                {
                    CrowdPeriodLock.SetLock(memberGuid, false);
                    throw ex;
                }
                //finally
                //{
                //} 
            }
        }
        #endregion




    }

}
