using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Mall.AOP;
using Mall.Common.API;
using Mall.Common.Enum.Reserve;
using Mall.Common.Plugin;
using Mall.Model.Entity.Product;
using Mall.Model.Entity.Reserve;
using Mall.Model.Entity.User;
using Mall.Model.Extend.Reserve;
using Mall.Model.Extend.User;
using Mall.Module.Reserve;
using Mall.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Mall.WebApi.Controllers.Reserve
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class ReserveController : BaseController
    {

        private readonly ReserveModule reserveModule = new ReserveModule();
        private Module.User.UserModule UserModule = new Module.User.UserModule();
        /// <summary>
        /// 门店处理类对象
        /// </summary>
        private readonly Module.User.ContentModule contentModule = AOPHelper.CreateAOPObject<Module.User.ContentModule>();

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



        #region 海报
        /// <summary>
        /// 添加修改服务人员海报
        /// </summary>
        /// <returns></returns>
        public ApiResult SetReserveFenXiaoPoster()
        {
            var extModel = JsonConvert.DeserializeObject<RB_Reserve_FenXiaoPoster_Extend>(RequestParm.msg.ToString());
            extModel.TenantId = RequestParm.TenantId;
            extModel.MallBaseId = RequestParm.MallBaseId;
            var flag = reserveModule.SetReserveFenXiaoPosterModule(extModel);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 获取服务人员海报
        /// </summary>
        /// <returns></returns>
        public ApiResult GetReserveFenXiaoPoster()
        {
            var extModel = JsonConvert.DeserializeObject<RB_Reserve_FenXiaoPoster_Extend>(RequestParm.msg.ToString());
            extModel.TenantId = RequestParm.TenantId;
            extModel.MallBaseId = RequestParm.MallBaseId;
            var result = reserveModule.GetReserveFenXiaoPosterModule(extModel);
            return ApiResult.Success(data: result);
        }
        #endregion

        #region 基础配置
        /// <summary>
        /// 获取线下服务行业基础配置
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetReserveBaseInfo()
        {
            var req = RequestParm;

            var model = reserveModule.GetReserveBaseInfo(req.TenantId, req.MallBaseId);
            return ApiResult.Success("", model);
        }

        /// <summary>
        /// 保存线下服务行业基础配置
        /// </summary>
        /// <returns></returns>
        public ApiResult SetReserveBaseInfo()
        {
            var req = RequestParm;
            RB_Reserve_Base_Extend demodel = JsonConvert.DeserializeObject<RB_Reserve_Base_Extend>(req.msg.ToString());

            demodel.OrderStateJson = "";
            if (demodel.OrderStateList != null && demodel.OrderStateList.Any())
            {
                demodel.OrderStateJson = JsonConvert.SerializeObject(demodel.OrderStateList);
            }
            demodel.BusinessHoursJson = "";
            if (demodel.BusinessHoursList != null && demodel.BusinessHoursList.Any())
            {
                demodel.BusinessHoursJson = JsonConvert.SerializeObject(demodel.BusinessHoursList);
            }
            if (demodel.PayTypeList == null || !demodel.PayTypeList.Any())
            {
                return ApiResult.Failed("请选择付款方式");
            }
            demodel.PayTypeJson = "";
            if (demodel.PayTypeList != null && demodel.PayTypeList.Any())
            {
                demodel.PayTypeJson = JsonConvert.SerializeObject(demodel.PayTypeList);
            }
            demodel.TenantId = req.TenantId;
            demodel.MallBaseId = req.MallBaseId;
            demodel.UpdateBy = req.EmpId;
            demodel.CreateDate = DateTime.Now;
            demodel.UpdateDate = DateTime.Now;
            bool flag = reserveModule.SetReserveBaseInfo(demodel);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }
        #endregion

        #region 服务人员
        /// <summary>
        /// 获取服务人员列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetServicePersonalPageList()
        {
            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.GetServicePersonalPageList(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,
                x.StoreName,
                Score = x.Score == 0 ? "暂无" : x.Score.ToString(),
                x.OrderNum,
                CreateDateStr = x.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                x.ServiceStatus,
                x.Telephone,
                x.Major,
                x.WorkYears,
                GenderStr = x.Gender.GetEnumName(),
                ServiceTypeStr = x.ServiceType.GetEnumName(),
                x.FictitiousReserveNum,
            });
            return ApiResult.Success("", pagelist);
        }


        



        /// <summary>
        /// 禁用/启用服务人员状态
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult EnableServicePersonalInfo()
        {
            var parms = RequestParm;
            JObject parmsJob = JObject.Parse(RequestParm.msg.ToString());
            string idInfo = parmsJob.GetStringValue("Ids");
            int serviceStatus = parmsJob.GetInt("ServiceStatus", 0);
            if (string.IsNullOrWhiteSpace(idInfo))
            {
                return ApiResult.Failed("请传递参数");
            }
            if (serviceStatus == 0)
            {
                return ApiResult.Failed("请选择您要操作的类型");
            }
            bool flag = reserveModule.EnableServicePersonalInfo(idInfo.Split(",").ToList(), serviceStatus, UserInfo.TenantId, parms.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }



        /// <summary>
        /// 获取详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetServicePersonalModel()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Reserve_ServicePersonal_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            query.ServiceStatus = -1;
            var oldLogisticsModel = reserveModule.GetServicePersonalList(query).FirstOrDefault();
            if (oldLogisticsModel == null)
            {
                oldLogisticsModel = new RB_Reserve_ServicePersonal_Extend();
            }
            if (!string.IsNullOrWhiteSpace(oldLogisticsModel.LableName))
            {
                oldLogisticsModel.LableNameList = JsonConvert.DeserializeObject<List<string>>(oldLogisticsModel.LableName);
            }
            return ApiResult.Success("", oldLogisticsModel);
        }


        /// <summary>
        /// 获取全部服务人员
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetServicePersonalList()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Reserve_ServicePersonal_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            query.ServiceStatus = 1;
            var list = reserveModule.GetServicePersonalList(query);
            var result = list.Select(x => new { x.ID, x.Name, x.ServiceLogo, x.StoreName, GenderStr = x.Gender.GetEnumName() });
            return ApiResult.Success("", result);
        }


        /// <summary>
        /// 保存服务人员信息
        /// </summary>
        /// <returns></returns>
        public ApiResult AddOrUpdateServicePersonal()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Reserve_ServicePersonal_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            if (query == null)
            {
                return ApiResult.Failed("请传入服务人员信息");
            }
            else
            {
                if (string.IsNullOrWhiteSpace(query.Name))
                {
                    return ApiResult.Failed("请输入服务人员名称");
                }
                if (string.IsNullOrWhiteSpace(query.ServiceLogo))
                {
                    return ApiResult.Failed("请上传服务人员头像");
                }
                if (string.IsNullOrWhiteSpace(query.Telephone))
                {
                    return ApiResult.Failed("请输入联系电话");
                }
                if (query.ID == 0)
                {
                    query.CreateDate = System.DateTime.Now;
                }
                query.UpdateDate = System.DateTime.Now;
                if (query.LableNameList != null && query.LableNameList.Any())
                {
                    query.LableName = JsonConvert.SerializeObject(query.LableNameList);
                }
                bool result = reserveModule.AddOrUpdateServicePersonal(query);
                if (result)
                {
                    return ApiResult.Success("服务人员信息保存成功");
                }
                else
                {
                    return ApiResult.Failed("服务人员信息保存失败");
                }
            }
        }



        /// <summary>
        /// 获取关联产品类型
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetServiceTypeEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(ServiceTypeEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }

        /// <summary>
        /// 获取性别类型
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetGenderEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(GenderEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }


        #region 服务人员的排班计划


        /// <summary>
        /// 获取全部服务人员
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetServiceTargetDateList()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Reserve_ServiceTargetDate_Extend>(RequestParm.msg.ToString());
            var list = reserveModule.GetServiceTargetDateList(query);
            List<string> result = new List<string>();
            foreach (var item in list)
            {
                if (item.Date.HasValue)
                {
                    result.Add(item.Date.Value.ToString("yyyy-MM-dd"));
                }
            }
            return ApiResult.Success("", result);
        }


        /// <summary>
        /// 保存服务人员信息
        /// </summary>
        /// <returns></returns>
        public ApiResult AddOrUpdateServiceTargetDate()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Reserve_ServicePersonal_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            if (query == null)
            {
                return ApiResult.Failed("请传入服务人员信息");
            }
            else
            {
                if (query.TargetDateStrList == null || !query.TargetDateStrList.Any())
                {
                    return ApiResult.Failed("请传入服务人员排班信息");
                }

                if (query.TargetDateStrList != null && query.TargetDateStrList.Any())
                {
                    if (query.TargetDateStrList.Count() != query.TargetDateStrList.Distinct().Count())
                    {
                        return ApiResult.ParamIsNull("可预定日期有重复");
                    }
                    query.ServiceTargetDateList = new List<RB_Reserve_ServiceTargetDate_Extend>();
                    foreach (var item in query.TargetDateStrList)
                    {
                        query.ServiceTargetDateList.Add(new RB_Reserve_ServiceTargetDate_Extend()
                        {
                            Date = Convert.ToDateTime(item)
                        });
                    }
                }

                string vmsg = reserveModule.ValidateServiceTargetDate(query.ID, query.ServiceTargetDateList);
                if (vmsg != "")
                {
                    return ApiResult.Failed(vmsg);
                }
                bool result = reserveModule.AddOrUpdateServiceTargetDate(query.ID, query.ServiceTargetDateList);
                if (result)
                {
                    return ApiResult.Success("服务人员信息保存成功");
                }
                else
                {
                    return ApiResult.Failed("服务人员信息保存失败");
                }
            }
        }

        #endregion



        #endregion


        #region 套餐卡

        [HttpPost]
        public ApiResult GetDiscountCouponPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            RB_Reserve_Coupon_Extend demodel = JsonConvert.DeserializeObject<RB_Reserve_Coupon_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = reserveModule.GetDiscountCouponPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.ID,
                x.Name,
                x.HeXiao,
                x.CouponIco,
                UseTypeStr = Mall.Common.Plugin.EnumHelper.GetEnumName(x.UseType),
                StartDate = x.StartDate.HasValue ? x.StartDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                CreateDate = x.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                x.IndateType,
                x.IndateDay,
                EndDate = x.EndDate.HasValue ? x.EndDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                x.TotalNum,
                ResidueNum = x.ReceiveNum,
                x.PickupCenter,
                x.SmallShopName,
                x.SmallShopId,
                x.IsZanYangUse
            });
            return ApiResult.Success("", pagelist);
        }


        /// <summary>
        /// 获取详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDiscountCouponDetail()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Reserve_Coupon_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            var oldLogisticsModel = reserveModule.GetDiscountCouponList(query).FirstOrDefault();
            if (oldLogisticsModel == null)
            {
                oldLogisticsModel = new RB_Reserve_Coupon_Extend();
                oldLogisticsModel.IndateType = Common.Enum.MarketingCenter.IndateTypeEnum.DayHorizon;
            }

            return ApiResult.Success("", oldLogisticsModel);
        }


        /// <summary>
        /// 保存套餐卡
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult AddOrUpdateDiscountCoupon()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Reserve_Coupon_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            if (query == null)
            {
                return ApiResult.Failed("请传入套餐卡信息");
            }
            else
            {
                if (string.IsNullOrWhiteSpace(query.Name))
                {
                    return ApiResult.Failed("请输入套餐卡名称");
                }
                if (query.IndateType == Common.Enum.MarketingCenter.IndateTypeEnum.DayHorizon)
                {
                    if (query.IndateDay == 0)
                    {
                        return ApiResult.Failed("请输入有效期天数");
                    }
                }
                else
                {
                    if (!query.StartDate.HasValue || !query.EndDate.HasValue)
                    {
                        return ApiResult.Failed("开始日期或结束日期必填");
                    }
                    if (query.StartDate > query.EndDate)
                    {
                        return ApiResult.Failed("开始日期必须小于结束日期");
                    }
                }
                if (query.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Category || query.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Product)
                {
                    if (query.ProductList == null || !query.ProductList.Any())
                    {
                        return ApiResult.Failed(query.UseType == Common.Enum.MarketingCenter.UseTypeEnum.Category ? "请选择商品类别" : "请选择商品");
                    }
                }
                if (query.TotalNum == 0)
                {
                    return ApiResult.Failed("请输入可发放数量");
                }

                if (string.IsNullOrWhiteSpace(query.Describe))
                {
                    return ApiResult.Failed("请输入套餐卡描述");
                }
                if (query.ID == 0)
                {
                    query.CreateDate = System.DateTime.Now;
                }

                query.UpdateDate = System.DateTime.Now;
                bool result = reserveModule.AddOrUpdateDiscountCoupon(query);
                if (result)
                {
                    return ApiResult.Success("套餐卡信息保存成功");
                }
                else
                {
                    return ApiResult.Failed("套餐卡信息保存失败");
                }
            }
        }

        /// <summary>
        /// 删除套餐卡
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelDiscountCoupon()
        {
            var parms = RequestParm;
            JObject parmsJob = JObject.Parse(RequestParm.msg.ToString());
            int Id = parmsJob.GetInt("Id", 0);
            if (Id <= 0)
            {
                return ApiResult.Failed("请传递参数");
            }
            bool flag = reserveModule.DelDiscountCoupon(Id, UserInfo.TenantId, parms.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 加入领劵中心
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult UpdatePickupType()
        {
            var parms = RequestParm;
            JObject parmsJob = JObject.Parse(RequestParm.msg.ToString());
            int Id = parmsJob.GetInt("Id", 0);
            if (Id <= 0)
            {
                return ApiResult.Failed("请传递参数");
            }
            bool flag = reserveModule.UpdatePickupType(Id, UserInfo.TenantId, parms.MallBaseId);
            if (flag)
            {
                return ApiResult.Success("操作成功");
            }
            else
            {
                return ApiResult.Failed("操作失败");
            }
        }


        /// <summary>
        /// 发放套餐卡
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GrantCoupon()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Reserve_Coupon_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            if (query == null)
            {
                return ApiResult.Failed("请传入套餐卡信息");
            }
            else
            {
                var oldLogisticsModel = reserveModule.GetDiscountCouponList(query).FirstOrDefault();
                if (oldLogisticsModel == null || oldLogisticsModel.ID == 0)
                {
                    return ApiResult.Failed("套餐卡信息不存在，请核实后再操作");
                }
                if (string.IsNullOrWhiteSpace(query.UserIds))
                {
                    return ApiResult.Failed("请选择发放对象");
                }

                //获取领取套餐卡用户的信息判断是否属于当前店铺
                var memberList = new List<RB_Member_User_Extend>();
                if (oldLogisticsModel.SmallShopId > 0)
                {
                    memberList = UserModule.GetMemberUserList(new RB_Member_User_Extend { TenantId = UserInfo.TenantId, MallBaseId = parms.MallBaseId, UserIds = query.UserIds });

                    var notSmallShopList = memberList.Where(x => x.SmallShopId != oldLogisticsModel.SmallShopId);
                    if (notSmallShopList != null && notSmallShopList.Any())
                    {
                        return ApiResult.Failed(string.Join(",", notSmallShopList.Select(x => x.Name) + "不属于当前店铺"));
                    }
                }
                List<RB_Reserve_MemberCoupon_Extend> list = new List<RB_Reserve_MemberCoupon_Extend>();
                for (int i = 0; i < query.GrantNum; i++)
                {
                    foreach (var item in query.UserIds.Split(","))
                    {
                        if (!string.IsNullOrWhiteSpace(item))
                        {
                            RB_Reserve_MemberCoupon_Extend memberCoupon = new RB_Reserve_MemberCoupon_Extend();
                            memberCoupon.Id = 0;
                            memberCoupon.UserId = Convert.ToInt32(item);
                            memberCoupon.Description = oldLogisticsModel.Describe;
                            memberCoupon.CreateDate = System.DateTime.Now;
                            memberCoupon.TenantId = oldLogisticsModel.TenantId;
                            memberCoupon.MallBaseId = oldLogisticsModel.MallBaseId;
                            memberCoupon.Remarks = "";
                            memberCoupon.CouponId = oldLogisticsModel.ID;
                            memberCoupon.Name = oldLogisticsModel.Name;
                            memberCoupon.UseType = oldLogisticsModel.UseType;
                            memberCoupon.HeXiao = oldLogisticsModel.HeXiao;
                            memberCoupon.UseHeXiao = 0;
                            if (oldLogisticsModel.IndateType == Common.Enum.MarketingCenter.IndateTypeEnum.DayHorizon)
                            {
                                memberCoupon.StartDate = System.DateTime.Now;
                                memberCoupon.EndDate = memberCoupon.StartDate.Value.AddDays(oldLogisticsModel.IndateDay);
                            }
                            else
                            {
                                memberCoupon.StartDate = oldLogisticsModel.StartDate;
                                memberCoupon.EndDate = oldLogisticsModel.EndDate;
                            }
                            list.Add(memberCoupon);
                        }
                    }
                }
                if (oldLogisticsModel.TotalNum != -1)
                {
                    if (oldLogisticsModel.TotalNum < list.Count())
                    {
                        return ApiResult.Failed("套餐卡剩余" + oldLogisticsModel.TotalNum + "张");
                    }
                }
                bool result = reserveModule.GrantCoupon(list, oldLogisticsModel);
                if (result)
                {
                    return ApiResult.Success("套餐卡信息保存成功");
                }
                else
                {
                    return ApiResult.Failed("套餐卡信息保存失败");
                }
            }
        }




        /// <summary>
        /// 获取详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAllDiscountCouponList()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Reserve_Coupon_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            var oldLogisticsModel = reserveModule.GetAllDiscountCouponList(query);
            return ApiResult.Success("", oldLogisticsModel);
        }




        /// <summary>
        /// 我的套餐卡
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCouponPageListByMemberId()
        {
            var req = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            RB_Reserve_Coupon_Extend demodel = JsonConvert.DeserializeObject<RB_Reserve_Coupon_Extend>(req.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = req.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.CouponIco,
                x.HeXiao,
                x.UseHeXiao,
                x.ID,
                x.MemberCouponId,
                CreateDate = x.CreateDate.ToString("yyyy-MM-dd HH:ss:mm"),
                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,
                x.PickupCenter,
                x.UseState,
                x.GetType
            });
            return ApiResult.Success("", pagelist);
        }





        /// <summary>
        /// 删除用户套餐卡
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelMemberCoupon()
        {
            var parms = RequestParm;
            JObject parmsJob = JObject.Parse(RequestParm.msg.ToString());
            int Id = parmsJob.GetInt("MemberCouponId", 0);
            if (Id <= 0)
            {
                return ApiResult.Failed("请传递参数");
            }
            bool flag = reserveModule.DelMemberCoupon(Id, UserInfo.TenantId, parms.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        #endregion


        #region 自动发放套餐卡
        /// <summary>
        /// 自动发放套餐卡列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSelfMotionPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            RB_Reserve_CSelfMotion_Extend demodel = JsonConvert.DeserializeObject<RB_Reserve_CSelfMotion_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = reserveModule.GetSelfMotionPageLis(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.ID,
                x.GrantNum,
                x.DiscountCouponName,
                TriggerTypeStr = Mall.Common.Plugin.EnumHelper.GetEnumName(x.TriggerType)

            });
            return ApiResult.Success("", pagelist);
        }


        /// <summary>
        /// 获取自动发放套餐卡详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GettRepositoryList()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Reserve_CSelfMotion_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            var oldLogisticsModel = reserveModule.GettRepositoryList(query).FirstOrDefault();
            if (oldLogisticsModel == null)
            {
                oldLogisticsModel = new RB_Reserve_CSelfMotion_Extend();
            }
            else
            {
                if (oldLogisticsModel.IsAll == 1)
                {
                    oldLogisticsModel.UserList = new List<RB_Reserve_CSelfMotionMember_Extend>();
                    oldLogisticsModel.UserList = reserveModule.GetSelfMotionMemberList(new RB_Reserve_CSelfMotionMember_Extend { TenantId = oldLogisticsModel.TenantId, MallBaseId = oldLogisticsModel.MallBaseId, SelfMotionId = oldLogisticsModel.ID });
                }

            }
            return ApiResult.Success("", oldLogisticsModel);
        }


        /// <summary>
        /// 保存自动发放套餐卡
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult AddOrUpdateSelfMotion()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Reserve_CSelfMotion_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            if (query == null)
            {
                return ApiResult.Failed("请传入自动发放套餐卡信息");
            }
            else
            {
                if (query.ID == 0)
                {
                    query.CreateDate = System.DateTime.Now;
                }
                if (query.IsAll == 1 && (query.UserList == null || !query.UserList.Any()))
                {
                    return ApiResult.Failed("请选择领取人信息");
                }
                query.UpdateDate = System.DateTime.Now;
                bool result = reserveModule.AddOrUpdateSelfMotion(query);
                if (result)
                {
                    return ApiResult.Success("自动发放套餐卡保存成功");
                }
                else
                {
                    return ApiResult.Failed("自动发放套餐卡保存失败");
                }
            }
        }

        /// <summary>
        /// 删除自动发放套餐卡
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelDiscountSelfMotion()
        {
            var parms = RequestParm;
            JObject parmsJob = JObject.Parse(RequestParm.msg.ToString());
            int Id = parmsJob.GetInt("Id", 0);
            if (Id <= 0)
            {
                return ApiResult.Failed("请传递参数");
            }
            bool flag = reserveModule.DelDiscountSelfMotion(Id, UserInfo.TenantId, parms.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }



        /// <summary>
        /// 获取触发事件枚举
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetTriggerTypeEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(Common.Enum.MarketingCenter.TriggerTypeEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }


        #endregion


        #region 	预约看板

        /// <summary>
        /// 获取详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetStoreOrderInfo()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Reserve_ServicePersonal_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            var oldLogisticsModel = contentModule.GetStoresListModule(new Model.Entity.User.RB_Stores_Extend { TenantId = UserInfo.TenantId, MallBaseId = parms.MallBaseId, Id = query.StoreId }).FirstOrDefault();
            if (string.IsNullOrWhiteSpace(query.WorkDate))
            {
                query.WorkDate = System.DateTime.Now.ToString("yyyy-MM-dd");
            }
            List<RB_Reserve_ServicePersonal_Extend> servicePersonalList = new List<RB_Reserve_ServicePersonal_Extend>();
            List<Model.Extend.Product.RB_Goods_OrderDetail_Extend> orderList = new List<Model.Extend.Product.RB_Goods_OrderDetail_Extend>();
            List<ServicePersonalKanBan> KanBanList = new List<ServicePersonalKanBan>();
            List<string> allTime = new List<string>();
            if (oldLogisticsModel == null)
            {
                return ApiResult.Failed("店铺信息不存在");
            }
            else
            {
                //获取门店下面当天需要上班的服务人员
                servicePersonalList = reserveModule.GetKanBanServicePersonalList(query);
                //获取门店下面当前的订单信息
                orderList = offlineGoodsModule.GetReserveOrderList(new Model.Extend.Product.RB_Goods_Order_Extend { TenantId = UserInfo.TenantId, MallBaseId = parms.MallBaseId, OrderClassify = 3, StoresId = query.StoreId, StartTime = query.WorkDate });

                foreach (var item in servicePersonalList)//添加到服务人员
                {
                    ServicePersonalKanBan kanBanModel = new ServicePersonalKanBan
                    {

                        Name = item.Name,
                        Id = item.ID,
                        OrderList = new List<OrderKanBan>(),
                        StoreName = item.StoreName,
                        StoreAddress = item.StoreAddress
                    };
                    KanBanList.Add(kanBanModel);
                }
                //看门店营业时间半小时一个节点
                try
                {
                    int startTime = Convert.ToInt32(oldLogisticsModel.StartTime.Split(':')[0]);
                    int endTime = Convert.ToInt32(oldLogisticsModel.EndTime.Split(':')[0]);
                    DateTime tempStartTime = Convert.ToDateTime(System.DateTime.Now.ToString("yyyy-MM-dd") + " " + oldLogisticsModel.StartTime);
                    DateTime tempEndTime = Convert.ToDateTime(System.DateTime.Now.ToString("yyyy-MM-dd") + " " + oldLogisticsModel.EndTime);
                    if (startTime > endTime)//次日营业
                    {
                        tempEndTime = Convert.ToDateTime(System.DateTime.Now.AddDays(1).ToString("yyyy-MM-dd") + " " + oldLogisticsModel.EndTime);
                    }
                    DateTime nowStartTime = tempStartTime;
                    DateTime nowEndTime = tempEndTime;
                    int startMin = Convert.ToInt32(oldLogisticsModel.StartTime.Split(':')[1]);
                    if (startMin >= 0 && startMin < 30)
                    {
                        nowStartTime = Convert.ToDateTime(System.DateTime.Now.ToString("yyyy-MM-dd") + " " + startTime + ":00");
                    }
                    else
                    {
                        nowStartTime = Convert.ToDateTime(System.DateTime.Now.ToString("yyyy-MM-dd") + " " + startTime + ":30");
                    }
                    int endMin = Convert.ToInt32(oldLogisticsModel.EndTime.Split(':')[1]);
                    if (endMin >= 0 && endMin < 30)
                    {
                        nowEndTime = Convert.ToDateTime(System.DateTime.Now.ToString("yyyy-MM-dd") + " " + endTime + ":00");
                    }
                    else
                    {
                        nowEndTime = Convert.ToDateTime(System.DateTime.Now.ToString("yyyy-MM-dd") + " " + endTime + ":30");
                    }

                    bool isAddTime = true;
                    foreach (var item in KanBanList)
                    {
                        for (var day = nowStartTime; day <= nowEndTime; day = day.AddMinutes(30))
                        {
                            string nowTimeInfo = day.ToString("HH:mm");
                            if (day == nowStartTime)
                            {
                                nowTimeInfo = oldLogisticsModel.StartTime;
                            }
                            else if (day == nowEndTime)
                            {
                                nowTimeInfo = oldLogisticsModel.EndTime;
                            }
                            if (isAddTime)
                            {
                                allTime.Add(nowTimeInfo);
                            }
                            var tempOrderList = orderList.Where(x => x.ServicepersonalId == item.Id && day <= Convert.ToDateTime(x.ServiceDate + " " + x.ServiceTime) && Convert.ToDateTime(x.ServiceDate + " " + x.ServiceTime) < day.AddMinutes(30));
                            foreach (var itemOrder in tempOrderList)
                            {
                                OrderKanBan orderModel = new OrderKanBan();
                                orderModel.Id = item.Id;
                                orderModel.Name = item.Name;
                                orderModel.GoodsName = itemOrder.GoodsName;
                                orderModel.ServiceTime = itemOrder.ServiceTime;
                                orderModel.SystemServiceTime = nowTimeInfo;
                                orderModel.GoodServiceTime = itemOrder.GoodServiceTime;
                                orderModel.UserName = itemOrder.UserName;
                                orderModel.UserPhoto = itemOrder.UserPhoto;
                                orderModel.OrderId = itemOrder.OrderId ?? 0;
                                orderModel.OrderDetailId = itemOrder.Id;
                                orderModel.Number = itemOrder.Number ?? 0;
                                orderModel.BuyerMessage = itemOrder.BuyerMessage;
                                orderModel.Mobile = itemOrder.Mobile;
                                item.OrderList.Add(orderModel);
                            }
                        }
                        isAddTime = false;
                    }
                }
                catch (Exception ex)
                {

                    LogHelper.WriteInfo("门店时间转换错误" + ex.ToString());
                }
                return ApiResult.Success("", new { KanBanList, allTime });
            }


        }
        #endregion


        #region 服务人员绩效统计
        /// <summary>
        /// 获取服务人员列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAchievementsList()
        {
            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;
            var list = reserveModule.GetAchievementsList(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,
                x.ServiceTargetDateNum,
                x.OrderNum,
                x.Final_Price,
                x.OrderGuestNum,
                ScoreStr = (x.CommentScore > 0 && x.CommentNum > 0) ? (Convert.ToDecimal(x.CommentScore / x.CommentNum)) : 5
            });
            return ApiResult.Success("", pagelist);
        }
        #endregion
    }
}