using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Mall.Model.Extend.Product;
using Mall.Repository.BaseSetUp;
using Mall.Repository.Product;
using Mall.Repository.User;
using Newtonsoft.Json;
using VT.FW.DB;

namespace Mall.Module.Product
{
    /// <summary>
    /// 活动处理层
    /// </summary>
    public class ActivityModule
    {
        /// <summary>
        /// 活动
        /// </summary>
        private readonly RB_Goods_ActivityRepository goods_ActivityRepository = new RB_Goods_ActivityRepository();
        /// <summary>
        /// 活动奖品领取
        /// </summary>
        private readonly RB_Goods_Activity_GetRepository goods_Activity_GetRepository = new RB_Goods_Activity_GetRepository();
        /// <summary>
        /// 商品分类
        /// </summary>
        private readonly RB_Product_CategoryRepository product_CategoryRepository = new RB_Product_CategoryRepository();
        /// <summary>
        /// 商品
        /// </summary>
        private readonly RB_GoodsRepository goodsRepository = new RB_GoodsRepository();
        /// <summary>
        /// 订单
        /// </summary>
        private readonly RB_Goods_OrderRepository goods_OrderRepository = new RB_Goods_OrderRepository();
        /// <summary>
        /// 小程序基础
        /// </summary>
        private readonly RB_MallBaseRepository mallBaseRepository = new RB_MallBaseRepository();


        /// <summary>
        /// 获取活动分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Goods_Activity_Extend> GetGoodsActivityPageList(int pageIndex, int pageSize, out long count, RB_Goods_Activity_Extend demodel)
        {
            var list = goods_ActivityRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any()) {
                string CategoryIds = string.Join(",", list.Where(x => x.RangeType == 1).Select(x => x.RangeIds));
                string GoodsIds = string.Join(",", list.Where(x => x.RangeType == 2).Select(x => x.RangeIds));
                List<RB_Product_Category_Extend> categoryList = new List<RB_Product_Category_Extend>();
                if (!string.IsNullOrEmpty(CategoryIds)) {
                    categoryList = product_CategoryRepository.GetList(new RB_Product_Category_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, CategoryIds = CategoryIds });
                }
                List<RB_Goods_Extend> goodsList = new List<RB_Goods_Extend>();
                if (!string.IsNullOrEmpty(GoodsIds)) {
                    goodsList = goodsRepository.GetSingleList(new RB_Goods_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, GoodsIds = GoodsIds });
                }
                foreach (var item in list) {
                    if (item.RangeType == 1)
                    {
                        List<int> RangeIdList = JsonConvert.DeserializeObject<List<int>>("[" + item.RangeIds + "]");
                        item.RangeList = categoryList.Where(x => RangeIdList.Contains(x.Id)).Select(x => new
                        {
                            x.Id,
                            x.Name,
                            Image = ""
                        });
                    }
                    else {
                        List<int> RangeIdList = JsonConvert.DeserializeObject<List<int>>("[" + item.RangeIds + "]");
                        item.RangeList = goodsList.Where(x => RangeIdList.Contains(x.Id)).Select(x => new
                        {
                            x.Id,
                            x.Name,
                            Image = x.CarouselImage != "" && x.CarouselImage != "[]" ? JsonConvert.DeserializeObject<List<string>>(x.CarouselImage)[0] : ""
                        });
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 获取活动详情
        /// </summary>
        /// <param name="activityId"></param>
        /// <returns></returns>
        public RB_Goods_Activity_Extend GetGoodsActivityInfo(int activityId)
        {
            var model = goods_ActivityRepository.GetEntity<RB_Goods_Activity_Extend>(activityId);
            if (model != null) {
                string CategoryIds = model.RangeType == 1 ? model.RangeIds : "";
                string GoodsIds = model.RangeType == 2 ? model.RangeIds : "";
                List<RB_Product_Category_Extend> categoryList = new List<RB_Product_Category_Extend>();
                if (!string.IsNullOrEmpty(CategoryIds))
                {
                    categoryList = product_CategoryRepository.GetList(new RB_Product_Category_Extend() { TenantId = model.TenantId, MallBaseId = model.MallBaseId, CategoryIds = CategoryIds });
                }
                List<RB_Goods_Extend> goodsList = new List<RB_Goods_Extend>();
                if (!string.IsNullOrEmpty(GoodsIds))
                {
                    goodsList = goodsRepository.GetSingleList(new RB_Goods_Extend() { TenantId = model.TenantId, MallBaseId = model.MallBaseId, GoodsIds = GoodsIds });
                }
                
                if (model.RangeType == 1)
                {
                    List<int> RangeIdList = JsonConvert.DeserializeObject<List<int>>("[" + model.RangeIds + "]");
                    model.RangeList = categoryList.Where(x => RangeIdList.Contains(x.Id)).Select(x => new
                    {
                        x.Id,
                        x.Name,
                        Image = ""
                    });
                }
                else
                {
                    List<int> RangeIdList = JsonConvert.DeserializeObject<List<int>>("[" + model.RangeIds + "]");
                    model.RangeList = goodsList.Where(x => RangeIdList.Contains(x.Id)).Select(x => new
                    {
                        x.Id,
                        x.Name,
                        Image = x.CarouselImage != "" && x.CarouselImage != "[]" ? JsonConvert.DeserializeObject<List<string>>(x.CarouselImage)[0] : ""
                    });
                }
            }
            return model ?? new RB_Goods_Activity_Extend();
        }

        /// <summary>
        /// 获取活动验证码
        /// </summary>
        /// <param name="qitem"></param>
        /// <returns></returns>
        private string GetActivityCode(RB_Goods_Activity_Extend qitem)
        {
            int min = Convert.ToInt32("1111111111".Substring(0, qitem.CodeLength - 1));
            int max = Convert.ToInt32("9999999999".Substring(0, qitem.CodeLength - 1));
            Random rd = new Random();
            string code = rd.Next(min, max).ToString();
            return code;
        }

        /// <summary>
        /// 获取小程序端 活动列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Goods_Activity_Extend> GetGoodsActivityPageListForApplet(int pageIndex, int pageSize, out long count, RB_Goods_Activity_Extend demodel, int UserId)
        {
            var list = goods_ActivityRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                string CategoryIds = string.Join(",", list.Where(x => x.RangeType == 1).Select(x => x.RangeIds));
                string GoodsIds = string.Join(",", list.Where(x => x.RangeType == 2).Select(x => x.RangeIds));
                List<RB_Product_Category_Extend> categoryList = new List<RB_Product_Category_Extend>();
                if (!string.IsNullOrEmpty(CategoryIds))
                {
                    categoryList = product_CategoryRepository.GetList(new RB_Product_Category_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, CategoryIds = CategoryIds });
                }
                List<RB_Goods_Extend> goodsList = new List<RB_Goods_Extend>();
                if (!string.IsNullOrEmpty(GoodsIds))
                {
                    goodsList = goodsRepository.GetSingleListForGoodsId(new RB_Goods_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, GoodsIds = GoodsIds });
                }
                //查询中奖活动
                var myPrizeList = goods_Activity_GetRepository.GetList(new RB_Goods_Activity_Get_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, ActivityIds = string.Join(",", list.Select(x => x.Id)), UserId = UserId });
                int AfterTime = 0;
                //if (demodel.QActivityState == 1) {
                var mallModel = mallBaseRepository.GetEntity(demodel.MallBaseId);
                if (mallModel != null && mallModel.AfterTime > 0)
                {
                    AfterTime = mallModel.AfterTime;
                }
                //}
                foreach (var item in list)
                {
                    if (item.RangeType == 1)
                    {
                        List<int> RangeIdList = JsonConvert.DeserializeObject<List<int>>("[" + item.RangeIds + "]");
                        item.RangeList = categoryList.Where(x => RangeIdList.Contains(x.Id)).Select(x => new
                        {
                            x.Id,
                            x.Name
                        });
                    }
                    else
                    {
                        List<int> RangeIdList = JsonConvert.DeserializeObject<List<int>>("[" + item.RangeIds + "]");
                        item.RangeList = goodsList.Where(x => RangeIdList.Contains(x.Id)).Select(x => new
                        {
                            x.Id,
                            x.Name
                        });
                    }
                    var pmodel = myPrizeList.Where(x => x.ActivityId == item.Id).FirstOrDefault();
                    if (pmodel != null)
                    {
                        item.IsFinish = 1;
                    }
                    else
                    {
                        item.IsFinish = 2;
                        //if (demodel.QActivityState == 1)
                        //{
                        //查询分类/商品下  
                        var clist = goods_OrderRepository.GetGoodsNumForCategoryOrGoods_V2(item, UserId, AfterTime);//查询所有活动日期内的已付款订单
                        if (item.Tier == 1 || item.Tier == 2 || item.Tier == 3)
                        {
                            //如果属于有限定层级  需要先遍历 查询出对应的层级人员
                            foreach (var qitem in clist)
                            {
                                List<int> UserIdList = JsonConvert.DeserializeObject<List<int>>("[" + qitem.UserTree + "]");
                                qitem.OneUserId = UserIdList[0];
                                if (UserIdList.Count() > 1)
                                {
                                    qitem.TwoUserId = UserIdList[1];
                                }
                                if (UserIdList.Count() > 2)
                                {
                                    qitem.TwoUserId = UserIdList[2];
                                }
                            }
                            if (item.Tier == 1)
                            {
                                clist = clist.Where(x => x.OneUserId == UserId).ToList();
                            }
                            else if (item.Tier == 2)
                            {
                                clist = clist.Where(x => x.OneUserId == UserId || x.TwoUserId == UserId).ToList();
                            }
                            else
                            {
                                clist = clist.Where(x => x.OneUserId == UserId || x.TwoUserId == UserId || x.ThreeUserId == UserId).ToList();
                            }
                        }
                        if (item.Type == 1)
                        {
                            //订单数量
                            item.OrderTNum = clist.Select(x => x.OrderId).Distinct().Count();
                        }
                        else if (item.Type == 2)
                        {
                            //订单金额
                            item.Final_Price = clist.Sum(x => x.Final_Price);
                        }
                        else
                        {
                            //商品数量
                            item.Number = clist.Sum(x => x.Number);
                        }
                        //}
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 获取活动详情
        /// </summary>
        /// <param name="activityId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public RB_Goods_Activity_Extend GetGoosdActivityInfo(int activityId, int userId)
        {
            var model = goods_ActivityRepository.GetEntity<RB_Goods_Activity_Extend>(activityId);
            if (model != null)
            {
                string CategoryIds = model.RangeType == 1 ? model.RangeIds : "";
                string GoodsIds = model.RangeType == 2 ? model.RangeIds : "";
                List<RB_Product_Category_Extend> categoryList = new List<RB_Product_Category_Extend>();
                if (!string.IsNullOrEmpty(CategoryIds))
                {
                    categoryList = product_CategoryRepository.GetList(new RB_Product_Category_Extend() { TenantId = model.TenantId, MallBaseId = model.MallBaseId, CategoryIds = CategoryIds });
                }
                List<RB_Goods_Extend> goodsList = new List<RB_Goods_Extend>();
                if (!string.IsNullOrEmpty(GoodsIds))
                {
                    goodsList = goodsRepository.GetSingleList(new RB_Goods_Extend() { TenantId = model.TenantId, MallBaseId = model.MallBaseId, GoodsIds = GoodsIds });
                }

                if (model.RangeType == 1)
                {
                    List<int> RangeIdList = JsonConvert.DeserializeObject<List<int>>("[" + model.RangeIds + "]");
                    model.RangeList = categoryList.Where(x => RangeIdList.Contains(x.Id)).Select(x => new
                    {
                        x.Id,
                        x.Name,
                        Image = ""
                    });
                }
                else
                {
                    List<int> RangeIdList = JsonConvert.DeserializeObject<List<int>>("[" + model.RangeIds + "]");
                    model.RangeList = goodsList.Where(x => RangeIdList.Contains(x.Id)).Select(x => new
                    {
                        x.Id,
                        x.Name,
                        Image = x.CarouselImage != "" && x.CarouselImage != "[]" ? JsonConvert.DeserializeObject<List<string>>(x.CarouselImage)[0] : ""
                    });
                }
                return model;
            }
            else
            {
                return new RB_Goods_Activity_Extend();
            }
        }

        /// <summary>
        /// 新增修改活动
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetGoodsActivityInfo(RB_Goods_Activity_Extend demodel)
        {
            if (demodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods_Activity_Extend.ActivityName),demodel.ActivityName},
                    { nameof(RB_Goods_Activity_Extend.Tier),demodel.Tier},
                    { nameof(RB_Goods_Activity_Extend.Type),demodel.Type},
                    { nameof(RB_Goods_Activity_Extend.OrderNum),demodel.OrderNum},
                    { nameof(RB_Goods_Activity_Extend.OrderMoney),demodel.OrderMoney},
                    { nameof(RB_Goods_Activity_Extend.RangeType),demodel.RangeType},
                    { nameof(RB_Goods_Activity_Extend.RangeIds),demodel.RangeIds},
                    { nameof(RB_Goods_Activity_Extend.Way),demodel.Way},
                    { nameof(RB_Goods_Activity_Extend.CodeLength),demodel.CodeLength},
                    { nameof(RB_Goods_Activity_Extend.PrizeName),demodel.PrizeName},
                    { nameof(RB_Goods_Activity_Extend.PrizeImage),demodel.PrizeImage},
                    { nameof(RB_Goods_Activity_Extend.StartTime),demodel.StartTime},
                    { nameof(RB_Goods_Activity_Extend.EndTime),demodel.EndTime},
                    { nameof(RB_Goods_Activity_Extend.CoverImage),demodel.CoverImage},
                    { nameof(RB_Goods_Activity_Extend.Description),demodel.Description},
                    { nameof(RB_Goods_Activity_Extend.ReceiveTime),demodel.ReceiveTime},
                    { nameof(RB_Goods_Activity_Extend.UpdateDate),demodel.UpdateDate},
                    { nameof(RB_Goods_Activity_Extend.ActiveObject),demodel.ActiveObject},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName =nameof(RB_Goods_Activity_Extend.Id),
                          FiledValue=demodel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                return goods_ActivityRepository.Update(keyValues, wheres);
            }
            else {
                return goods_ActivityRepository.Insert(demodel) > 0;
            }
        }

        /// <summary>
        /// 获取活动中奖人员分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Goods_Activity_Get_Extend> GetGoodsActivityGetUserPageList(int pageIndex, int pageSize, out long count, RB_Goods_Activity_Get_Extend demodel)
        {
            var list = goods_Activity_GetRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any()) {
                string OrderIds = string.Join(",", list.Select(x => x.OrderIds));
                var orderList = goods_OrderRepository.GetOrderList(new RB_Goods_Order_Extend() { OrderIds = OrderIds });
                foreach (var item in list) {
                    List<int> OrderIdList = JsonConvert.DeserializeObject<List<int>>("[" + item.OrderIds + "]");
                    item.OrderList = orderList.Where(x => OrderIdList.Contains(x.OrderId)).Select(x => new
                    {
                        x.OrderId,
                        x.OrderNo
                    });
                    if (item.State == 1 && item.ReceiveTime < DateTime.Now)
                    {
                        item.State = 3;//已过期了
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 设置活动状态
        /// </summary>
        /// <param name="activityId"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public string SetGoodsActivityState(int activityId, int type)
        {
            var model = goods_ActivityRepository.GetEntity(activityId);
            if (model == null) { return "活动不存在"; }
            if (model.Status == 1) { return "已删除活动，无法操作"; }

            Dictionary<string, object> keyValues = new Dictionary<string, object>() { };
            if (type == 1)
            {
                keyValues.Add(nameof(RB_Goods_Activity_Extend.Enable), 1);
            }
            else if (type == 2)
            {
                keyValues.Add(nameof(RB_Goods_Activity_Extend.Enable), 2);
            }
            else {
                keyValues.Add(nameof(RB_Goods_Activity_Extend.Status), 1);
            }
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName =nameof(RB_Goods_Activity_Extend.Id),
                        FiledValue=activityId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = goods_ActivityRepository.Update(keyValues, wheres);
            return flag ? "" : "出错了，请联系管理员";
        }

        /// <summary>
        /// 设置中奖状态
        /// </summary>
        /// <param name="prizeId"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public string SetGoodsActivityUserState(int prizeId, int type)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() { };
            if (type == 1)
            {
                keyValues.Add(nameof(RB_Goods_Activity_Get_Extend.State), 2);
            }
            else 
            {
                keyValues.Add(nameof(RB_Goods_Activity_Get_Extend.State), 3);
            }
            
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName =nameof(RB_Goods_Activity_Get_Extend.Id),
                        FiledValue=prizeId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = goods_Activity_GetRepository.Update(keyValues, wheres);
            return flag ? "" : "出错了，请联系管理员";
        }

        /// <summary>
        /// 获取得的奖品信息
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Goods_Activity_Get_Extend> GetGoodsMyActivityPrizeList(int pageIndex, int pageSize, out long count, RB_Goods_Activity_Get_Extend demodel)
        {
            var list = goods_Activity_GetRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            foreach (var item in list) {
                if (item.State == 1 && item.ReceiveTime < DateTime.Now) {
                    item.State = 3;//已过期了
                }
            }
            return list;
        }
    }
}
