using System;
using System.Collections.Generic;
using System.Linq;
using Dnc.Api.Throttle;
using Mall.AOP;
using Mall.Common.API;
using Mall.Common.Plugin;
using Mall.Model.Entity.User;
using Mall.Model.Extend.Product;
using Mall.Model.Extend.Reserve;
using Mall.Module.Product;
using Mall.Module.Reserve;
using Mall.Module.User;
using Mall.WebApi.Filter;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Mall.WebApi.Controllers.Reserve
{
    /// <summary>
    /// 小程序门店商品
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class AppletStoresController : BaseController
    {
        /// <summary>
        /// 门店处理类对象
        /// </summary>
        private readonly ContentModule contentModule = AOPHelper.CreateAOPObject<ContentModule>();


        private readonly ReserveModule reserveModule = new ReserveModule();

        /// <summary>
        /// 线下服务商品处理类对象
        /// </summary>
        private readonly OfflineGoodsModule offlineGoodsModule = AOPHelper.CreateAOPObject<OfflineGoodsModule>();

        private readonly Module.User.UserModule UserModule = new Module.User.UserModule();

        private readonly OrderModule orderModule = new OrderModule();

        /// <summary>
        /// 线下服务首页获取当前距离最近门店
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
                [AllowAnonymous] [RateValve(Policy = Policy.Ip, Limit = 10, Duration = 60)]
        public virtual ApiResult GetCurrentStore(object requestMsg)
        {
            var userInfo = AppletUserInfo;
            var parms = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            if (parms.MallBaseId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            JObject parm = JObject.Parse(parms.msg.ToString());
            var position = parm.GetStringValue("position");
            int storeId = parm.GetInt("storeId");
            var storeModel = contentModule.GetStoresListModule(new RB_Stores_Extend()
            {
                CurrentPosition = position,
                Id = storeId,
                MallBaseId = parms.MallBaseId,
                OrderByType = 3
            }, isFirst: true)?.FirstOrDefault();
            var consumptionObj = new object();
            if (userInfo != null && userInfo.UserId > 0)
            {
                var orderModel = orderModule.GetOfflineServiceOrderPageListModule(1, 1, out long rowsCount, new RB_Goods_Order_Extend()
                {
                    UserId = userInfo.UserId,
                    IsNotSelectCancel = 1,
                })?.FirstOrDefault();
                if (orderModel != null && orderModel.StoresId > 0)
                {
                    var useStoreModel = contentModule.GetStoresModule(orderModel.StoresId);
                    consumptionObj = new
                    {
                        consumptionStoreId = useStoreModel?.Id,
                        consumptionStoreName = useStoreModel?.Name
                    };
                }
            }
            object result = new
            {
                storeInfo = new
                {
                    storeId = storeModel?.Id,
                    storeName = storeModel?.Name,
                    storeAddress = storeModel?.Address,
                    storeTel = storeModel?.Tel,
                    distance = storeModel?.KM,
                    storeCoverImg = storeModel?.CoverImg,
                    storeNavImg = storeModel?.NavImg,
                    consumptionObj
                },
            };
            return ApiResult.Success(data: result);
        }


        /// <summary>
        /// 小程序获取门店分页列表
        /// </summary>
        /// <param name="requestMsg"></param>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
                [AllowAnonymous] [RateValve(Policy = Policy.Ip, Limit = 10, Duration = 60)]
        public virtual ApiResult GetStorePage(object requestMsg)
        {
            var parms = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            if (parms.MallBaseId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            ResultPageModel pageModel = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            var query = JsonConvert.DeserializeObject<RB_Stores_Extend>(parms.msg.ToString());
            query.TenantId = parms.TenantId;
            query.MallBaseId = parms.MallBaseId;
            var list = contentModule.GetStoresPageListModule(pageModel.pageIndex, pageModel.pageSize, out long rowsCount, query);
            pageModel.pageData = list;
            pageModel.count = Convert.ToInt32(rowsCount);
            return ApiResult.Success(data: pageModel);
        }

        /// <summary>
        /// 获取门店详情
        /// </summary>
        /// <param name="requestMsg"></param>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
                [AllowAnonymous] [RateValve(Policy = Policy.Ip, Limit = 10, Duration = 60)]
        public virtual ApiResult GetStoreInfo(object requestMsg)
        {
            var userInfo = AppletUserInfo;
            var parms = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            if (parms.MallBaseId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            JObject parm = JObject.Parse(parms.msg.ToString());
            int storeId = parm.GetInt("storeId");
            var position = parm.GetStringValue("position");
            var storeModel = contentModule.GetStoresListModule(new RB_Stores_Extend()
            {
                Id = storeId,
                MallBaseId = parms.MallBaseId,
                CurrentPosition = position
            }, isFirst: true)?.FirstOrDefault();
            string serviceTime = "";
            if (storeModel != null)
            {
                if (storeModel.IsAllDay == 1)
                {
                    serviceTime = "全天";
                }
                else
                {
                    serviceTime = storeModel.StartTime + "-" + storeModel.EndTime;
                }
            }
            var consumptionObj = new object();
            if (userInfo != null && userInfo.UserId > 0)
            {
                var orderModel = orderModule.GetOfflineServiceOrderPageListModule(1, 1, out long rowsCount, new RB_Goods_Order_Extend()
                {
                    UserId = userInfo.UserId,
                    IsNotSelectCancel = 1,
                })?.FirstOrDefault();
                if (orderModel != null && orderModel.StoresId > 0)
                {
                    var useStoreModel = contentModule.GetStoresModule(orderModel.StoresId);
                    consumptionObj = new
                    {
                        consumptionStoreId = useStoreModel?.Id,
                        consumptionStoreName = useStoreModel?.Name
                    };
                }
            }
            //查看门店是否有商品信息
            long totalNum = 0;
            RB_Goods_Extend goodsModel = new RB_Goods_Extend();
            goodsModel.TeacherId = parms.TenantId;
            goodsModel.MallBaseId = parms.MallBaseId;
            goodsModel.GoodsStatus = 1;
            goodsModel.GoodsClassify = 3;
            goodsModel.StoresIds = (storeModel?.Id??0).ToString();
            var goodsList = offlineGoodsModule.GetServicePersonalGoodsList(1, 1, out totalNum, goodsModel, 3);
            object result = new
            {
                storeInfo = new
                {
                    storeId = storeModel?.Id,
                    storeName = storeModel?.Name,
                    storeAddress = storeModel?.Address,
                    storeTel = storeModel?.Tel,
                    distance = storeModel?.KM,
                    storeScore = storeModel?.Score,
                    storeCoverImg = storeModel?.CoverImg,
                    storeNavImg = storeModel?.NavImg,
                    storeIntro = storeModel?.Intro,
                    storeProject = storeModel?.ServiceProject,
                    storeServiceTime = serviceTime,
                    consumptionObj,
                    IsHaveGoods = totalNum,
                },
            };
            return ApiResult.Success(data: result);
        }

        #region 获取设计师与套餐卡


        #region 设计师
        /// <summary>
        /// 获取服务人员列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
                [AllowAnonymous] [RateValve(Policy = Policy.Ip, Limit = 10, Duration = 60)]
        public ApiResult GetServicePersonalList(object requestMsg)
        {
            var parms = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Reserve_ServicePersonal_Extend demodel = JsonConvert.DeserializeObject<RB_Reserve_ServicePersonal_Extend>(parms.msg.ToString());
            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            demodel.ServiceStatus = 1;
            var list = reserveModule.GetMinServicePersonalList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.ID,
                x.ServiceLogo,
                x.Name,
                Score = x.Score == 0 ? "5" : x.Score.ToString(),
                x.OrderNum,
                CreateDateStr = x.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                x.ServiceStatus,
                x.Telephone,
                x.Major,
                x.WorkYears,
                x.Gender,
                ServiceTypeStr = x.ServiceType.GetEnumName(),
                x.ServiceType,
                x.FictitiousReserveNum,
                x.CommentNum
            });
            return ApiResult.Success("", pagelist);
        }


        [HttpPost]
                [AllowAnonymous] [RateValve(Policy = Policy.Ip, Limit = 10, Duration = 60)]
        public ApiResult GetServicePersonalDetailList(object requestMsg)
        {
            var parms = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Reserve_ServicePersonal_Extend demodel = JsonConvert.DeserializeObject<RB_Reserve_ServicePersonal_Extend>(parms.msg.ToString());
            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            demodel.ServiceStatus = 1;
            var list = reserveModule.GetServicePersonalDetailList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.ID,
                x.ServiceLogo,
                x.Name,
                Score = x.Score == 0 ? "5" : x.Score.ToString(),
                x.OrderNum,
                CreateDateStr = x.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                x.ServiceStatus,
                x.Telephone,
                x.Major,
                x.WorkYears,
                x.Gender,
                ServiceTypeStr = x.ServiceType.GetEnumName(),
                x.ServiceType,
                x.FictitiousReserveNum,
                x.CommentNum
            });
            return ApiResult.Success("", pagelist);
        }


        /// <summary>
        /// 获取详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
                [AllowAnonymous] [RateValve(Policy = Policy.Ip, Limit = 10, Duration = 60)]
        public ApiResult GetServicePersonalModel(object requestMsg)
        {
            var parms = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            var query = JsonConvert.DeserializeObject<RB_Reserve_ServicePersonal_Extend>(parms.msg.ToString());
            query.TenantId = parms.TenantId;
            query.MallBaseId = parms.MallBaseId;
            query.ServiceStatus = -1;
            var oldLogisticsModel = reserveModule.GetServicePersonalList(query).FirstOrDefault();
            List<RB_Goods_Extend> goodsList = new List<RB_Goods_Extend>();
            if (oldLogisticsModel == null)
            {
                return ApiResult.Failed("信息不存在");
            }
            else
            {

                //获取服务人员的商品top3
                long totalNum = 0;
                RB_Goods_Extend goodsModel = new RB_Goods_Extend();
                goodsModel.TeacherId = parms.TenantId;
                goodsModel.MallBaseId = parms.MallBaseId;
                goodsModel.GoodsStatus = 1;
                goodsModel.GoodsClassify = 3;
                goodsModel.StoresIds = oldLogisticsModel.StoreId.ToString();
                if (oldLogisticsModel.ServiceType != Common.Enum.Reserve.ServiceTypeEnum.All)
                {
                    string ids = string.Join(",", oldLogisticsModel.ProductList.Select(x => x.ProductId));
                    if (!string.IsNullOrWhiteSpace(ids))
                    {
                        if (oldLogisticsModel.ServiceType == Common.Enum.Reserve.ServiceTypeEnum.Category)
                        {
                            goodsModel.CategoryIds = ids;
                        }
                        else if (oldLogisticsModel.ServiceType == Common.Enum.Reserve.ServiceTypeEnum.Product)
                        {
                            goodsModel.GoodsIds = ids;
                        }
                    }
                }
                goodsList = offlineGoodsModule.GetServicePersonalGoodsList(1, 3, out totalNum, goodsModel, 3);
            }
            if (!string.IsNullOrWhiteSpace(oldLogisticsModel.LableName))
            {
                oldLogisticsModel.LableNameList = JsonConvert.DeserializeObject<List<string>>(oldLogisticsModel.LableName);
            }
            var result = new
            {
                oldLogisticsModel.ID,
                oldLogisticsModel.Name,
                oldLogisticsModel.ServiceLogo,
                oldLogisticsModel.Score,
                oldLogisticsModel.WorkYears,
                oldLogisticsModel.Introduction,
                oldLogisticsModel.Gender,
                oldLogisticsModel.OrderNum,
                oldLogisticsModel.FictitiousReserveNum,
                oldLogisticsModel.Major,
                oldLogisticsModel.Telephone,
                oldLogisticsModel.LableNameList,
                oldLogisticsModel.StoreAddress,
                oldLogisticsModel.StoreName,
                goodsList = goodsList.Select(x => new { x.Name, x.SellingPrice, x.DepositMoney, x.CoverImage, x.SubName, x.GoodsBuyNum, x.Id })
            };



            return ApiResult.Success("", result);
        }
        #endregion


        #region 套餐卡

        /// <summary>
        /// 套餐卡领劵中心
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAllCouponPageList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            RB_Reserve_Coupon_Extend demodel = JsonConvert.DeserializeObject<RB_Reserve_Coupon_Extend>(req.msg.ToString());
            demodel.UserId = userInfo.UserId;
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.SmallShopId = userInfo.UserSmallShopId;
            var list = reserveModule.GetAllCouponList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Name,
                x.Describe,
                x.TotalNum,
                x.MemberNum,
                x.CouponIco,
                CouponId = x.ID,
                x.IndateDay,
                x.MaxDiscountsPrice,
                x.IndateType,
                StartDate = x.StartDate.HasValue ? x.StartDate.Value.ToString("yyyy-MM-dd HH:ss:mm") : "",
                EndDate = x.EndDate.HasValue ? x.EndDate.Value.ToString("yyyy-MM-dd HH:ss:mm") : "",
                IsReceive = x.MemberNum > 0 ? 1 : 0,
                UseTypeStr = ((int)x.UseType == 3 || (int)x.UseType == 4) ? x.UseType.GetEnumName() : (x.ProductList != null && x.ProductList.Any() ? string.Join("、", x.ProductList.Select(x => x.Relevance)) : ""),
                x.UseType,
                x.ProductList,
                x.HeXiao
            });
            return ApiResult.Success("", pagelist);
        }



        /// <summary>
        /// 获取套餐卡详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]

        public ApiResult GetReserveCouponDetail()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            var query = JsonConvert.DeserializeObject<RB_Reserve_Coupon_Extend>(req.msg.ToString());
            query.TenantId = userInfo.TenantId;
            query.MallBaseId = userInfo.MallBaseId;
            var oldLogisticsModel = reserveModule.GetDiscountCouponList(query).FirstOrDefault();
            if (oldLogisticsModel == null)
            {
                return ApiResult.Failed("套餐卡信息不存在");
            }
            else
            {
                oldLogisticsModel.StoresList = new List<RB_Stores_Extend>();

                //查询所属门店
                if (string.IsNullOrWhiteSpace(oldLogisticsModel.StoreIds) || oldLogisticsModel.StoreIds == "0")
                {
                    oldLogisticsModel.StoresList = contentModule.GetStoresListModule(new RB_Stores_Extend()
                    {
                        MallBaseId = userInfo.MallBaseId,
                        TenantId = userInfo.TenantId
                    });

                }
                else
                {
                    oldLogisticsModel.StoresList = contentModule.GetStoresListModule(new RB_Stores_Extend()
                    {
                        MallBaseId = userInfo.MallBaseId,
                        TenantId = userInfo.TenantId,
                        QIds = oldLogisticsModel.StoreIds
                    });
                }
                //判断当前人是否领取了改优惠券
                //判断套餐卡是否已领取
                var receiveList = reserveModule.GetMemberDiscountCouponList(new RB_Reserve_MemberCoupon_Extend
                {
                    CouponId = oldLogisticsModel.ID,
                    MallBaseId = userInfo.MallBaseId,
                    TenantId = userInfo.TenantId,
                    UserId = userInfo.UserId
                });
                if (receiveList != null && receiveList.Any())
                {
                    oldLogisticsModel.MemberNum = receiveList.Count();
                }
            }
            return ApiResult.Success("", oldLogisticsModel);
        }


        /// <summary>
        /// 领取套餐卡
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GrantCoupon()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            var query = JsonConvert.DeserializeObject<RB_Reserve_MemberCoupon_Extend>(RequestParm.msg.ToString());
            query.TenantId = userInfo.TenantId;
            query.MallBaseId = userInfo.MallBaseId;
            query.UserId = userInfo.UserId;
            if (query == null)
            {
                return ApiResult.Failed("请传入套餐卡信息");
            }
            else
            {
                var oldLogisticsModel = reserveModule.GetDiscountCouponList(new RB_Reserve_Coupon_Extend { StoreId = query.StoreId, TenantId = query.TenantId, MallBaseId = query.MallBaseId, ID = query.CouponId }).FirstOrDefault();
                var allMemberInfo = UserModule.GetMemberUserInfo(userInfo.UserId);

                if (oldLogisticsModel == null || oldLogisticsModel.ID == 0)
                {
                    return ApiResult.Failed("套餐卡信息不存在，请核实后再操作");
                }
                //if (oldLogisticsModel.StoreId > 0 && oldLogisticsModel.StoreId != query.StoreId)
                //{
                //    return ApiResult.Failed("领取套餐卡不属于当前门店");
                //}

                if (!string.IsNullOrWhiteSpace(oldLogisticsModel.StoreIds))
                {
                    if (oldLogisticsModel.StoreIds != "0")
                    {
                        bool isGrantCoupon = false;
                        foreach (var item in oldLogisticsModel.StoreIds.Split(","))
                        {
                            if (Convert.ToInt32(item) > 0)
                            {
                                if (Convert.ToInt32(item) == query.StoreId)
                                {
                                    isGrantCoupon = true;
                                }
                            }
                        }
                        if (!isGrantCoupon)
                        {
                            return ApiResult.Failed("领取套餐卡不属于当前门店");
                        }
                    }
                }
                if (oldLogisticsModel.TotalNum != -1)//判断套餐卡剩余数量是够足够
                {
                    if (oldLogisticsModel.TotalNum < 1)
                    {
                        return ApiResult.Failed("套餐卡已领完");
                    }
                }
                //判断套餐卡是否已领取
                var receiveList = reserveModule.GetMemberDiscountCouponList(query);
                if (receiveList != null && receiveList.Any())
                {
                    return ApiResult.Failed("您已领取套餐卡");
                }

                if (oldLogisticsModel.IndateType == Common.Enum.MarketingCenter.IndateTypeEnum.TimeHorizon)
                {
                    if (oldLogisticsModel.EndDate.Value < System.DateTime.Now)
                    {
                        return ApiResult.Failed("套餐卡时间已过期");
                    }
                }


                RB_Reserve_MemberCoupon_Extend memberCoupon = new RB_Reserve_MemberCoupon_Extend();
                memberCoupon.Id = 0;
                memberCoupon.UserId = userInfo.UserId;
                memberCoupon.Description = oldLogisticsModel.Describe;
                memberCoupon.CreateDate = System.DateTime.Now;
                memberCoupon.TenantId = userInfo.TenantId;
                memberCoupon.MallBaseId = userInfo.MallBaseId;
                memberCoupon.Remarks = "";
                memberCoupon.CouponId = oldLogisticsModel.ID;
                memberCoupon.Name = oldLogisticsModel.Name;
                memberCoupon.HeXiao = oldLogisticsModel.HeXiao;
                memberCoupon.UseHeXiao = 0;
                memberCoupon.UseType = oldLogisticsModel.UseType;
                if (oldLogisticsModel.IndateType == Common.Enum.MarketingCenter.IndateTypeEnum.DayHorizon)
                {
                    memberCoupon.StartDate = System.DateTime.Now;
                    LogHelper.WriteInfo(userInfo.Name + "套餐卡领取时间:" + memberCoupon.StartDate);
                    memberCoupon.EndDate = memberCoupon.StartDate.Value.AddDays(oldLogisticsModel.IndateDay);
                }
                else
                {
                    memberCoupon.StartDate = oldLogisticsModel.StartDate;
                    memberCoupon.EndDate = oldLogisticsModel.EndDate;
                }
                var memberList = new List<RB_Reserve_MemberCoupon_Extend>();
                memberList.Add(memberCoupon);
                bool result = reserveModule.GrantCoupon(memberList, oldLogisticsModel);
                if (result)
                {
                    return ApiResult.Success("套餐卡信息领取成功");
                }
                else
                {
                    return ApiResult.Failed("套餐卡信息领取成功");
                }
            }
        }


        /// <summary>
        /// 我的套餐卡
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMemberCouponPageList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            RB_Reserve_Coupon_Extend demodel = JsonConvert.DeserializeObject<RB_Reserve_Coupon_Extend>(req.msg.ToString());
            demodel.UserId = userInfo.UserId;
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            var list = reserveModule.GetMemberDisCouponList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Name,
                x.Describe,
                x.UseHeXiao,
                x.HeXiao,
                x.ID,
                x.MaxDiscountsPrice,
                x.CouponIco,
                x.MemberCouponId,
                StartDate = x.StartDate.HasValue ? x.StartDate.Value.ToString("yyyy-MM-dd HH:ss:mm") : "",
                EndDate = x.EndDate.HasValue ? x.EndDate.Value.ToString("yyyy-MM-dd HH:ss:mm") : "",
                UseTypeStr = ((int)x.UseType == 3 || (int)x.UseType == 4) ? x.UseType.GetEnumName() : (x.ProductList != null && x.ProductList.Any() ? string.Join("、", x.ProductList.Select(x => x.Relevance)) : ""),
                x.UseType,
                x.ProductList
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 分享领取套餐卡
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult ShareEducationCoupon()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            var query = JsonConvert.DeserializeObject<RB_Reserve_Coupon_Extend>(RequestParm.msg.ToString());
            query.TenantId = userInfo.TenantId;
            query.MallBaseId = userInfo.MallBaseId;
            query.UserId = userInfo.UserId;
            RB_Reserve_Coupon_Extend resultModel = new RB_Reserve_Coupon_Extend();
            if (query.TriggerType == 2)
            {
                query.TriggerType = 4;
                resultModel = reserveModule.AutoEducationCoupon(query);
                if (resultModel == null || resultModel.ID == 0)
                {
                    query.TriggerType = 2;
                    resultModel = reserveModule.AutoEducationCoupon(query);
                }
            }
            else
            {
                resultModel = reserveModule.AutoEducationCoupon(query);
            }
            if (resultModel != null && resultModel.ID > 0)
            {
                return ApiResult.CouponSuccess(ResultCode.Success, 1, "", resultModel.Name);
            }
            else
            {
                return ApiResult.CouponFailed(ResultCode.Fail, 1, "", "");
            }
        }




        /// <summary>
        /// 获取用户未使用的套餐卡
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetNoUseCouponList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject prams = JObject.Parse(req.msg.ToString());
            var query = JsonConvert.DeserializeObject<RB_Reserve_Coupon_Extend>(RequestParm.msg.ToString());

            query.TenantId = userInfo.TenantId;
            query.MallBaseId = userInfo.MallBaseId;
            query.UserId = userInfo.UserId;
            var list = reserveModule.GetNoUseCouponList(query);

            //获取套餐卡对应的商品，或者分类
            List<RB_Product_Category_Extend> categotyList = new List<RB_Product_Category_Extend>();

            List<RB_Reserve_CouponProduct_Extend> productList = new List<RB_Reserve_CouponProduct_Extend>();

            string Ids = "";
            foreach (var item in list.Where(x => x.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Category))
            {
                productList.AddRange(item.ProductList);
                item.CategoryIds = item.ProductList.Select(x => x.ProductId).ToList().ToArray();
            }
            if (productList != null && productList.Any())
            {
                Ids = string.Join(",", productList.Select(x => x.ProductId));
            }
            if (!string.IsNullOrWhiteSpace(Ids))
            {
                categotyList = offlineGoodsModule.GetCategoryListModule(new Model.Extend.Product.RB_Product_Category_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, CategoryIds = Ids });
            }

            if (categotyList == null || !categotyList.Any())
            {
                categotyList = new List<RB_Product_Category_Extend>();
            }



            List<RB_Goods_Extend> goodsList = new List<RB_Goods_Extend>();

            productList = new List<RB_Reserve_CouponProduct_Extend>();

            Ids = "";

            foreach (var item in list.Where(x => x.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Product))
            {
                productList.AddRange(item.ProductList);
                item.GoodsIds = item.ProductList.Select(x => x.ProductId).ToList().ToArray();
            }
            if (productList != null && productList.Any())
            {
                Ids = string.Join(",", productList.Select(x => x.ProductId));
            }

            if (!string.IsNullOrWhiteSpace(Ids))
            {
                goodsList = offlineGoodsModule.GetProductGoodsList(new RB_Goods_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, GoodsIds = Ids, GoodsClassify = 3 });
            }
            if (goodsList == null || !goodsList.Any())
            {
                goodsList = new List<RB_Goods_Extend>();
            }
            var result = list.Select(x => new
            {
                id = x.MemberCouponId,
                mall_id = userInfo.MallBaseId,
                user_id = userInfo.UserId,
                coupon_id = x.ID,
                start_time = x.StartDate.HasValue ? x.StartDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                end_time = x.EndDate.HasValue ? x.EndDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                is_use = 0,
                is_delete = 0,
                created_at = x.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                updated_at = x.UpdateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                deleted_at = "0000-00-00 00:00:00",
                receive_type = "",
                discount_limit = x.MaxDiscountsPrice,
                usehexiao = x.HeXiao - x.UseHeXiao,
                couponIco = x.CouponIco,
                coupon_data = new
                {
                    id = x.ID,
                    mall_id = userInfo.MallBaseId,
                    name = x.Name,
                    pic_url = "",
                    desc = "",
                    total_count = x.TotalNum + x.ReceiveNum,
                    expire_type = x.IndateType,
                    expire_day = x.IndateDay,
                    begin_time = x.StartDate.HasValue ? x.StartDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                    end_time = x.EndDate.HasValue ? x.EndDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                    appoint_type = (int)x.UseType,
                    rule = x.Describe,
                    is_delete = 0,
                    deleted_at = "0000-00-00 00:00:00",
                    created_at = x.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                    updated_at = x.UpdateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                    discount_limit = x.MaxDiscountsPrice,
                    couponIco = x.CouponIco,
                    usehexiao = x.HeXiao - x.UseHeXiao,
                    car = categotyList.Where(y => x.CategoryIds.Contains(x.ID)).Select(y => new
                    {
                        id = y.Id,
                        mall_id = userInfo.MallBaseId,
                        mch_id = 0,
                        parent_id = y.ParentId,
                        name = y.Name,
                        pic_url = y.AdvertisingImagePath,
                        sort = y.Sort,
                        big_pic_url = y.BigIconPath,
                        advert_pic = y.AdvertisingImage,
                        advert_url = y.AdvertisingImagePath,
                        status = y.Status,
                        created_at = y.CreateDate.HasValue ? y.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                        updated_at = y.UpdateDate.HasValue ? y.UpdateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                        deleted_at = "0000-00-00 00:00:00",
                        is_delete = 0,
                        is_show = y.IsShow,
                        advert_open_type = "",
                        advert_params = ""
                    }),
                    goods = goodsList.Where(y => x.GoodsIds.Contains(x.ID)).Select(y => new
                    {
                        id = y.Id,
                        mall_id = userInfo.MallBaseId,
                        name = y.Name,
                        original_price = y.OriginalPrice,
                        cost_price = y.CostPrice,
                        detail = y.GoodsDetails,
                        cover_pic = y.CoverImage,
                        pic_url = "",
                        video_url = y.VideoAddress,
                        unit = y.Unit,
                        created_at = y.CreateDate.HasValue ? y.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                        updated_at = y.UpdateDate.HasValue ? y.UpdateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                        deleted_at = "0000-00-00 00:00:00",
                        is_delete = 0,
                    }),
                },
                x.Name,
                x.Describe,
                x.MaxDiscountsPrice,
                x.UseType
            });
            return ApiResult.Success("", result);

        }

        #endregion


        #region 获取分销海报

        /// <summary>
        /// 获取服务人员分销海报
        /// </summary>
        /// <returns></returns>
        public ApiResult GetFenXiaoPoster()
        {
            var userInfo = AppletUserInfo;
            JObject jobj = JObject.Parse(RequestParm.msg.ToString());
            var extModel = JsonConvert.DeserializeObject<RB_Reserve_FenXiaoPoster_Extend>(RequestParm.msg.ToString());
            extModel.TenantId = userInfo.TenantId;
            extModel.MallBaseId = userInfo.MallBaseId;
            extModel.IsOpenReserve = jobj.GetInt("IsOpenReserve", 0);
            var result = reserveModule.GetReserveFenXiaoPosterModule(extModel);
            return ApiResult.Success(data: result);
        }

        #endregion


        #region 评论

        /// <summary>
        /// 用户新增评论
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetGuideCarCommentInfo()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            List<RB_Goods_Comment_Extend> list = JsonConvert.DeserializeObject<List<RB_Goods_Comment_Extend>>(req.msg.ToString());
            if (list != null && list.Any())
            {

                if (list.Where(x => (x.GoodsId ?? 0) > 0).Count() == 0)
                {
                    return ApiResult.ParamIsNull("请传递商品");
                }
                //if (list.Where(x => x.ServicePersonalId > 0).Count() == 0)
                //{
                //    return ApiResult.ParamIsNull("请传递服务人员信息");
                //}
            }
            else
            {
                return ApiResult.ParamIsNull("请选择您要评论的信息");
            }
            foreach (var demodel in list)
            {
                if ((demodel.OrderDetailId ?? 0) <= 0)
                {
                    return ApiResult.ParamIsNull("请传递订单明细OrderDetailId");
                }
                if ((demodel.GoodsId ?? 0) <= 0)
                {
                    return ApiResult.ParamIsNull("请传递商品");
                }
                if (string.IsNullOrEmpty(demodel.Content))
                {
                    return ApiResult.ParamIsNull("请输入评价内容");
                }
                demodel.CommentImage = "";
                if (demodel.CommentImgList != null && demodel.CommentImgList.Any())
                {
                    demodel.CommentImage = JsonConvert.SerializeObject(demodel.CommentImgList);
                }
                demodel.CommentGrade ??= Common.Enum.Goods.GoodsCommentTypeEnum.Praise;
                demodel.CommentScore ??= 5;
                if (demodel.CommentScore == 3 || demodel.CommentScore == 2)
                {
                    demodel.CommentGrade = Common.Enum.Goods.GoodsCommentTypeEnum.Medium;
                }
                else if (demodel.CommentScore == 1)
                {
                    demodel.CommentGrade = Common.Enum.Goods.GoodsCommentTypeEnum.Negative;
                }
                demodel.UserPhoto ??= 0;
                demodel.Is_Top ??= 2;
                demodel.Is_Show ??= 1;
                demodel.Is_Anonymity ??= 2;
                demodel.UserId ??= 0;
                demodel.Reply ??= "";
                demodel.TenantId = userInfo.TenantId;
                demodel.MallBaseId = userInfo.MallBaseId;
                demodel.UserId = userInfo.UserId;
                demodel.UserName = userInfo.Name;
                demodel.PlatformSource = userInfo.Source;
                demodel.Status = 0;
                demodel.CreateDate = DateTime.Now;
                demodel.UpdateDate = DateTime.Now;
            }

            bool flag = offlineGoodsModule.SetReserveGoodsCommentInfo(list);
            if (flag)
            {
                var demodel = list.FirstOrDefault();
                var dmodel = offlineGoodsModule.GetOrderDetailInfo(demodel.OrderDetailId ?? 0);
                if (dmodel != null && dmodel.CommentGiveIntegral > 0 && demodel.UserId > 0)
                {
                    Model.Entity.User.RB_Member_Integral memberIntegralModel = new Model.Entity.User.RB_Member_Integral
                    {
                        UserId = demodel.UserId,
                        Type = Common.Enum.MarketingCenter.RecordTypeEnum.Income,
                        PlatformType = demodel.PlatformSource,
                        Integral = dmodel.CommentGiveIntegral,
                        Description = "评论赠送" + dmodel.CommentGiveIntegral + "积分",
                        TenantId = demodel.TenantId,
                        MallBaseId = demodel.MallBaseId,
                        Remarks = "评论商品" + dmodel.GoodsName + "赠送" + dmodel.CommentGiveIntegral + "积分",
                        CreateDate = demodel.CreateDate,
                        OrderId = dmodel.OrderId
                    };
                    bool integralResult = offlineGoodsModule.AddMemberIntegral(memberIntegralModel);
                    if (integralResult)
                    {
                        return ApiResult.CouponSuccess(ResultCode.Success, 2, "", dmodel.CommentGiveIntegral.ToString());
                    }
                    else
                    {
                        return ApiResult.CouponSuccess(ResultCode.Fail, 2, "", "");
                    }
                }

                return ApiResult.CouponSuccess(ResultCode.Fail, 2, "", "");


            }
            else { return ApiResult.CouponFailed(ResultCode.Fail, 2, "", ""); }
            // if (flag) { return ApiResult.Success(); } else { return ApiResult.Failed(); }
        }


        /// <summary>
        /// 获取商品评论分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
                [AllowAnonymous] [RateValve(Policy = Policy.Ip, Limit = 10, Duration = 60)]
        public ApiResult GetAppletGoodsCommentPageList(object requestMsg)
        {
            var parms = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Goods_Comment_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Comment_Extend>(parms.msg.ToString());

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            demodel.Is_Show = 1;
            var list = offlineGoodsModule.GetAppletReservePageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.GoodsId,
                x.UserId,
                UserName = x.Is_Anonymity == 1 ? "匿名用户" : x.UserName,
                UserPhotoPath = x.UserPhotoPath ?? "",
                x.CommentGrade,
                CommentGradeName = x.CommentGrade > 0 ? ((Common.Enum.Goods.GoodsCommentTypeEnum)x.CommentGrade).GetEnumName() : "",
                x.CommentScore,
                x.CommentImgList,
                x.Content,
                x.Reply,
                x.GuideName,
                x.CarBrandName,
                x.CarColorName,
                x.CarName,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                x.ServicePersonalId
            });
            return ApiResult.Success("", pagelist);
        }



        /// <summary>
        /// 获取商品评论统计
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAppletGoodsCommentStatistics()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parms = JObject.Parse(req.msg.ToString());
            int GoodsId = parms.GetInt("GoodsId", 0);
            int StoreId = parms.GetInt("StoreId", 0);
            int ServicepersonalId = parms.GetInt("ServicepersonalId", 0);
            return offlineGoodsModule.GetAppletGoodsCommentStatistics(GoodsId, StoreId, ServicepersonalId, userInfo.TenantId, userInfo.MallBaseId);
        }

        #endregion


        #region 卡包
        /// <summary>
        /// 套餐卡领劵中心
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAllCardBagList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            RB_Reserve_CardBag_Extend demodel = JsonConvert.DeserializeObject<RB_Reserve_CardBag_Extend>(req.msg.ToString());
            demodel.UserId = userInfo.UserId;
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.SmallShopId = userInfo.UserSmallShopId;
            var list = reserveModule.GetAllCardBagList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Name,
                x.Describe,
                x.CardBagIco,
                x.MemberNum,
                x.CardNo,
                CouponId = x.ID,
                StartDate = x.StartDate.HasValue ? x.StartDate.Value.ToString("yyyy-MM-dd HH:ss:mm") : "",
                EndDate = x.EndDate.HasValue ? x.EndDate.Value.ToString("yyyy-MM-dd HH:ss:mm") : "",
                IsReceive = x.MemberNum > 0 ? 1 : 0,
            });
            return ApiResult.Success("", pagelist);
        }



        /// <summary>
        /// 获取套餐卡详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]

        public ApiResult GetReserveCardBagDetail()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            var query = JsonConvert.DeserializeObject<RB_Reserve_CardBag_Extend>(req.msg.ToString());
            query.TenantId = userInfo.TenantId;
            query.MallBaseId = userInfo.MallBaseId;
            var oldLogisticsModel = reserveModule.GetCardBagList(query).FirstOrDefault();
            if (oldLogisticsModel == null)
            {
                return ApiResult.Failed("卡包信息不存在");
            }
            else
            {
                oldLogisticsModel.StoresList = new List<RB_Stores_Extend>();

                //查询所属门店
                if (string.IsNullOrWhiteSpace(oldLogisticsModel.StoreIds) || oldLogisticsModel.StoreIds == "0")
                {
                    oldLogisticsModel.StoresList = contentModule.GetStoresListModule(new RB_Stores_Extend()
                    {
                        MallBaseId = userInfo.MallBaseId,
                        TenantId = userInfo.TenantId
                    });

                }
                else
                {
                    oldLogisticsModel.StoresList = contentModule.GetStoresListModule(new RB_Stores_Extend()
                    {
                        MallBaseId = userInfo.MallBaseId,
                        TenantId = userInfo.TenantId,
                        QIds = oldLogisticsModel.StoreIds
                    });
                }
                //判断当前人是否领取了改优惠券
                //判断套餐卡是否已领取
                var receiveList = reserveModule.GetMemberCarBagList(new RB_Reserve_MemberCardBag_Extend
                {
                    CouponId = oldLogisticsModel.ID,
                    MallBaseId = userInfo.MallBaseId,
                    TenantId = userInfo.TenantId,
                    UserId = userInfo.UserId
                });
                if (receiveList != null && receiveList.Any())
                {
                    oldLogisticsModel.MemberNum = receiveList.Count();
                }
            }
            return ApiResult.Success("", oldLogisticsModel);
        }





        /// <summary>
        /// 领取卡券
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GrantCardBag()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            var query = JsonConvert.DeserializeObject<RB_Reserve_MemberCardBag_Extend>(RequestParm.msg.ToString());
            query.TenantId = userInfo.TenantId;
            query.MallBaseId = userInfo.MallBaseId;
            query.UserId = userInfo.UserId;
            if (query == null)
            {
                return ApiResult.Failed("请传入卡券信息");
            }
            else
            {
                var oldLogisticsModel = reserveModule.GetCardBagList(new RB_Reserve_CardBag_Extend { StoreId = query.StoreId, TenantId = query.TenantId, MallBaseId = query.MallBaseId, ID = query.CouponId }).FirstOrDefault();
                var allMemberInfo = UserModule.GetMemberUserInfo(userInfo.UserId);

                if (oldLogisticsModel == null || oldLogisticsModel.ID == 0)
                {
                    return ApiResult.Failed("卡券信息不存在，请核实后再操作");
                }
                if (oldLogisticsModel.EndDate.Value < System.DateTime.Now)
                {
                    return ApiResult.Failed("卡券时间已过期");
                }
                if (!string.IsNullOrWhiteSpace(oldLogisticsModel.StoreIds))
                {
                    if (oldLogisticsModel.StoreIds != "0")
                    {
                        bool isGrantCoupon = false;
                        foreach (var item in oldLogisticsModel.StoreIds.Split(","))
                        {
                            if (Convert.ToInt32(item) > 0)
                            {
                                if (Convert.ToInt32(item) == query.StoreId)
                                {
                                    isGrantCoupon = true;
                                }
                            }
                        }
                        if (!isGrantCoupon)
                        {
                            return ApiResult.Failed("领取卡券不属于当前门店");
                        }
                    }
                }

                //判断套餐卡是否已领取
                var receiveList = reserveModule.GetMemberCarBagList(query);
                if (receiveList != null && receiveList.Any())
                {
                    return ApiResult.Failed("您已领取卡券");
                }


                RB_Reserve_MemberCardBag_Extend memberCoupon = new RB_Reserve_MemberCardBag_Extend();
                memberCoupon.Id = 0;
                memberCoupon.UserId = userInfo.UserId;
                memberCoupon.Description = oldLogisticsModel.Describe;
                memberCoupon.CreateDate = System.DateTime.Now;
                memberCoupon.TenantId = userInfo.TenantId;
                memberCoupon.MallBaseId = userInfo.MallBaseId;
                memberCoupon.Remarks = "";
                memberCoupon.CouponId = oldLogisticsModel.ID;
                memberCoupon.Name = oldLogisticsModel.Name;

                memberCoupon.StartDate = oldLogisticsModel.StartDate;
                memberCoupon.EndDate = oldLogisticsModel.EndDate;

                var memberList = new List<RB_Reserve_MemberCardBag_Extend>();
                memberList.Add(memberCoupon);
                bool result = reserveModule.GrantCardBag(memberList, oldLogisticsModel);
                if (result)
                {
                    return ApiResult.Success("卡券信息领取成功");
                }
                else
                {
                    return ApiResult.Failed("卡券信息领取成功");
                }
            }
        }





        /// <summary>
        /// 我的套餐卡
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMemberCardBagList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            RB_Reserve_CardBag_Extend demodel = JsonConvert.DeserializeObject<RB_Reserve_CardBag_Extend>(req.msg.ToString());
            demodel.UserId = userInfo.UserId;
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            var list = reserveModule.GetMemberCardBagList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Name,
                x.Describe,
                x.ID,
                x.CardBagIco,
                x.MemberCouponId,
                x.CardNo,
                IsOver = x.EndDate.Value > System.DateTime.Now ? 0 : 1,
                StartDate = x.StartDate.HasValue ? x.StartDate.Value.ToString("yyyy-MM-dd HH:ss:mm") : "",
                EndDate = x.EndDate.HasValue ? x.EndDate.Value.ToString("yyyy-MM-dd HH:ss:mm") : "",
            });
            return ApiResult.Success("", pagelist);
        }
        #endregion

        #endregion
    }
}
