using System;
using System.Collections.Generic;
using System.Linq;
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();

        /// <summary>
        /// 线下服务首页获取当前距离最近门店
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        [AllowAnonymous]
        public virtual ApiResult GetCurrentStore(object requestMsg)
        {
            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
            }, isFirst: true)?.FirstOrDefault();
            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 = new
                    {
                        consumptionStoreId = 0,
                        consumptionStoreName = "HK门店"
                    }
                },
            };
            return ApiResult.Success(data: result);
        }


        /// <summary>
        /// 小程序获取门店分页列表
        /// </summary>
        /// <param name="requestMsg"></param>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        [AllowAnonymous]
        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]
        public virtual ApiResult GetStoreInfo(object requestMsg)
        {
            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
            }, isFirst: true)?.FirstOrDefault();
            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
                },
            };
            return ApiResult.Success(data: result);
        }



        #region 获取设计师与套餐卡


        #region 设计师
        /// <summary>
        /// 获取服务人员列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ApiResult GetServicePersonalList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            RB_Reserve_ServicePersonal_Extend demodel = JsonConvert.DeserializeObject<RB_Reserve_ServicePersonal_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = UserInfo.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);
        }
        #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
            });
            return ApiResult.Success("", pagelist);
        }



        /// <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 { 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 (allMemberInfo.SmallShopId == 0)
                {
                    if (oldLogisticsModel.SmallShopId > 0)
                    {
                        return ApiResult.Failed("您不属于当前店铺");
                    }
                }
                else
                {
                    if (oldLogisticsModel.SmallShopId > 0 && oldLogisticsModel.SmallShopId != allMemberInfo.SmallShopId)
                    {
                        return ApiResult.Failed("领取套餐卡不属于当前店铺");
                    }
                    if (allMemberInfo.SmallShopId > 0 && oldLogisticsModel.SmallShopId == 0 && oldLogisticsModel.IsZanYangUse == 1)
                    {
                        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 = new List<RB_Product_Category_Extend>();  //productModule.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 = new List<RB_Goods_Extend>(); //productModule.GetProductGoodsList(new RB_Goods_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, GoodsIds = Ids });
            }
            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

        #endregion
    }
}
