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.Text.RegularExpressions;

namespace RFrameGenerate.BLL
{
    public class AgentWithdrawHqManage
    {

        #region 获取代理商佣金提现列表-分页数据
        /// <summary>
        /// 获取代理商佣金审核提现列表-分页数据 
        /// </summary>
        /// <param name="gridModel"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static List<T_BAS_FactorageWithdrawalHqLite> GetPageList(GridModel gridModel, string UserID, int? TradingType, string TradingCode, DateTime? beginTime, DateTime? endTime, DateTime? beginTimeSe, DateTime? endTimeSe)
        {
            using (var query = Factory.CreateT_BAS_FactorageWithdrawalHqLite())
            {
                var agentArr = AgentAuditManage.GetAllSubordinateAgent().ToArray();
                if (agentArr == null || agentArr.Count() == 0)
                {
                    return null;
                }
                endTime = endTime != null ? endTime.Value.AddDays(1) : endTime;
                endTimeSe = endTimeSe != null ? endTimeSe.Value.AddDays(1) : endTimeSe;

                var list = query.GetPageList(gridModel, c => c.MerchantGuid.SqlIn(agentArr) && c.UserID.SqlLike(UserID) && c.TradingType == TradingType && c.TradingCode.SqlLike(TradingCode) && c.ApplyTime >= beginTime && c.ApplyTime <= endTime && c.DealWithTime >= beginTimeSe && c.DealWithTime <= endTimeSe, true, c => c.ApplyTime, DAL.Enums.OrderMethods.DESC, RFramework.SQLServer.Enums.LockType.Default, false);
                return list;
            }
        }
        #endregion
         
        #region 设置备注
        /// <summary>
        /// 设置备注
        /// </summary>
        /// <param name="guids"></param>
        /// <param name="Remark"></param>
        /// <returns></returns>
        public static object SetRemark(Guid guid, string Remark)
        {
            using (var tran = new SqlRTransaction())
            {
                try
                {
                    tran.BeginTransaction();
                    var query_FactorageWithdraw = Factory.CreateT_BAS_FactorageWithdrawal(tran);
                    query_FactorageWithdraw.Update(c => new object[] {
                        c.Remark==Remark
                    }, c => c.FactorageWithdrawalGuid == guid, false);
                    tran.Commit();
                    return new Result(true);
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    return new Result(false, ex.Message);
                }
            }
        }
        #endregion

        #region 提现操作
        /// <summary>
        /// 提现操作
        /// </summary>
        /// <param name="guid"></param>
        /// <param name="TradingType"></param>
        /// <returns></returns>
        public static object DoWithdraw(T_BAS_FactorageWithdrawalHqLite model, decimal? TradingAmountTe)
        {
            using (var tran = new SqlRTransaction())
            {
                try
                {
                    tran.BeginTransaction();

                    var query_FactorageWithdraw = Factory.CreateT_BAS_FactorageWithdrawal(tran);
                    var query_FactorageAccount = Factory.CreateT_BAS_FactorageAccount(tran);
                    var query_mer = Factory.CreateT_BAS_Merchants(tran);
                    if (model.TradingType == FactorageWithdrawalConst.TradingType.提现成功)
                    {
                        query_FactorageWithdraw.Update(c => new object[] {
                            c.WithdrawalCode==model.WithdrawalCode,
                            c.Remark==model.Remark
                           }, c => c.FactorageWithdrawalGuid == model.FactorageWithdrawalGuid, false);
                    }
                    if (model.TradingType == FactorageWithdrawalConst.TradingType.审核通过)
                    {
                        query_FactorageWithdraw.Update(c => new object[] {
                            c.WithdrawalCode==model.WithdrawalCode,
                            c.Remark==model.Remark,
                            c.TradingType==FactorageWithdrawalConst.TradingType.提现成功
                           }, c => c.FactorageWithdrawalGuid == model.FactorageWithdrawalGuid, false);

                        var available = 0m;
                        var freeze = 0m;
                        AgentCommissionManage.GetAvailableAndFreeze(model.MerchantGuid.Value, ref available, ref freeze);


                        if (AgentAccountManage.IsCountFsBalance)
                        {
                            return new Result(false, "系统繁忙，请稍后重试");
                        }

                        var fz = freeze - (TradingAmountTe ?? 0);
                        query_mer.Update(c => new object[] {  
                            c.ComFreeze==fz
                        }, c => c.MerchantGuid == model.MerchantGuid, isFilterMerchant: false);


                        query_FactorageAccount.Add(new T_BAS_FactorageAccount()
                           {
                               FactorageAccountGuid = Guid.NewGuid(),
                               MerchantGuid = model.MerchantGuid,
                               TradingCode = DateTime.Now.ToString("yyyyMMddHHmmss") + string.Format("{0:D2}", AgentCommissionConst.TradingType.提现成功),
                               AvailableBalance = available,
                               TradingType = AgentCommissionConst.TradingType.提现成功,
                               FactorageSubjectGuid = model.FactorageWithdrawalGuid,
                               TradingAmount = (/*model.TradingAmount ?? */0),
                               TradingDate = DateTime.Now,
                           });

                    }
                    if (AgentAccountManage.IsCountFsBalance)
                    {
                        return new Result(false, "系统繁忙，请稍后重试");
                    }
                    tran.Commit();
                    return new Result(true);
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    return new Result(false, ex.Message);
                }
            }


        }

        #endregion

        #region 设置提现审核状态
        /// <summary>
        /// 设置提现审核状态（审核通过/不通过）
        /// </summary>
        /// <param name="guids"></param>
        /// <param name="TradingType"></param>
        /// <returns></returns>
        public static Result SetTradingType(Guid[] guids, int TradingType)
        {
            using (var tran = new SqlRTransaction())
            {
                try
                {
                    var query_FactorageWithdraw = Factory.CreateT_BAS_FactorageWithdrawal(tran);
                    var query_Mer = Factory.CreateT_BAS_Merchants(tran);

                    var listFwds = query_FactorageWithdraw.GetList(c => c.FactorageWithdrawalGuid.SqlIn(guids), isFilterMerchant: false);
                    if (listFwds == null && listFwds.Count == 0)
                    {
                        return new Result(false, "提现记录不存在，请刷新查看");
                    }
                    var fs = listFwds.FirstOrDefault(c => c.TradingType != FactorageWithdrawalConst.TradingType.审核中 && c.TradingType != FactorageWithdrawalConst.TradingType.审核通过);
                    if (fs != null)
                    {
                        return new Result(false, string.Format("交易号{0}已处理，请重新选择", fs.TradingCode));
                    }

                    tran.BeginTransaction();

                    if (AgentAccountManage.IsCountFsBalance)
                    {
                        return new Result(false, "系统繁忙，请稍后重试");
                    }

                    query_FactorageWithdraw.Update(c => new object[] {
                        c.TradingType==TradingType
                    }, c => c.FactorageWithdrawalGuid.SqlIn(guids), false);

                    if (TradingType == FactorageWithdrawalConst.TradingType.审核不通过)
                    {
                        var query_FactorageAccount = Factory.CreateT_BAS_FactorageAccount(tran);
                        var listMer = query_Mer.GetList(c => c.MerchantGuid.SqlIn(listFwds.Select(f => f.MerchantGuid.ToString()).Distinct().ToArray()), isFilterMerchant: false);
                        var listFs = new List<T_BAS_FactorageAccount>();
                        listFwds.ForEach(c =>
                        {
                            //var available = 0m;
                            //var freeze = 0m;
                            //AgentCommissionManage.GetAvailableAndFreeze(c.MerchantGuid, ref available, ref freeze);

                            //    query_Mer.Update(m => new object[] { 
                            //    m.FsBalance==available,
                            //    m.ComFreeze==freeze
                            //}, m => m.MerchantGuid == c.MerchantGuid, isFilterMerchant: false);

                            //query_FactorageAccount.Add(new T_BAS_FactorageAccount()
                            //{
                            //    FactorageAccountGuid = Guid.NewGuid(),
                            //    MerchantGuid = c.MerchantGuid,
                            //    TradingCode = DateTime.Now.ToString("yyyyMMddHHmmss") + string.Format("{0:D2}", AgentCommissionConst.TradingType.提现不通过),
                            //    AvailableBalance = (available + c.TradingAmount),
                            //    TradingType = AgentCommissionConst.TradingType.提现不通过,
                            //    FactorageSubjectGuid = c.MerchantGuid,
                            //    TradingAmount = c.TradingAmount,
                            //    TradingDate = DateTime.Now
                            //});
                            var currMer = listMer.First(m => m.MerchantGuid == c.MerchantGuid);
                            currMer.FsBalance = (currMer.FsBalance ?? 0M) + c.TradingAmount;
                            currMer.ComFreeze = (currMer.ComFreeze /*?? 0M*/) - c.TradingAmount;
                            currMer.EntityState = EntityStates.ToBeUpdated;

                            listFs.Add(new T_BAS_FactorageAccount()
                                {
                                    FactorageAccountGuid = Guid.NewGuid(),
                                    MerchantGuid = c.MerchantGuid,
                                    TradingCode = DateTime.Now.ToString("yyyyMMddHHmmss") + string.Format("{0:D2}", AgentCommissionConst.TradingType.提现不通过),
                                    AvailableBalance = currMer.FsBalance,
                                    TradingType = AgentCommissionConst.TradingType.提现不通过,
                                    FactorageSubjectGuid = c.MerchantGuid,
                                    TradingAmount = c.TradingAmount,
                                    TradingDate = DateTime.Now
                                });

                        });

                        if (listFs.Count > 0)
                        {
                            query_FactorageAccount.AddList(listFs);
                            query_Mer.UpdateList(listMer);
                        }
                    }

                    if (AgentAccountManage.IsCountFsBalance)
                    {
                        return new Result(false, "系统繁忙，请稍后重试");
                    }

                    tran.Commit();
                    return new Result(true);
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    return new Result(false, ex.Message);
                }
            }

        }
        #endregion

        #region 获取代理商待提现、已提现金额 待定
        /// <summary>
        /// 获取代理商待提现、已提现金额 待定
        /// </summary>
        /// <param name="wait"></param>
        /// <param name="complete"></param>
        public static void GetAvailableAndFreeze(ref decimal wait, ref decimal complete)
        {
            using (var tran = new SqlRTransaction())
            {
                var agentArr = AgentAuditManage.GetAllSubordinateAgent().ToArray();
                var query_FactorageWithdrawal = Factory.CreateT_BAS_FactorageWithdrawal(tran);
                if (agentArr == null || agentArr.Count() == 0)
                {
                    return;
                }

                //160503修改，暂时不保留字段
                var list_FactorageWithdrawal = query_FactorageWithdrawal.GetList(c => c.MerchantGuid.SqlIn(agentArr), false, null, DAL.Enums.OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                if (list_FactorageWithdrawal != null && list_FactorageWithdrawal.Count > 0)
                {
                    wait = (list_FactorageWithdrawal.Where(c => c.TradingType == FactorageWithdrawalConst.TradingType.审核通过 || c.TradingType == FactorageWithdrawalConst.TradingType.审核中).Sum(c => c.TradingAmount) ?? 0);
                    complete = (list_FactorageWithdrawal.Where(c => c.TradingType == FactorageWithdrawalConst.TradingType.提现成功).Sum(c => c.TradingAmount) ?? 0);

                }
            }
        }

        #endregion
    }




}
