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

namespace RFrameGenerate.BLL
{

    /// <summary>
    /// 提取金额设置的参数管理
    /// </summary>
    public class ParameterManage
    {
        #region List<T_SYS_Parameter> GetSettingParameters
        /// <summary>
        /// get parameters
        /// </summary>
        /// <returns></returns>
        public static List<T_SYS_Parameter> GetSettingParameters(string parametersType)
        {
            using (var query = Factory.CreateT_SYS_Parameter())
            {
                switch (parametersType)
                {
                    case ParameterName.SystemSet.ShowState:
                        return query.GetList(c => c.MerchantGuid == Common.CurrentManage.MerchantGuid &&
                                                  (c.ParameterName == ParameterName.SystemSet.ShowState ||
                                                  c.ParameterName == ParameterName.SystemSet.CloseReason)
                                                  );
                    case ParameterName.Distribution.WithdrawalAmountLimits:
                        return query.GetList(c => c.MerchantGuid == Common.CurrentManage.MerchantGuid &&
                                                  (c.ParameterName == ParameterName.Distribution.WithdrawalAmountLimits ||
                                                  c.ParameterName == ParameterName.Distribution.AmountLimit ||
                                                  c.ParameterName == ParameterName.Distribution.WithdrawalNumberLimits)
                                                  );
                    case ParameterName.DistributionMemeber.AuditApproachNew:
                        return query.GetList(c => c.MerchantGuid == Common.CurrentManage.MerchantGuid &&
                                                  (c.ParameterName == ParameterName.DistributionMemeber.AuditApproachNew ||
                                                  c.ParameterName == ParameterName.DistributionMemeber.Distributionchart ||
                                                  c.ParameterName == ParameterName.DistributionMemeber.DistributorRelations ||
                                                  c.ParameterName == ParameterName.DistributionMemeber.TopNumber ||
                                                  c.ParameterName == ParameterName.DistributionMemeber.BaseAmount)
                                                  );
                    case ParameterName.CommissionMember.FirstCommission:
                        return query.GetList(c => c.MerchantGuid == Common.CurrentManage.MerchantGuid &&
                                                  (c.ParameterName == ParameterName.CommissionMember.CommissionSettlementTime ||
                                                  c.ParameterName == ParameterName.CommissionMember.SecondCommission ||
                                                  c.ParameterName == ParameterName.CommissionMember.FirstCommission ||
                                                  c.ParameterName == ParameterName.CommissionMember.ThirdCommission)
                                                  );
                    case ParameterName.Withdraw.Payments:
                        return query.GetList(c => c.MerchantGuid == Common.CurrentManage.MerchantGuid &&
                                                  (c.ParameterName == ParameterName.Withdraw.Payments ||
                                                  c.ParameterName == ParameterName.Withdraw.MinAmount ||
                                                  c.ParameterName == ParameterName.Withdraw.ExtNumber)
                                                  );
                }
                return query.GetList(c => c.MerchantGuid == Common.CurrentManage.MerchantGuid);
            }

        }


        #endregion

        #region Result UpdateExtSettingParameters
        /// <summary>
        /// update balance parameter setting by datalist
        /// </summary>
        /// <param name="dataList"></param>
        /// <returns></returns>
        public static Result UpdateExtSettingParameters(List<T_SYS_Parameter> dataList)
        {

            using (SqlRTransaction tran = new SqlRTransaction())
            {
                tran.BeginTransaction();
                var query = Factory.CreateT_SYS_Parameter(tran);
                foreach (T_SYS_Parameter i in dataList)
                {
                    i.EntityState = EntityStates.ToBeUpdated;
                }
                query.UpdateList(dataList);
                tran.Commit();
            }
            return new Result(true);
        }
        #endregion

        #region Result AddExtSettingParameters
        /// <summary>
        /// add balance parameter setting 
        /// </summary>
        /// <param name="dataList"></param>
        /// <returns></returns>
        public static Result AddExtSettingParameters(List<T_SYS_Parameter> dataList)
        {

            using (SqlRTransaction tran = new SqlRTransaction())
            {
                tran.BeginTransaction();
                var query = Factory.CreateT_SYS_Parameter(tran);

                query.AddList(dataList);
                tran.Commit();
            }
            return new Result(true);
        }
        #endregion

        #region Result UpdateSimpleResult
        /// <summary>
        /// update simple 
        /// </summary>
        /// <param name="parameterGuid"></param>
        /// <param name="parameterName"></param>
        /// <param name="parameterValue"></param>
        /// <returns></returns>
        public static Result UpdateSimpleResult(Guid parameterGuid, string parameterName, string parameterValue)
        {
            using (var query = Factory.CreateT_SYS_Parameter())
            {
                query.Update(c => new object[]
                {
                    c.ParameterName==parameterName,
                    c.ParameterValue==parameterValue
                }, a => a.ParameterGuid == parameterGuid && a.MerchantGuid == Common.CurrentManage.MerchantGuid);
            }
            return new Result(true);
        }
        #endregion

        public static Result UpdateParameter(string title, string desc)
        {
            using (var query = Factory.CreateT_SYS_Parameter())
            {
                if (query.IsExist(a => a.ParameterName == ParameterName.WeiXinShareSeting && a.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid) != true)
                {
                    query.Add(new T_SYS_Parameter()
                    {
                        ParameterName = ParameterName.WeiXinShareSeting,
                        MerchantGuid = RFrameGenerate.Common.CurrentManage.MerchantGuid,
                        ParameterGuid = Guid.NewGuid(),
                        ParameterType = 1,
                        ParameterValue = title,
                        ParameterDescription = desc,
                    });
                }
                else
                {
                    query.Update(a => new object[] 
                    {
                        a.ParameterValue == title, 
                        a.ParameterDescription == desc 
                    }, b => b.MerchantGuid == CurrentManage.MerchantGuid && b.ParameterName == ParameterName.WeiXinShareSeting);
                }

                return new Result(true);
            }
        }

        public static T_SYS_Parameter GetShareParameter()
        {
            using (var query = Factory.CreateT_SYS_Parameter())
            {
                var param = query.GetFirstData(a => a.ParameterName == ParameterName.WeiXinShareSeting && a.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid);
                if (param == null)
                {
                    param = new T_SYS_Parameter() { ParameterValue = "分销二维码", ParameterDescription = "快来加入吧!" };
                }
                return param;
            }
        }

        public static Result Save_Parameters(List<T_SYS_Parameter> parameterList)
        {
            try
            {
                foreach (T_SYS_Parameter model in parameterList)
                {
                    using (var query = Factory.CreateT_SYS_Parameter())
                    {
                        var entity = query.GetFirstData(a => a.ParameterName == model.ParameterName && a.MerchantGuid == Common.CurrentManage.MerchantGuid);
                        if (entity == null)
                        {
                            query.Add(model);
                        }
                        else
                        {
                            entity.ParameterValue = model.ParameterValue;
                            query.Update(entity);
                        }
                    }
                }
                return new Result(true);
            }
            catch (Exception err)
            {
                return new Result(false, err.Message);
            }
        }
        /// <summary>
        /// 订单参数
        /// </summary>
        /// <param name="merchantGuid"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        public static Result GetParameters_Order(Guid merchantGuid, ref List<T_SYS_Parameter> list)
        {
            try
            {
                using (var query = Factory.CreateT_SYS_Parameter())
                {
                    var model_AutoExpirationTime = query.GetFirstData(a => a.MerchantGuid == merchantGuid && a.ParameterName == ParameterName.Order.AutoExpirationTime);
                    var model_AutomaticWrite = query.GetFirstData(a => a.MerchantGuid == merchantGuid && a.ParameterName == ParameterName.Order.AutomaticWrite);
                    var model_ExtendedReceipt = query.GetFirstData(a => a.MerchantGuid == merchantGuid && a.ParameterName == ParameterName.Order.ExtendedReceipt);

                    if (model_AutoExpirationTime != null)
                        list.Add(model_AutoExpirationTime);
                    if (model_AutomaticWrite != null)
                        list.Add(model_AutomaticWrite);
                    if (model_ExtendedReceipt != null)
                        list.Add(model_ExtendedReceipt);
                }
                return new Result(true);
            }
            catch (Exception err)
            {
                return new Result(false, err.Message);
            }
        }

        /// <summary>
        /// 退款申请参数
        /// </summary>
        /// <param name="merchantGuid"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        public static Result GetParameters_RefundApplys(Guid merchantGuid, ref List<T_SYS_Parameter> list)
        {
            try
            {
                using (var query = Factory.CreateT_SYS_Parameter())
                {
                    var model_OpenRefundService = query.GetFirstData(a => a.MerchantGuid == merchantGuid && a.ParameterName == ParameterName.Refund.OpenRefundService);
                    var model_RefundService_paid = query.GetFirstData(a => a.MerchantGuid == merchantGuid && a.ParameterName == ParameterName.Refund.RefundService_paid);
                    var model_RefundService_delivery = query.GetFirstData(a => a.MerchantGuid == merchantGuid && a.ParameterName == ParameterName.Refund.RefundService_delivery);
                    var model_RefundService_completed = query.GetFirstData(a => a.MerchantGuid == merchantGuid && a.ParameterName == ParameterName.Refund.RefundService_completed);
                    var model_RefundService_validity = query.GetFirstData(a => a.MerchantGuid == merchantGuid && a.ParameterName == ParameterName.Refund.RefundService_validity);
                    var model_commissionSettlementTime = query.GetFirstData(a => a.MerchantGuid == merchantGuid && a.ParameterName == ParameterName.CommissionMember.CommissionSettlementTime);

                    if (model_OpenRefundService != null)
                        list.Add(model_OpenRefundService);
                    if (model_RefundService_paid != null)
                        list.Add(model_RefundService_paid);
                    if (model_RefundService_delivery != null)
                        list.Add(model_RefundService_delivery);
                    if (model_RefundService_completed != null)
                        list.Add(model_RefundService_completed);
                    if (model_RefundService_validity != null)
                        list.Add(model_RefundService_validity);
                    if (model_commissionSettlementTime != null)
                        list.Add(model_commissionSettlementTime);
                }
                return new Result(true);
            }
            catch (Exception err)
            {
                return new Result(false, err.Message);
            }
        }
        /// <summary>
        /// 佣金设置参数
        /// </summary>
        /// <param name="merchantGuid"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        public static string GetParameters_Commission(Guid merchantGuid, string commission)
        {
            try
            {
                using (var query = Factory.CreateT_SYS_Parameter())
                {
                    var model_Commission = query.GetFirstData(a => a.MerchantGuid == merchantGuid && a.ParameterName == commission, isFilterMerchant: false);
                    if (model_Commission == null)
                        return "";
                    return model_Commission.ParameterValue;
                }
            }
            catch
            {
                return "";
            }
        }
        /// <summary>
        /// 佣金提现参数
        /// </summary>
        /// <param name="merchantGuid"></param>
        /// <param name="amount"></param>
        /// <returns></returns>
        public static Result CheckAllowed(Guid merchantGuid, decimal applyAmount, ref int times, ref decimal amount)
        {
            using (var query = Factory.CreateT_SYS_Parameter())
            {
                var model_WithdrawalAmountLimits = query.GetFirstData(a => a.MerchantGuid == merchantGuid && a.ParameterName == ParameterName.Distribution.WithdrawalAmountLimits);
                var model_WithdrawalNumberLimits = query.GetFirstData(a => a.MerchantGuid == merchantGuid && a.ParameterName == ParameterName.Distribution.WithdrawalNumberLimits);
                var model_AmountLimit = query.GetFirstData(a => a.MerchantGuid == merchantGuid && a.ParameterName == ParameterName.Distribution.AmountLimit);


                if (model_WithdrawalAmountLimits == null)
                    return new Result(false, "请先设置佣金提现参数！");
                if (model_WithdrawalNumberLimits == null)
                    return new Result(false, "请先设置佣金提现参数！");
                if (model_AmountLimit == null)
                    return new Result(false, "请先设置佣金提现参数！");

                times = int.Parse(model_WithdrawalNumberLimits.ParameterValue);
                amount = decimal.Parse(model_AmountLimit.ParameterValue);
                if (model_WithdrawalAmountLimits.ParameterValue != "0" && applyAmount < decimal.Parse(model_WithdrawalAmountLimits.ParameterValue))
                    return new Result(false, "金额需达到" + model_WithdrawalAmountLimits.ParameterValue + "元才能提现！");
                return new Result(true);
            }
        }
        /// <summary>
        /// 根据参数名称获取参数值
        /// </summary>
        /// <param name="parameterName"></param>
        /// <returns></returns>
        public static string GetParameterByName(string parameterName)
        {
            using (var query = Factory.CreateT_SYS_Parameter())
            {
                var plist = query.GetFirstData(c => c.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid && c.ParameterName == parameterName);

                return plist.ParameterValue ?? "auditApproach";
            }
        }

        public static T_SYS_Parameter GetParameter(string parameterName, Guid merchantGuid)
        {
            using (var query = Factory.CreateT_SYS_Parameter())
            {
                return query.GetFirstData(c => c.MerchantGuid == merchantGuid && c.ParameterName == parameterName);
            }
        }

        public static Result UpdateParam(string name, string value)
        {
            using (var tran = new SqlRTransaction())
            {
                tran.BeginTransaction();
                var query = Factory.CreateT_SYS_Parameter(tran);
                var model = query.GetFirstData(a => a.ParameterName == name && a.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid);
                if (model == null)
                {
                    query.Add(new T_SYS_Parameter()
                    {
                        ParameterName = name,
                        MerchantGuid = RFrameGenerate.Common.CurrentManage.MerchantGuid,
                        ParameterGuid = Guid.NewGuid(),
                        ParameterType = 1,
                        ParameterValue = value,
                    });

                    if (name == ParameterName.DistributionMemeber.StoreShareType || name == ParameterName.DistributionMemeber.DistributionStoreInfo)
                        SqlHelper.ExecuteNonQuery("update [T_BAS_DistributionProp] set DistributionQRCode='' where SMerchantGuid='" + CurrentManage.MerchantGuid + "'", tran);
                }
                else
                {
                    if (value != model.ParameterValue)
                    {
                        query.Update(a => new object[] 
                        {
                            a.ParameterValue == value,
                        }, b => b.MerchantGuid == CurrentManage.MerchantGuid && b.ParameterName == name);

                        if (name == ParameterName.DistributionMemeber.StoreShareType || name == ParameterName.DistributionMemeber.DistributionStoreInfo)
                            SqlHelper.ExecuteNonQuery("update [T_BAS_DistributionProp] set DistributionQRCode='' where SMerchantGuid='" + CurrentManage.MerchantGuid + "'", tran);
                    }
                }
                tran.Commit();
                return new Result(true);
            }
        }

        public static T_SYS_Parameter GetParam(string name, Guid? merGuid = null)
        {
            using (var query = Factory.CreateT_SYS_Parameter())
            {
                if (merGuid == null)
                {
                    merGuid = CurrentManage.MerchantGuid;
                }
                var model = query.GetFirstData(a => a.MerchantGuid == merGuid && a.ParameterName == name, isFilterMerchant: false);
                return model;
            }
        }
        /// <summary>
        /// 获取参数值，全部转小写
        /// </summary>
        public static string GetParamValue(string name)
        {
            var param = GetParam(name);

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

            if (string.IsNullOrEmpty(param.ParameterValue)) return string.Empty;

            return param.ParameterValue.ToLower(); ;
        }

        public static string GetParamValue(string name, string defaultValue, T_BAS_MerchantsAgent mer = null)
        {
            var param = GetParam(name, (mer != null && mer.GoodsDeliveryType == AgentRuleConst.GoodsDeliveryType.总部 ? mer.TopMerchantGuid : null));

            if (param == null) return defaultValue;

            if (string.IsNullOrEmpty(param.ParameterValue)) return defaultValue;

            return param.ParameterValue;
        }

        public static List<T_SYS_Parameter> GetParameters(string[] names)
        {
            if (names == null || names.Length <= 0) return new List<T_SYS_Parameter>(0);

            using (var query = Factory.CreateT_SYS_Parameter())
            {
                var list = query.GetList(m => m.ParameterName.SqlIn(names) && m.MerchantGuid == Common.CurrentManage.MerchantGuid);

                if (list == null) return new List<T_SYS_Parameter>(0);

                return list;
            }
        }
    }
}
