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

namespace RFrameGenerate.BLL
{
    public class ProductCrowdManage
    {
        #region 一元购商品管理

        public static List<T_BAS_Products> GetPageList(GridModel gridModel, string name)
        {
            using (var query = Factory.CreateT_BAS_Products())
            {
                return query.GetPageList(gridModel, a => a.MerchantGuid == Common.CurrentManage.MerchantGuid && a.ProductName.SqlLike(name), true, p => p.ProductCode, DAL.Enums.OrderMethods.Default);
            }
        }

        public static Result Join(Guid productGuid)
        {
            using (var tran = new SqlRTransaction())
            {
                var query = Factory.CreateT_BAS_Products(tran);
                var product = query.GetFirstData(a => a.ProductGuid == productGuid);
                if (product != null)
                {
                    var queryCrow = Factory.CreateT_CR_ProductCrowd(tran);
                    if (queryCrow.IsExist(a => a.ProductGuid == product.ProductGuid) != true)
                    {
                        var pc = new T_CR_ProductCrowd()
                        {
                            ProductGuid = product.ProductGuid,
                            JoinDate = DateTime.Now,
                            MaxPeriod = 10000,
                            IsAutoEnable = false,
                            Price = product.Price,
                            UnitPrice = product.Price,
                            ProductName = product.ProductName,
                            ProductCrowdGuid = Guid.NewGuid(),
                            Description = product.Description,
                            ProductImage = product.ProductImage,
                            ProductImage1 = product.ProductImage1,
                            ProductImage2 = product.ProductImage2,
                            ProductImage3 = product.ProductImage3,
                            ProductImage4 = product.ProductImage4,
                            Sort = product.Sort,
                            MerchantGuid = RFrameGenerate.Common.CurrentManage.MerchantGuid,                            
                            BuyUnitPrice = 1,
                        };
                        queryCrow.Add(pc);
                        return new Result(true);
                    }
                    else
                    {
                        return new Result(false, "商品重复添加");
                    }
                }
                else
                {
                    return new Result(false, "找不到商品");
                }
            }
        }

        #endregion

        #region 后台
        public static List<T_CR_ProductCrowd> GetProductCrowdPage(GridModel gridModel)
        {
            using (var query = Factory.CreateT_CR_ProductCrowd())
            {
                return query.GetPageList(gridModel, a => a.MerchantGuid == Common.CurrentManage.MerchantGuid, false, b => b.JoinDate, OrderMethods.DESC);
            }
        }
        public static List<T_ST_CrowdPeriodsView> GetProductCrowdPeriodPage(GridModel gridModel, Guid? crowdGuid)
        {
            if (crowdGuid == null) return new List<T_ST_CrowdPeriodsView>();
            using (var query = Factory.CreateT_ST_CrowdPeriodsView())
            {
                return query.GetPageList(gridModel, a => a.ProductCrowdGuid == crowdGuid, false, b => b.CrowdPeriods, OrderMethods.DESC);
            }
        }
        public static List<T_ST_CrowdPeriodsView> GetProductCrowdPeriodPage(GridModel gridModel)
        {
            using (var query = Factory.CreateT_ST_CrowdPeriodsView())
            {
                return query.GetPageList(gridModel, a => a.OpenDate.SqlIsNotNull(), false, b => b.CrowdPeriods, OrderMethods.DESC);
            }
        }

        public static Result EditEnable(Guid crowdGuid, bool state)
        {
            try
            {
                using (var tran = new SqlRTransaction())
                {
                    var query = Factory.CreateT_CR_ProductCrowd(tran);
                    Result result = new Result(true);
                    tran.BeginTransaction();
                    query.Update(a => new object[] { a.IsAutoEnable == state }, b => b.ProductCrowdGuid == crowdGuid);
                    if (state == true)
                    {//启用自动创建下期
                        result = AddPeri(crowdGuid, tran);
                    }
                    else
                    {
                        result = DelPeri(crowdGuid, tran);
                    }
                    if (result.State == true)
                        tran.Commit();
                    else
                        tran.Rollback();
                    return result;
                }
            }
            catch (Exception ex)
            {
                return new Result(false, ex.Message);
            }
        }
        public static Result Edit(T_CR_ProductCrowd data)
        {
            if (data.UnitPrice % data.BuyUnitPrice != 0)
                return new Result(false, "总参与人次只能为每次购买单价倍数!");
            try
            {
                using (var query = Factory.CreateT_CR_ProductCrowd())
                {
                    query.Update(a => new object[] 
                    { 
                        a.ProductName == data.ProductName,
                        a.UnitPrice == data.UnitPrice, 
                        //a.MaxPeriod == data.MaxPeriod, 
                        a.BuyUnitPrice == data.BuyUnitPrice,
                        a.Sort == data.Sort 
                    }, b => b.ProductCrowdGuid == data.ProductCrowdGuid);
                    return new Result(true);
                }
            }
            catch (Exception ex)
            {
                return new Result(false, ex.Message);
            }
        }
        public static Result Del(Guid crowdGuid)
        {
            try
            {
                using (var query = Factory.CreateT_CR_ProductCrowd())
                {
                    query.Delete(a => a.ProductCrowdGuid == crowdGuid);
                    return new Result(true);
                }
            }
            catch (Exception ex)
            {
                return new Result(false, ex.Message);
            }
        }
        #endregion

        #region 删除基数

        public static Result DelPeri(Guid crowdGuid, SqlRTransaction tran = null)
        {
            Result result = new Result(false, "失败");
            bool isdispose = false;
            if (tran == null)
            {
                isdispose = true;
                tran = new SqlRTransaction();
            }

            tran.BeginTransaction();
            var query = Factory.CreateT_CR_ProductCrowd(tran);
            T_CR_ProductCrowd crow = query.GetFirstData(a => a.ProductCrowdGuid == crowdGuid, false, null, OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
            var queryPeri = Factory.CreateT_CR_ProductCrowdPeriods(tran);
            //最后一期
            var peri = queryPeri.GetFirstData(a => a.ProductCrowdGuid == crow.ProductCrowdGuid, false, b => b.CrowdPeriods, OrderMethods.DESC, RFramework.SQLServer.Enums.LockType.Default, false);
            if (peri != null)
            {
                var lockmoel = CrowdPeriodLock.GetLock(peri.ProductCrowdPeriodGuid);
                lock (lockmoel)
                {
                    var queryluck = Factory.CreateT_CR_CrowdLuckyNumber(tran);
                    if (peri.RemainTime == peri.TotalTime)
                    {
                        //删除本期
                        queryluck.Delete(a => a.ProductCrowdPeriodGuid == peri.ProductCrowdPeriodGuid);
                        queryPeri.Delete(a => a.ProductCrowdPeriodGuid == peri.ProductCrowdPeriodGuid);
                        result.State = true;
                        result.Msg = string.Empty;
                    }
                    else
                    {
                        result.State = true;
                        result.Msg = string.Empty;
                    }
                }
            }
            tran.Commit();

            if (isdispose == true)
                tran.Dispose();

            return result;
        }
        #endregion

        #region 添加期数
        /// <summary>
        /// 添加期
        /// </summary>
        public static Result AddPeri(Guid crowdGuid, SqlRTransaction tran = null)
        {
            Result result;
            T_CR_ProductCrowd crow;
            bool isdispose = false;
            if (tran == null)
            {
                isdispose = true;
                tran = new SqlRTransaction();
            }

            var query = Factory.CreateT_CR_ProductCrowd(tran);
            crow = query.GetFirstData(a => a.ProductCrowdGuid == crowdGuid, false, null, OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
            if (crow == null)
                return new Result(false, "不存在众筹商品");

            if (crow.UnitPrice <= 1)
                return new Result(false, "总参与人次不能小于等于1");

            result = AddPeri(crow, tran);

            if (isdispose == true)
                tran.Dispose();

            return result;
        }
        /// <summary>
        /// 添加期
        /// </summary>
        public static Result AddPeri(T_CR_ProductCrowd crow, SqlRTransaction tran = null)
        {
            bool isdispose = false;
            if (tran == null)
            {
                isdispose = true;
                tran = new SqlRTransaction();
            }

            var queryPeri = Factory.CreateT_CR_ProductCrowdPeriods(tran);
            var peri = queryPeri.GetFirstData(a => a.ProductCrowdGuid == crow.ProductCrowdGuid, false, b => b.CrowdPeriods, OrderMethods.DESC, RFramework.SQLServer.Enums.LockType.Default, false);

            int maxtime = 0;
            if (peri != null)
            {
                maxtime = queryPeri.GetCount(a => a.ProductCrowdGuid == peri.ProductCrowdGuid.Value, false, false);
            }

            if ((peri != null && peri.RemainTime > 0) || crow.IsAutoEnable != true || maxtime > crow.MaxPeriod)//存在时判断是否可以自动添加下一期
            {
                if (isdispose == true)
                    tran.Dispose();
                return new Result(true);
            }

            int CrowdPeriods = 0;
            if (peri == null)
                CrowdPeriods = 1;
            else
                CrowdPeriods = peri.CrowdPeriods.Value + 1;

            tran.BeginTransaction();
            var period = new T_CR_ProductCrowdPeriods()
             {
                 ProductCrowdGuid = crow.ProductCrowdGuid,
                 CrowdPeriods = CrowdPeriods,
                 BuyUnitPrice = crow.BuyUnitPrice,
                 JoinDate = DateTime.Now,
                 BuyTime = 0,
                 RemainTime = (int)crow.UnitPrice,
                 TotalTime = (int)crow.UnitPrice,
                 Sort = 1,
                 ProductCrowdPeriodGuid = Guid.NewGuid(),
                 OpenDate = null,
                 Formula = null,
                 MerchantGuid = crow.MerchantGuid,
             };
            queryPeri.Add(period);
            //添加幸运号
            CrowdLuckyNumberManage.AddLuckNumber(period.ProductCrowdPeriodGuid, period.TotalTime.Value, crow.MerchantGuid.Value);
            tran.Commit();


            if (isdispose == true)
                tran.Dispose();

            return new Result(true);
        }
        #endregion

        #region 微信前端调用  add by panwp

        //上架新品
        public static List<T_CR_ProductCrowd> GetNewProducts()
        {
            using (var query = Factory.CreateT_CR_ProductCrowd())
            {
                return query.GetTopData("3", a => a.MerchantGuid == Common.CurrentManage.MerchantGuid, false, b => b.JoinDate, OrderMethods.DESC, RFramework.SQLServer.Enums.LockType.Default, false);
            }
        }

        public static T_CR_ProductCrowd GetProductCrowd(Guid? crowdGuid)
        {
            if (crowdGuid == null || crowdGuid.Value == Guid.Empty) return null;

            using (var query = Factory.CreateT_CR_ProductCrowd())
            {
                return query.GetDataByGuid(crowdGuid.Value);
            }
        }


        #endregion

        public static T_CR_ProductCrowdPeriods GetProductCrowdLastPeriod(Guid crowdGuid)
        {
            using (var query = Factory.CreateT_CR_ProductCrowdPeriods())
            {
                return query.GetFirstData(a => a.ProductCrowdGuid == crowdGuid, false, b => b.CrowdPeriods, OrderMethods.DESC);
            }
        }
        /// <summary>
        /// 获取中奖聊表
        /// </summary>
        public static List<T_ST_CrowdPeriodsWinningView> GetWinnigPage(GridModel gridModel, Guid crowdGuid, int? period)
        {
            using (var query = Factory.CreateT_ST_CrowdPeriodsWinningView())
            {
                return query.GetPageList(gridModel, a => a.ProductCrowdGuid == crowdGuid && a.CrowdPeriods == period, true, o => o.CrowdPeriods, OrderMethods.DESC);
            }
        }

        public static WinningProduct GetWinProduct(Guid periodGuid)
        {
            using (var query = Factory.CreateProcedure())
            {
                return query.GetWinningProduct(periodGuid);
            }
        }

        public static bool IsCrowding()
        {
            var Crowdfunding = ParameterManage.GetParam(ParameterName.MarketingName.Crowdfunding);
            if (Crowdfunding != null && Crowdfunding.ParameterValue.ToLower() == "true")
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
