using RFrameGenerate.Common;
using RFrameGenerate.DAL.Enums;
using RFrameGenerate.Model;
using RFramework.SQLServer;
using RFramework.SQLServer.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RFramework.SQLQuery;

namespace RFrameGenerate.BLL
{
    public class AgentManage
    {
        public static Result IsValid(string loginName, string password, string oldPwd, out T_BAS_Agents user)
        {
            using (var query = Factory.CreateT_BAS_Agents())
            {
                user = query.GetFirstData(a => a.UserID == loginName, false, null, OrderMethods.ASC, LockType.Default, false);
                if (user == null)
                    return new Result(false, "不存在用户:" + loginName);
                if (user.Password == password)
                {
                    if (user.StartDate <= DateTime.Now && DateTime.Now <= user.ExpireData)
                    {
                        return new Result(true);
                    }
                    else
                    {
                        return new Result(false, "账号已过期");
                    }
                }
                else
                {
                    return new Result(false, "密码不正确");
                }
            }
        }

        public static Result SetEnabel(Guid id, bool enable)
        {
            //退费
            using (var tran = new SqlRTransaction())
            {
                var query = Factory.CreateT_BAS_Agents(tran);
                var query_record = Factory.CreateT_BAS_OpenMerchantRrecords(tran);
                var model = query.GetFirstData(a => a.AgentGuid == id);
                if (model == null) return new Result(false, "找不到该数据！");
                try
                {
                    tran.BeginTransaction();
                    if (enable == false && DateTimeEx.DateDiff(model.StartDate.Value) <= 5)
                    {

                        model.CumulativeAmount = 0;
                        model.IsEnable = false;
                        model.EntityState = EntityStates.ToBeUpdated;
                        query.Update(model,false);
                        
                        query_record.Add(new T_BAS_OpenMerchantRrecords()
                        {
                            OpenMerchantRrecordGuid = Guid.NewGuid(),
                            AgentGuid = id,
                            MerchantGuid = Common.CurrentManage.MerchantGuid,
                            OpenDate = DateTime.Now,
                            OpenType = model.UserType,
                            PayType = DictionaryConst.PayType.Refund,
                            Amount = model.DepositsAmount,
                            AvailableBalance = 0,
                            Remark = "关闭商家5天内退款"
                        });
                    }
                    else
                    {
                        model.IsEnable = enable;
                        model.EntityState = EntityStates.ToBeUpdated;
                        query.Update(model);
                    }
                    tran.Commit();
                    return new Result(true);
                }
                catch (Exception err)
                {
                    tran.Rollback();
                    return new Result(false, err.Message);
                }

            }
        }

        public static Result IsKeyValid(string loginName, string key, out T_BAS_Agents user)
        {
            using (var query = Factory.CreateT_BAS_Agents())
            {
                user = query.GetFirstData(a => a.UserID == loginName, false, null, OrderMethods.ASC, LockType.Default, false);
                if (user == null)
                    return new Result(false, "不存在用户:" + loginName);
                if (user.Password == key)
                {
                    if (user.StartDate <= DateTime.Now && DateTime.Now <= user.ExpireData)
                    {
                        return new Result(true);
                    }
                    else
                    {
                        return new Result(false, "账号已过期");
                    }
                }
                else
                    return new Result(false, "密码不正确");
            }
        }

        public static List<T_BAS_Agents> GetAgentPageList(GridModel grid, string userid, string company)
        {
            using (var query = Factory.CreateT_BAS_Agents())
            {
                if (Common.CurrentUser.GetLoginType() == DictionaryConst.LoginType.HeadOffice)
                {
                    return query.GetPageList(grid, a => a.ParentAgentGuid == CurrentUser.GetCurrUserGuid() && a.UserID == userid && a.AgentCompany.SqlLike(company), true, b => b.StartDate, OrderMethods.DESC);
                }
                else
                {
                    return query.GetPageList(grid, a => a.ParentAgentGuid == CurrentUser.GetCurrUserGuid() && a.UserID == userid && a.AgentCompany.SqlLike(company), true, b => b.StartDate, OrderMethods.DESC);
                }
            }
        }

        public static List<T_BAS_Agents> GetAgentList()
        {
            using (var query = Factory.CreateT_BAS_Agents())
            {
                return query.GetList(a => a.ParentAgentGuid == CurrentUser.GetCurrUserGuid(), true, b => b.StartDate, OrderMethods.DESC);
            }
        }

        public static List<T_BAS_Agents> GetHeadList()
        {
            using (var query = Factory.CreateT_BAS_Agents())
            {
                return query.GetList(a => a.ParentAgentGuid.SqlIsNull());
            }
        }

        public static List<T_BAS_Agents> GetChildList(Guid parentAgentGuid)
        {
            using (var query = Factory.CreateT_BAS_Agents())
            {
                return query.GetList(a => a.ParentAgentGuid == parentAgentGuid);
            }
        }

        public static T_BAS_Agents GetCurrentAgent()
        {
            using (var query = Factory.CreateT_BAS_Agents())
            {
                return query.GetFirstData(a => a.AgentGuid == RFrameGenerate.Common.CurrentUser.GetCurrUserGuid());
            }
        }

        public static Result Add(T_BAS_Agents agent)
        {
            using (var tran = new SqlRTransaction())
            {
                tran.BeginTransaction();
                var query = Factory.CreateT_BAS_Agents(tran);
                agent.ParentAgentGuid = RFrameGenerate.Common.CurrentUser.GetCurrUserGuid();
                agent.Password = Utils.Md5(agent.Password);
                agent.AgentGuid = Guid.NewGuid();
                agent.UserType = DictionaryConst.LoginType.Agent;
                agent.CumulativeAmount = 0;
                agent.IsEnable = true;
                if (query.IsExist(a => a.ParentAgentGuid == agent.ParentAgentGuid && a.UserID == agent.UserID) != true)
                {
                    if (agent.DepositsAmount > 0)
                    {
                        var queryapr = Factory.CreateT_BAS_AgentPrepaidRrecords(tran);
                        queryapr.Add(new T_BAS_AgentPrepaidRrecords()
                        {
                            AgentGuid = agent.AgentGuid,
                            AgentPrepaidRrecordGuid = Guid.NewGuid(),
                            Amount = agent.DepositsAmount,
                            PrepaidDate = DateTime.Now
                        });
                    }

                    query.Add(agent);
                }
                else
                {
                    return new Result(false, agent.UserID + "已存在,无法新增.");
                }
                tran.Commit();
                return new Result(true);
            }
        }


        public static Result ChangePassword(Guid id, string password)
        {
            try
            {
                using (var query = Factory.CreateT_BAS_Agents())
                {
                    query.Update(a => new object[]
                {
                    a.Password== RFrameGenerate.Common.Utils.Md5( password)
                }, b => b.AgentGuid == id);
                }
                return new Result(true);
            }
            catch (Exception ex)
            {
                return new Result(false, ex.Message);
            }
        }


        public static Result ChangePassword(string userid, string password)
        {
            try
            {
                using (var query = Factory.CreateT_BAS_Agents())
                {
                    query.Update(a => new object[]
                {
                    a.Password== RFrameGenerate.Common.Utils.Md5( password)
                }, b => b.UserID == userid);
                }
                return new Result(true);
            }
            catch (Exception ex)
            {
                return new Result(false, ex.Message);
            }
        }
        /// <summary>
        /// 充值
        /// </summary>
        /// <param name="agentGuid"></param>
        /// <param name="rech"></param>
        /// <returns></returns>
        public static Result Recharge(Guid agentGuid, decimal rech)
        {
            try
            {
                using (var tran = new SqlRTransaction())
                {
                    decimal depositsAmount = 0;
                    decimal balance = 0;
                    int year = 0;
                    var query = Factory.CreateT_BAS_Agents(tran);
                    var queryRech = Factory.CreateT_BAS_AgentPrepaidRrecords(tran);
                    var queryRecord = Factory.CreateT_BAS_OpenMerchantRrecords(tran);
                    tran.BeginTransaction();
                    queryRech.Add(new T_BAS_AgentPrepaidRrecords()
                    {
                        AgentGuid = agentGuid,
                        AgentPrepaidRrecordGuid = Guid.NewGuid(),
                        Amount = rech,
                        PrepaidDate = DateTime.Now
                    });
                    var agent = query.GetFirstData(a => a.AgentGuid == agentGuid);
                    depositsAmount = agent.DepositsAmount + rech;
                    balance = depositsAmount - agent.CumulativeAmount;
                    year = agent.ExpireData.Value.Year - agent.StartDate.Value.Year;
                    query.Update(a => new object[]
                    {
                        a.DepositsAmount== depositsAmount
                    }, b => b.AgentGuid == agentGuid);

                    queryRecord.Add(new T_BAS_OpenMerchantRrecords()
                    {
                        OpenMerchantRrecordGuid = Guid.NewGuid(),
                        AgentGuid = agentGuid,
                        MerchantGuid = Common.CurrentManage.MerchantGuid,
                        OpenDate = DateTime.Now,
                        OpenType = agent.UserType,
                        PayType = DictionaryConst.PayType.Recharge,
                        Amount = rech,
                        OpenYear=year,
                        AvailableBalance = balance,
                        Remark = "充值" + rech.ToString() + "金额"
                    });
                    tran.Commit();
                }
                return new Result(true);
            }
            catch (Exception ex)
            {
                return new Result(false, ex.Message);
            }
        }

        /// <summary>
        /// 商家续费
        /// </summary>
        /// <param name="guid">商家Guid</param>
        /// <param name="money">续费金额</param>
        /// <param name="years">续费年数</param>
        /// <returns></returns>
        public static Result Renew(Guid guid, decimal money, int years)
        {
            using (var tran = new SqlRTransaction())
            {
                try
                {
                    decimal balance = 0M;
                    decimal cumulativeAmount = 0M;
                    //1.增加累积金额 写入流水
                    var query_agent = Factory.CreateT_BAS_Agents(tran);
                    var query_record = Factory.CreateT_BAS_OpenMerchantRrecords(tran);
                    var query_merchantguid = Factory.CreateT_BAS_Merchants(tran);
                    var model_agent = query_agent.GetFirstData(a => a.AgentGuid == CurrentUser.GetCurrUserGuid(), isFilterMerchant: false);
                    if (model_agent == null) return new Result(false, "代理商不存在！");
                    var model_merchantguid = query_merchantguid.GetFirstData(a => a.MerchantGuid == guid, isFilterMerchant: false);
                    if (model_merchantguid == null) return new Result(false, "该商家不存在！");
                    //判断余额是否够续费

                    if (CurrentUser.GetLoginType() != DictionaryConst.LoginType.HeadOffice) {
                        balance = model_agent.DepositsAmount - model_agent.CumulativeAmount - money;
                        if (balance < 0)
                        {
                            return new Result(false, "您的账号余额不足，请充值后再执行操作！");
                        }
                    }
                    //累计消费
                    cumulativeAmount = model_agent.CumulativeAmount + money;

                    query_agent.Update(a => new Object[] { a.CumulativeAmount == cumulativeAmount }, a => a.AgentGuid == CurrentUser.GetCurrUserGuid(), false);
                    //添加流水
                    query_record.Add(new T_BAS_OpenMerchantRrecords()
                    {
                        OpenMerchantRrecordGuid = Guid.NewGuid(),
                        AgentGuid = model_agent.AgentGuid,
                        MerchantGuid = guid,
                        OpenDate = DateTime.Now,
                        OpenType = model_agent.UserType,
                        PayType = DictionaryConst.PayType.Renew,
                        Amount = money,
                        OpenYear = years,
                        AvailableBalance = balance,
                        Remark = "续费" + money.ToString() + "元"
                    });
                    //2.修改商家到期时间 ，支持多年
                    var expireDate = model_merchantguid.ExpireDate.Value.AddYears(years);
                    query_merchantguid.Update(a => new Object[] { a.ExpireDate == expireDate }, a => a.MerchantGuid == guid&&a.AgentGuid==model_agent.AgentGuid, false);
                    return new Result(true);
                }
                catch (Exception err)
                {
                    return new Result(false, err.Message);
                }
            }
        }


        public static List<T_ST_MerchantRecords> LoadAgentRecords(GridModel gridModel, string agentCompany, string userID)
        {
            using (var query = Factory.CreateT_ST_MerchantRecords())
            {
                return query.GetPageList(gridModel, a => a.AgentCompany.SqlLike(agentCompany) && a.UserID.SqlLike(userID)&&a.AgentGuid==Common.CurrentUser.GetCurrUserGuid(), true, b => b.UserID, OrderMethods.ASC,LockType.Default,false);
            }
        }

        public static Result DelMerchant(Guid id)
        {
            try
            {
                using (var tran=new SqlRTransaction())
                {
                    decimal balance = 0;
                    decimal amount=0;
                    int years=0;
                    var query = Factory.CreateT_BAS_Merchants(tran);
                    var query_agent = Factory.CreateT_BAS_Agents(tran);
                    var query_records=Factory.CreateT_BAS_OpenMerchantRrecords(tran);
                    var model = query.GetFirstData(a => a.MerchantGuid == id && a.AgentGuid == Common.CurrentUser.GetCurrUserGuid(),false,null,OrderMethods.Default,LockType.Default,false);
                    if (model == null) return new Result(false, "该商家不存在或已删除！");
                    if (DaysDiff(model.CreateDate.Value, DateTime.Now) > 5) return new Result(false, "该商家开通时间超过5天不允许删除！");
                    //还原累计消费
                   var agent= query_agent.GetFirstData(a => a.AgentGuid == Common.CurrentUser.GetCurrUserGuid(), false, null, OrderMethods.Default, LockType.Default, false);
                   if (agent == null) return new Result(false, "找不到代理商！");
                   var records = query_records.GetList(a => a.AgentGuid == Common.CurrentUser.GetCurrUserGuid() && a.MerchantGuid == id, false, null, OrderMethods.Default, LockType.Default, false);
                   if (records == null) return new Result(false, "找不到此代理商消费记录！");
                   amount=records.Sum(a => a.Amount).Value;
                   agent.CumulativeAmount -= amount;

                    years=model.ExpireDate.Value.Year-model.CreateDate.Value.Year;
                    //余额
                   if (CurrentUser.GetLoginType() != DictionaryConst.LoginType.HeadOffice) balance = agent.DepositsAmount - agent.CumulativeAmount;
                   
                    query.Delete(model.MerchantGuid, false);
                    //更新代理余额
                    query_agent.Update(agent,false);

                    //写入记录
                    query_records.Add(new T_BAS_OpenMerchantRrecords()
                    {
                        OpenMerchantRrecordGuid = Guid.NewGuid(),
                        AgentGuid = agent.AgentGuid,
                        MerchantGuid = id,
                        OpenDate = DateTime.Now,
                        OpenType = agent.UserType,
                        PayType = DictionaryConst.PayType.Refund,
                        Amount = amount,
                        OpenYear = years,
                        AvailableBalance = balance,
                        Remark = "退费" + amount.ToString() + "元"
                    });
                    
                    return new Result(true);
                }
            }
            catch (Exception err)
            {
                return new Result(false, err.Message);
            }
        }

        /// <summary>
        /// 时间差
        /// </summary>
        /// <param name="DateTime1"></param>
        /// <param name="DateTime2"></param>
        /// <returns></returns>
        public static int DaysDiff(DateTime DateTime1, DateTime DateTime2)
        {
            int dateDiff = 0;
            try
            {
                TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
                TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
                TimeSpan ts = ts1.Subtract(ts2).Duration();
                dateDiff = int.Parse(ts.Days.ToString());
            }
            catch
            {

            }
            return dateDiff;
        }
    }
}
