using Mall.Common;
using Mall.Common.Plugin;
using Mall.Model.Extend.TradePavilion;
using Mall.Repository.TradePavilion;
using Mall.Repository.User;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VT.FW.DB;

namespace Mall.Module.TradePavilion
{
    /// <summary>
    /// 榜单处理类
    /// </summary>
    public class FirstShopListModule
    {
        /// <summary>
        /// 榜单
        /// </summary>
        private readonly RB_FirstShop_ListRepository firstShop_ListRepository = new RB_FirstShop_ListRepository();
        /// <summary>
        /// 报名
        /// </summary>
        private readonly RB_FirstShop_ListEnrollRepository firstShop_ListEnrollRepository = new RB_FirstShop_ListEnrollRepository();
        /// <summary>
        /// 品牌
        /// </summary>
        private readonly RB_BrandRepository brandRepository = new RB_BrandRepository();
        /// <summary>
        /// 载体
        /// </summary>
        private readonly RB_CarrierRepository carrierRepository = new RB_CarrierRepository();
        /// <summary>
        /// 用户
        /// </summary>
        private readonly RB_Member_UserRepository member_UserRepository = new RB_Member_UserRepository();

        /// <summary>
        /// 获取榜单分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_FirstShop_List_Extend> GetFirstShopListPageList(int pageIndex, int pageSize, out long rowsCount, RB_FirstShop_List_Extend query)
        {
            var list = firstShop_ListRepository.GetPageList(pageIndex, pageSize, out rowsCount, query);
            if (list.Any()) {
                foreach (var item in list) {

                    if (item.ListState == Common.Enum.TradePavilion.ListStateEnum.Enroll && item.EndDate <= DateTime.Now)
                    {
                        item.ListState = Common.Enum.TradePavilion.ListStateEnum.Rating;
                    }
                    item.ObjectTypeList = new List<string>();
                    if (!string.IsNullOrEmpty(item.ObjectTypeIds)) {
                        List<int> OIdList = JsonHelper.DeserializeObject<List<int>>("[" + item.ObjectTypeIds + "]");
                        foreach (var qitem in OIdList)
                        {
                            item.ObjectTypeList.Add(((Common.Enum.TradePavilion.ListObjectTypeEnum)qitem).GetEnumName());
                        }
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 获取小程序 - 榜单分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_FirstShop_List_Extend> GetAppletFirstShopListPageList(int pageIndex, int pageSize, out long rowsCount, RB_FirstShop_List_Extend query)
        {
            var list = firstShop_ListRepository.GetPageList(pageIndex, pageSize, out rowsCount, query);
            if (list.Any())
            {
                foreach (var item in list)
                {
                    if (item.ListState == Common.Enum.TradePavilion.ListStateEnum.Enroll && item.StartDate <= DateTime.Now && item.EndDate >= DateTime.Now)
                    {
                        item.State = 1;//进行中
                    }
                    else if (item.ListState == Common.Enum.TradePavilion.ListStateEnum.Enroll && item.EndDate <= DateTime.Now)
                    {
                        item.State = 2;//报名已截止
                    }
                    else if (item.ListState == Common.Enum.TradePavilion.ListStateEnum.Confirmed)
                    {
                        item.State = 3;//已放榜
                    }

                    item.ObjectTypeList = new List<string>();
                    if (!string.IsNullOrEmpty(item.ObjectTypeIds))
                    {
                        List<int> OIdList = JsonHelper.DeserializeObject<List<int>>("[" + item.ObjectTypeIds + "]");
                        foreach (var qitem in OIdList)
                        {
                            item.ObjectTypeList.Add(((Common.Enum.TradePavilion.ListObjectTypeEnum)qitem).GetEnumName());
                        }
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 获取榜单详情
        /// </summary>
        /// <param name="wishId"></param>
        /// <returns></returns>
        public RB_FirstShop_List_Extend GetFirstShopListInfo(int listId)
        {
            return firstShop_ListRepository.GetEntity<RB_FirstShop_List_Extend>(listId);
        }

        /// <summary>
        /// 小程序获取榜单详情
        /// </summary>
        /// <param name="listId"></param>
        /// <returns></returns>
        public RB_FirstShop_List_Extend GetAppletFirstShopListInfo(int listId, Common.AppletUserInfo userInfo)
        {
            var model = firstShop_ListRepository.GetEntity<RB_FirstShop_List_Extend>(listId);
            if (model != null) {
                if (model.ListState == Common.Enum.TradePavilion.ListStateEnum.Confirmed)
                {
                    //已放榜  查询所有上榜的列表
                    var enrollList = firstShop_ListEnrollRepository.GetList(new RB_FirstShop_ListEnroll_Extend() { MallBaseId = userInfo.MallBaseId, ListId = listId, RankListState = 1 });
                    //查询 品牌/载体  名称 图片
                    if (enrollList.Any()) {
                        var e1list = enrollList.Where(x => x.ObjectType == Common.Enum.TradePavilion.ListObjectTypeEnum.Brand).ToList();
                        var e2list = enrollList.Where(x => x.ObjectType == Common.Enum.TradePavilion.ListObjectTypeEnum.Carrier).ToList();
                        if (e1list.Any()) {
                            //查询品牌
                            string bids = string.Join(",", e1list.Select(x => x.ObjectId));
                            var blist = brandRepository.GetBrandList(new RB_Brand_Extend() { MallBaseId = userInfo.MallBaseId, BrandIds = bids });
                            foreach (var item in e1list) {
                                var bmodel = blist.Where(x => x.ID == item.ObjectId).FirstOrDefault();
                                item.ObjectName = bmodel?.BrandName ?? "";
                                item.ObjectIcon = bmodel?.Logo ?? "";
                            }
                        }
                        if (e2list.Any()) {
                            //查询载体
                            string cids = string.Join(",", e2list.Select(x => x.ObjectId));
                            var clist = carrierRepository.GetCarrierList(new RB_Carrier_Extend() { MallBaseId = userInfo.MallBaseId, CarrierIds = cids });
                            foreach (var item in e2list) {
                                var cmodel = clist.Where(x => x.ID == item.ObjectId).FirstOrDefault();
                                item.ObjectName = cmodel?.CarrierName ?? "";
                                item.ObjectIcon = cmodel?.Logo ?? "";
                            }
                        }
                    }
                    model.RankList = enrollList;
                }
                else {
                    //查询个人报名记录
                    var enrollList = firstShop_ListEnrollRepository.GetList(new RB_FirstShop_ListEnroll_Extend() { MallBaseId = userInfo.MallBaseId, ListId = listId, UserId = userInfo.UserId });
                    //查询 品牌/载体  名称 图片
                    if (enrollList.Any())
                    {
                        var e1list = enrollList.Where(x => x.ObjectType == Common.Enum.TradePavilion.ListObjectTypeEnum.Brand).ToList();
                        var e2list = enrollList.Where(x => x.ObjectType == Common.Enum.TradePavilion.ListObjectTypeEnum.Carrier).ToList();
                        if (e1list.Any())
                        {
                            //查询品牌
                            string bids = string.Join(",", e1list.Select(x => x.ObjectId));
                            var blist = brandRepository.GetBrandList(new RB_Brand_Extend() { MallBaseId = userInfo.MallBaseId, BrandIds = bids });
                            foreach (var item in e1list)
                            {
                                var bmodel = blist.Where(x => x.ID == item.ObjectId).FirstOrDefault();
                                item.ObjectName = bmodel?.BrandName ?? "";
                                item.ObjectIcon = bmodel?.Logo ?? "";
                            }
                        }
                        if (e2list.Any())
                        {
                            //查询载体
                            string cids = string.Join(",", e2list.Select(x => x.ObjectId));
                            var clist = carrierRepository.GetCarrierList(new RB_Carrier_Extend() { MallBaseId = userInfo.MallBaseId, CarrierIds = cids });
                            foreach (var item in e2list)
                            {
                                var cmodel = clist.Where(x => x.ID == item.ObjectId).FirstOrDefault();
                                item.ObjectName = cmodel?.CarrierName ?? "";
                                item.ObjectIcon = cmodel?.Logo ?? "";
                            }
                        }
                    }
                    model.EnrollList = enrollList;
                }
            }
            return model;
        }

        /// <summary>
        /// 新增修改榜单
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public string SetFirstShopListInfo(RB_FirstShop_List_Extend demodel)
        {
            if (demodel.Id > 0)
            {
                var oldModel = firstShop_ListRepository.GetEntity(demodel.Id);
                if (oldModel == null || oldModel.Status == 1 || oldModel.ListState == Common.Enum.TradePavilion.ListStateEnum.Cancel || oldModel.ListState == Common.Enum.TradePavilion.ListStateEnum.Confirmed) {
                    return "绑单状态不正确";
                }

                //修改
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_FirstShop_List_Extend.ListType),demodel.ListType },
                    { nameof(RB_FirstShop_List_Extend.ObjectTypeIds),demodel.ObjectTypeIds },
                    { nameof(RB_FirstShop_List_Extend.Sponsor),demodel.Sponsor },
                    { nameof(RB_FirstShop_List_Extend.ListName),demodel.ListName },
                    { nameof(RB_FirstShop_List_Extend.CoverImage),demodel.CoverImage },
                    { nameof(RB_FirstShop_List_Extend.FinishDate),demodel.FinishDate },
                    { nameof(RB_FirstShop_List_Extend.StartDate),demodel.StartDate },
                    { nameof(RB_FirstShop_List_Extend.EndDate),demodel.EndDate },
                    { nameof(RB_FirstShop_List_Extend.Content),demodel.Content },
                    { nameof(RB_FirstShop_List_Extend.EnableRank),demodel.EnableRank },
                    { nameof(RB_FirstShop_List_Extend.PrizeNum),demodel.PrizeNum },
                    { nameof(RB_FirstShop_List_Extend.UpdateBy),demodel.UpdateBy },
                    { nameof(RB_FirstShop_List_Extend.UpdateDate),demodel.UpdateDate }
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_FirstShop_List_Extend.Id),
                          FiledValue=demodel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = firstShop_ListRepository.Update(keyValues, wheres);
                return flag ? "" : "修改失败,请联系管理员";
            }
            else {
                //新增
                bool flag = firstShop_ListRepository.Insert(demodel) > 0;
                return flag ? "" : "新增失败，请联系管理员";
            }
        }

        /// <summary>
        /// 取消榜单
        /// </summary>
        /// <param name="listId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public string DelFirstShopListInfo(int listId, int mallBaseId)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_FirstShop_List_Extend.ListState), Common.Enum.TradePavilion.ListStateEnum.Cancel}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_FirstShop_List_Extend.Id),
                      FiledValue=listId,
                       OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                     FiledName= nameof(RB_FirstShop_List_Extend.MallBaseId),
                      FiledValue= mallBaseId,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = firstShop_ListRepository.Update(keyValues, wheres);
            return flag ? "" : "取消失败";
        }

        /// <summary>
        /// 获取用户可报表的品牌/载体列表
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public object GetAppletMyBrandCarrierList(int listId, int enrollId, AppletUserInfo userInfo)
        {
            List<object> RList = new List<object>();
            //查询该榜单  
            var listModel = firstShop_ListRepository.GetEntity(listId);
            if (listModel == null) { return null; }
            var enrollList = firstShop_ListEnrollRepository.GetList(new RB_FirstShop_ListEnroll_Extend() { MallBaseId = userInfo.MallBaseId, ListId = listId, UserId = userInfo.UserId });
            if (enrollId > 0) { enrollList = enrollList.Where(x => x.Id != enrollId).ToList(); }//排除当前修改的
            //查询用户下所有的品牌
            if (listModel.ObjectTypeIds.Contains("1")) {
                //品牌
                var blist = brandRepository.GetBrandList(new RB_Brand_Extend() { MallBaseId = userInfo.MallBaseId, UserId = userInfo.UserId });
                blist = blist.Where(x => !enrollList.Where(x => x.ObjectType == Common.Enum.TradePavilion.ListObjectTypeEnum.Brand).Select(y => y.ObjectId).Contains(x.ID)).ToList();
                if (blist.Any())
                {
                    foreach (var item in blist)
                    {
                        RList.Add(new
                        {
                            Id = item.ID,
                            Name = item.BrandName,
                            ObjectType = 1
                        });
                    }
                }
            }
            //查询用户下所有的载体
            if (listModel.ObjectTypeIds.Contains("2"))
            {
                var clist = carrierRepository.GetCarrierList(new RB_Carrier_Extend() { MallBaseId = userInfo.MallBaseId, UserId = userInfo.UserId });
                clist = clist.Where(x => !enrollList.Where(x => x.ObjectType == Common.Enum.TradePavilion.ListObjectTypeEnum.Carrier).Select(y => y.ObjectId).Contains(x.ID)).ToList();
                if (clist.Any())
                {
                    foreach (var item in clist)
                    {
                        RList.Add(new
                        {
                            Id = item.ID,
                            Name = item.CarrierName,
                            ObjectType = 2
                        });
                    }
                }
            }

            return RList;
        }

        /// <summary>
        /// 新增修改报名
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public string SetAppletFirstShopListInfo(RB_FirstShop_ListEnroll_Extend demodel)
        {
            var listModel = firstShop_ListRepository.GetEntity(demodel.ListId);
            if (listModel == null || listModel.Status == 1 || listModel.ListState == Common.Enum.TradePavilion.ListStateEnum.Cancel) {
                return "榜单不存在，请核实后再试";
            }
            if (listModel.StartDate > DateTime.Now) { return "榜单还未开始报名，无法报名"; }
            if (listModel.EndDate < DateTime.Now) { return "榜单已截止报名"; }

            if (demodel.Id > 0)
            {
                #region 验证
                var valistList = firstShop_ListEnrollRepository.GetList(new RB_FirstShop_ListEnroll_Extend() { MallBaseId = demodel.MallBaseId, UserId = demodel.UserId, ObjectType = demodel.ObjectType, ObjectId = demodel.ObjectId });
                if (valistList.Where(x => x.Id != demodel.Id).Any())
                {
                    return "该品牌/载体已报名，无法重复报名";
                }
                #endregion
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_FirstShop_ListEnroll_Extend.ObjectType),demodel.ObjectType},
                    { nameof(RB_FirstShop_ListEnroll_Extend.ObjectId),demodel.ObjectId},
                    { nameof(RB_FirstShop_ListEnroll_Extend.Content),demodel.Content},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_FirstShop_ListEnroll_Extend.Id),
                          FiledValue= demodel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = firstShop_ListEnrollRepository.Update(keyValues, wheres);
                return flag ? "" : "修改失败，请联系管理人员";
            }
            else {
                #region 验证
                var valistList = firstShop_ListEnrollRepository.GetList(new RB_FirstShop_ListEnroll_Extend() { MallBaseId = demodel.MallBaseId, UserId = demodel.UserId, ObjectType = demodel.ObjectType, ObjectId = demodel.ObjectId });
                if (valistList.Any()) {
                    return "该品牌/载体已报名，无法重复报名";
                }
                #endregion
                bool flag = firstShop_ListEnrollRepository.Insert(demodel) > 0;
                return flag ? "" : "报名失败，请联系管理人员";
            }
        }

        /// <summary>
        /// 取消报名
        /// </summary>
        /// <param name="enrollId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string CancelAppletFirstShopListInfo(int enrollId, AppletUserInfo userInfo)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_FirstShop_ListEnroll_Extend.Status),1},
                { nameof(RB_FirstShop_ListEnroll_Extend.UpdateDate),DateTime.Now},
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_FirstShop_ListEnroll_Extend.Id),
                        FiledValue= enrollId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = firstShop_ListEnrollRepository.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_FirstShop_List_Extend> GetAppletMyEnrollFistShopListPageList(int pageIndex, int pageSize, out long count, RB_FirstShop_List_Extend demodel)
        {
            var list = firstShop_ListRepository.GetAppletMyEnrollFistShopListPageList(pageIndex, pageSize, out count, demodel);
            return list;
        }
    }
}
