using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using RFrameGenerate.Model;
using RFramework.SQLQuery;
using RFramework.SQLServer;
using RFrameGenerate.Model.PageModel;

namespace RFrameGenerate.BLL
{
    public class WithdrawsComManage
    {
        #region List<T_BAS_DistributionProp> GetWithdrawalMgePageList

        /// <summary>
        /// get withdrawalmanagement page list
        /// </summary>
        /// <returns></returns>
        public static List<T_ST_MemberToWitthdrawsCommission> GetWithdrawalMgePageList(GridModel gridModel, string name)
        {
            using (var query = Factory.CreateT_ST_MemberToWitthdrawsCommission())
            {
                return query.GetPageList(gridModel, c => c.DistributionName.SqlLike(name), true, b => b.ApplyDateTime, DAL.Enums.OrderMethods.DESC);
            }

        }
        #endregion

        #region Result UpdateWithdrawsComState
        /// <summary>
        /// update withdrawalmanagement state
        /// </summary>
        /// <param name="withdrawsCommissionGuid"></param>
        /// <param name="stateCode"></param>
        /// <returns></returns>
        public static Result UpdateWithdrawsComState(Guid withdrawsCommissionGuid, int stateCode)
        {
            using (var query = Factory.CreateT_BAS_WithdrawsCommission())
            {
                query.Update(c => new object[]
                {
                    c.State==stateCode
                }, a => a.WithdrawsCommissionGuid == withdrawsCommissionGuid);
            }
            return new Result(true);
        }
        #endregion

        //public static List<T_BAS_WithdrawsCommission> GetWithdrawsComData()
        //{
        //    using (var query = Factory.CreateT_BAS_WithdrawsCommission())
        //    {
        //        return query.GetList(c=>c.MerchantGuid)
        //    }

        //}

        public static T_BAS_WithdrawsCommission GetWithdrawsApplyAmount(Guid withdrawsCommissionGuid)
        {
            using (var query = Factory.CreateT_BAS_WithdrawsCommission())
            {
                return query.GetFirstData(c => c.WithdrawsCommissionGuid == withdrawsCommissionGuid);
            }
        }

        #region 根据会员Guid获取佣金提现记录
        /// <summary>
        /// 根据会员Guid获取佣金提现记录
        /// </summary>
        /// <param name="memberGuid"></param>
        /// <returns></returns>
        public static List<T_BAS_WithdrawsCommission> GetListByMemberGuid(Guid merchantGuid)
        {
            var model = DistributionManage.GetList();
            if (model == null)
                return null;
            using (var query = Factory.CreateT_BAS_WithdrawsCommission())
            {
                return query.GetList(a => a.DistributionPropGuid == model.DistributionPropGuid && a.MerchantGuid == merchantGuid.ToString()).OrderByDescending(a => a.ApplyDateTime).ToList();
            }
        }
        #endregion

        #region 判断是否符合提现条件
        public static Result CheckAllowed(Guid did, decimal applyAmount)
        {
            int times = 0;
            decimal amount = 0;
            var result = ParameterManage.CheckAllowed(Common.CurrentManage.MerchantGuid, applyAmount, ref times, ref amount);
            if (result.State)
            {
                //统计本月提现次数
                using (var tran = new SqlRTransaction())
                {
                    var query = Factory.CreateT_BAS_WithdrawsCommission(tran);
                    var query_distribution = Factory.CreateT_BAS_DistributionProp(tran);
                    var model = query_distribution.GetFirstData(c => c.DistributionPropGuid == did);
                    if (applyAmount > (model.DistributionCommissions - model.WithdrawalAmount))
                    {
                        return new Result(false, "提现金额不能大于分销可用佣金！");
                    }
                    var dt1 = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
                    var dt2 = dt1.AddMonths(1).AddDays(-1);
                    string[] arr = new string[2];
                    arr[0] = dt1.ToString();
                    arr[1] = dt2.ToString();
                    //每月提现次数
                    if (times != 0)
                    {
                        var list = query.GetList(a => a.MerchantGuid == Common.CurrentManage.MerchantGuid.ToString() && a.DistributionPropGuid == model.DistributionPropGuid && a.State == DictionaryConst.WithdriwalCom.WithdrawalsSuccess && a.ApplyDateTime.SqlBetween(arr));
                        if (list.Count > times)
                            return new Result(false, "超过每月提现次数限制！");
                    }
                    //分销商提现金额小于等于提现审核金额限制时，系统自动将提现金额打到分销商账户余额，无需后台审核。

                    var withdrawsCommission = new T_BAS_WithdrawsCommission()
                    {
                        WithdrawsCommissionGuid = Guid.NewGuid(),
                        DistributionPropGuid = DistributionManage.GetList().DistributionPropGuid,
                        MerchantGuid = Common.CurrentManage.MerchantGuid.ToString(),
                        ApplyDateTime = DateTime.Now,
                        ApplyAmount = applyAmount,
                        State = applyAmount <= amount ? DictionaryConst.WithdriwalCom.WithdrawalsSuccess : DictionaryConst.WithdriwalCom.Handling
                    };

                    //更新分销会员属性
                    if (applyAmount <= amount)
                    {
                        model.WithdrawalAmount = (model.WithdrawalAmount == null ? 0 : model.WithdrawalAmount.Value) + applyAmount;
                        var queryMember = Factory.CreateT_BAS_Member(tran);
                        var memeber = queryMember.GetFirstData(a => a.MemberGuid == RFrameGenerate.Common.CurrentUser.GetCurrUserGuid());
                        decimal Balance = memeber.Balance + applyAmount;
                        decimal Amount = memeber.Amount + applyAmount;
                        queryMember.Update(a => new object[]
                                        {
                                            a.Balance==Balance,
                                            a.Amount==Amount,
                                        }, b => b.MemberGuid == RFrameGenerate.Common.CurrentUser.GetCurrUserGuid());
                         
                        //添加会员账户记录 Bing 160423
                        MemberAccountManage.AddMemberAccount(memeber.MemberGuid, MemberAccountConst.TradingType.分销佣金提现, withdrawsCommission.WithdrawsCommissionGuid, applyAmount, tran, memeber.Balance, memeber.MerchantGuid, "佣金提现");

                    }
                    else
                    {
                        model.AmountFrozen = applyAmount + (model.AmountFrozen == null ? 0 : model.AmountFrozen.Value);
                    }
                    try
                    {
                        tran.BeginTransaction();
                        query.Add(withdrawsCommission);
                        query_distribution.Update(model);
                        tran.Commit();
                    }
                    catch
                    {
                        tran.Rollback();
                    }
                    if (applyAmount <= amount)
                    {

                        return new Result(true, "提现成功！");
                    }
                    else
                    {
                        return new Result(true, "申请成功！");
                    }
                }
            }
            return result;
        }
        #endregion
    }
}
