using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Mall.AOP;
using Mall.Common.API;
using Mall.Common.Enum.Goods;
using Mall.Common.Plugin;
using Mall.Model.Extend.Product;
using Mall.Model.Extend.User;
using Mall.Module.Product;
using Mall.Module.User;
using Mall.WebApi.Filter;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
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 OSGoodsController : BaseController
    {
        /// <summary>
        /// 线下服务商品处理类对象
        /// </summary>
        private readonly OfflineGoodsModule offlineGoodsModule = AOPHelper.CreateAOPObject<OfflineGoodsModule>();

        private readonly OrderModule orderModule = new OrderModule();
        private readonly Module.User.MiniProgramModule programModule = new Module.User.MiniProgramModule();
        private readonly UserModule userModule = new UserModule();

        /// <summary>
        /// 商品后台分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetOfflineGoodsPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            JObject parameters = JObject.Parse(RequestParm.msg.ToString());
            RB_Goods_Extend demodel = new RB_Goods_Extend()
            {
                Name = parameters.GetStringValue("Name"),
                GoodsStatus = parameters.GetInt("GoodsStatus"),
                CategoryIds = parameters.GetStringValue("CategoryIds"),
                Id = parameters.GetInt("Id"),
                StartTime = parameters.GetStringValue("StartTime"),
                EndTime = parameters.GetStringValue("EndTime"),
                OrderBy = parameters.GetInt("OrderBy"),
                StoresIds=parameters.GetStringValue("StoresIds")
            };

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = offlineGoodsModule.GetOfflineProductGoodsPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.Name,
                x.Sort,
                x.CoverImage,
                CategoryList = x.CategoryList.Select(y => new { y.Id, y.CategoryName }),
                x.SellingPrice,
                x.GoodsBuyNum,
                x.GoodsStatus,
                x.TenantId,
                x.MallBaseId,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                x.DepositMoney,
                x.IsChooseServicePerson,
                x.StoreNameList
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 商品导出
        /// </summary>
        [HttpPost]
        public FileContentResult GetProductGoodsListToExcel()
        {
            var parms = RequestParm;
            RB_Goods_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Extend>(parms.msg.ToString());
            string ExcelName = "司导商品列表" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            List<ExcelDataSource> slist = new List<ExcelDataSource>();
            ExcelDataSource header = new ExcelDataSource()
            {
                ExcelRows = new List<ExcelColumn>(30)
                {
                    new ExcelColumn(value: "序号") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "商品名称") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "原价") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "成本价") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "商品详情") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "商品缩略图") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "商品轮播图") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "商品视频") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "售价") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "赠送积分") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "赠送积分类型") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "可抵扣积分") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "可抵扣积分类型") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "允许多件累计折扣") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "自定义分享图片") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "自定义分享标题") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "排序") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "是否单独区域购买") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "区域限购详情") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "站点") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "导游") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "车辆") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "车辆颜色") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "车牌号") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "是否拼座") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "乘坐人数") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "提前预定时间") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER }
                }
            };
            slist.Add(header);
            try
            {
                demodel.TenantId = parms.TenantId;
                demodel.MallBaseId = parms.MallBaseId;
                var list = offlineGoodsModule.GetProductGoodsPageListToExcel(1, 10000, out long count, demodel);
                #region 组装数据
                int Num = 0;
                foreach (var item in list)
                {
                    Num++;
                    string AreaList = "";
                    if (item.IsAreaBuy == 1)
                    {
                        AreaList = JsonConvert.SerializeObject(item.AreaList.Select(x => new
                        {
                            x.Id,
                            x.GoodsId,
                            x.AreaId,
                            x.AreaName,
                            x.AreaType
                        }));
                    }

                    ExcelDataSource datarow = new ExcelDataSource()
                    {
                        ExcelRows = new List<ExcelColumn>(30)
                        {
                            new ExcelColumn(value:Num.ToString()){ },
                            new ExcelColumn(value:item.Name){ },
                            new ExcelColumn(value:(item.OriginalPrice??0).ToString()){ },
                            new ExcelColumn(value:(item.CostPrice??0).ToString()){ },
                            new ExcelColumn(value:item.GoodsDetails){ },
                            new ExcelColumn(value:item.CoverImage){ },
                            new ExcelColumn(value:item.CarouselImage){ },
                            new ExcelColumn(value:item.VideoAddress){ },
                            new ExcelColumn(value:(item.SellingPrice??0).ToString()){ },
                            new ExcelColumn(value:(item.IntegralPresent??0).ToString()){ },
                            new ExcelColumn(value:(item.IntegralPresentType??0).ToString()){ },
                            new ExcelColumn(value:(item.PointsDeduction??0).ToString()){ },
                            new ExcelColumn(value:(item.PointsDeductionType??0).ToString()){ },
                            new ExcelColumn(value:(item.IsMultipleDeduction??0).ToString()){ },
                            new ExcelColumn(value:item.CustomShareImage ??""){ },
                            new ExcelColumn(value:item.CustomShareTitles ??""){ },
                            new ExcelColumn(value:(item.Sort??0).ToString()){ },
                            new ExcelColumn(value:(item.IsAreaBuy??0).ToString()){ },
                            new ExcelColumn(value:AreaList.ToString()){ },
                            new ExcelColumn(value:item.SiteName){ },
                            new ExcelColumn(value:item.GuideName){ },
                            new ExcelColumn(value:item.CarName){ },
                            new ExcelColumn(value:item.CarColorName){ },
                            new ExcelColumn(value:item.CarNumber){ },
                            new ExcelColumn(value:item.IsSpell==1?"是":"否"){ },
                            new ExcelColumn(value:(item.RideNum??0).ToString()){ },
                            new ExcelColumn(value:(item.AdvanceDay??0).ToString()+"天"){ },
                        }
                        ,
                        ColumnHight = 30
                    };
                    slist.Add(datarow);
                }
                #endregion
                var byteData = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData, "application/octet-stream", ExcelName);
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, string.Format("GetFileFromWebApi_requestData: {0}", JsonHelper.Serialize(RequestParm)));
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }

        }

        /// <summary>
        /// 获取商品详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetGoodsInfo()
        {
            var req = RequestParm;
            JObject prams = JObject.Parse(req.msg.ToString());
            int GoodsId = prams.GetInt("GoodsId", 0);
            if (GoodsId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            var model = offlineGoodsModule.GetProductGoodsInfo(GoodsId, req.TenantId, req.MallBaseId);
            return ApiResult.Success("", new
            {
                model?.Id,
                model?.Name,
                model?.CarouselImageList,
                model?.VideoAddress,
                model?.CustomShareTitles,
                model?.CustomShareImage,
                model?.GoodsStatus,
                model?.Sort,
                model?.SellingPrice,
                model?.OriginalPrice,
                model?.CostPrice,
                model?.IsAreaBuy,
                model?.IntegralPresent,
                model?.IntegralPresentType,
                model?.PointsDeduction,
                model?.PointsDeductionType,
                model?.IsMultipleDeduction,
                model?.GoodsDetails,
                model?.SeparateDistribution,
                model?.SeparateDistributionType,
                model?.SeparateDistributionMoneyType,
                model?.EnjoyMember,
                model?.SeparateSetMember,
                model?.SupplierId,
                model?.Commission,
                model?.IsLiveGoods,
                CategoryList = model?.CategoryList.Select(x => new
                {
                    x.Id,
                    x.CategoryId,
                    x.CategoryName
                }),
                AreaList = model?.AreaList.Select(x => new
                {
                    x.Id,
                    x.AreaId,
                    x.AreaName,
                    x.AreaType
                }),
                DistributionCommissionList = model?.DistributionCommissionList.Select(x => new
                {
                    x.Id,
                    x.DistributorGrade,
                    x.OneCommission,
                    x.SpecificationSort,
                    x.ThreeCommission,
                    x.TwoCommission
                }),
                DistributionCommissionTreeList = model?.DistributionCommissionTreeList.Select(x => new
                {
                    x.Id,
                    x.SpecificationSort,
                    x.AttrList,
                    GradeCommissionList = x.GradeCommissionList.Select(y => new
                    {
                        y.DistributorGrade,
                        y.OneCommission,
                        y.ThreeCommission,
                        y.TwoCommission
                    })
                }),
                MemberPriceList = model?.MemberPriceList.Select(x => new
                {
                    x.Id,
                    x.MemberGrade,
                    x.MemberPrice,
                    x.SpecificationSort
                }),
                MemberPriceTreeList = model?.MemberPriceTreeList.Select(x => new
                {
                    x.Id,
                    x.SpecificationSort,
                    x.AttrList,
                    GradePriceList = x.GradePriceList.Select(y => new
                    {
                        y.MemberGrade,
                        y.MemberPrice
                    })
                }),
                model?.Advertising,
                model?.SubName,
                model?.MarketingLogo,
                model?.SiteId,
                model?.GuideId,
                model?.CarId,
                model?.CarColorId,
                model?.CarNumber,
                model?.CarBuyYear,
                model?.CarType,
                CarTypeName = model?.CarType.GetEnumName(),
                model?.UseDay,
                model?.LineName,
                model?.LineDescriptionList,
                model?.IsSpell,
                model?.RideNum,
                model?.AdvanceDay,
                model?.TargetDateList,
                model?.IntegralComment,
                model?.IntegralCommentType,
                model?.GoodsPageType,
                GoodsPageTypeName = model?.GoodsPageType.GetEnumName() ?? "",
                DepositMoney=model?.DepositMoney??0,
                model?.IsChooseServicePerson,
                model?.StoresIds,
                StoresList= model?.StoresList??new List<int> (),
                model?.ShelvesDate,
                model?.DownDate,
                model?.Unit,
                model?.SalesNum,
                model?.Remark,
                model?.VideoType,
                model?.LimitBuyGoodsNum,
                model?.ServiceTime,
            });
        }

        /// <summary>
        /// 新增修改商品信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetGoodsInfo()
        {
            var parms = RequestParm;
            RB_Goods_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Extend>(parms.msg.ToString());
            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            if (string.IsNullOrEmpty(demodel.Name))
            {
                return ApiResult.ParamIsNull("请输入商品名称");
            }
            if (demodel.CarouselImageList == null || !demodel.CarouselImageList.Any())
            {
                return ApiResult.ParamIsNull("请添加商品轮播图");
            }
            demodel.CarouselImage = JsonConvert.SerializeObject(demodel.CarouselImageList.Select(x => x.Path));
            if ((demodel.SellingPrice ?? 0) < 0)
            {
                return ApiResult.ParamIsNull("请输入售价");
            }
            if ((demodel.OriginalPrice ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请输入原价");
            }
            demodel.IsSpell ??= 1;
            demodel.AdvanceDay ??= 0;

            demodel.IsCustomSpecification ??= 2;
            demodel.DefaultSpecificationName = "默认";
            demodel.InventoryNum ??= 0;
            List<Model.Extend.User.RB_Distributor_Grade_Extend> DGradeList = null;
            List<Model.Extend.User.RB_Member_Grade_Extend> MGradeList = null;
            demodel.VideoAddress ??= "";
            demodel.CustomShareTitles ??= "";
            demodel.CustomShareImage ??= "";
            demodel.GoodsStatus ??= 2;
            demodel.Sort ??= 0;
            demodel.CostPrice ??= 0;
            demodel.IsGoodsNegotiable ??= 2;
            demodel.SalesNum ??= 0;
            demodel.GoodsNumbers ??= "";
            demodel.GoodsWeight ??= 0;
            demodel.IsDefaultService ??= 1;
            if (demodel.IsDefaultService == 2)
            {
                if (demodel.ServiceList == null || !demodel.ServiceList.Any())
                {
                    return ApiResult.ParamIsNull("请选择商品服务");
                }
                demodel.GoodsService = JsonConvert.SerializeObject(demodel.ServiceList.Select(x => x.Id));
            }
            else
            {
                demodel.GoodsService = "[]";
            }
            demodel.FreightId ??= 0;
            demodel.FormsId ??= 0;
            demodel.LimitBuyGoodsNum ??= -1;
            demodel.LimitBuyOrderNum ??= -1;
            demodel.FullNumPinkage ??= 0;
            demodel.FullMoneyPinkage ??= 0;

            demodel.IsAreaBuy ??= 2;
            if (demodel.IsAreaBuy == 1)
            {
                if (demodel.AreaList == null || !demodel.AreaList.Any())
                {
                    return ApiResult.ParamIsNull("请选择区域");
                }
            }
            demodel.IntegralPresent ??= 0;
            demodel.IntegralPresentType ??= 1;
            demodel.PointsDeduction ??= 0;
            demodel.PointsDeductionType ??= 1;
            demodel.IsMultipleDeduction ??= 2;

            demodel.Status = 0;
            demodel.CreateDate = DateTime.Now;
            demodel.UpdateDate = DateTime.Now;

            demodel.SeparateDistribution ??= 2;
            demodel.SeparateDistributionType ??= 1;
            if (demodel.SeparateDistribution == 1)
            {
                //获取所有分销商等级
                if (DGradeList == null)
                {
                    DGradeList = offlineGoodsModule.GetDistributorGradeList(new Model.Extend.User.RB_Distributor_Grade_Extend() { Enabled = 1, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                    DGradeList.Add(new Model.Extend.User.RB_Distributor_Grade_Extend()
                    {
                        Grade = 0,
                        Name = "默认等级",
                        Id = 0
                    });
                }
                if (demodel.SeparateDistributionType == 1)
                {
                    if (demodel.DistributionCommissionList == null || !demodel.DistributionCommissionList.Any())
                    {
                        return ApiResult.ParamIsNull("请传递分销佣金列表");
                    }
                    //转换
                    List<RB_Goods_DistributionCommission_Extend> Rlist = new List<RB_Goods_DistributionCommission_Extend>();
                    foreach (var item in demodel.DistributionCommissionList)
                    {
                        if (item.GradeCommissionList == null || !item.GradeCommissionList.Any())
                        {
                            return ApiResult.ParamIsNull("请传递分销佣金列表");
                        }
                        foreach (var qitem in item.GradeCommissionList)
                        {
                            Rlist.Add(new RB_Goods_DistributionCommission_Extend()
                            {
                                DistributorGrade = qitem.DistributorGrade,
                                Id = 0,
                                SpecificationSort = item.SpecificationSort,
                                OneCommission = qitem.OneCommission,
                                TwoCommission = qitem.TwoCommission,
                                ThreeCommission = qitem.ThreeCommission
                            });
                        }
                    }
                    if (Rlist.Any())
                    {
                        demodel.DistributionCommissionList = Rlist;
                    }
                    //普通设置  直接根据等级验证数量
                    if (DGradeList.Count() != demodel.DistributionCommissionList.Count())
                    {
                        return ApiResult.ParamIsNull("分销佣金列表数量不正确");
                    }
                    foreach (var item in DGradeList)
                    {
                        var defaultModel = demodel.DistributionCommissionList.Where(x => x.DistributorGrade == item.Id).FirstOrDefault();
                        if (defaultModel == null)
                        {
                            return ApiResult.ParamIsNull("分销佣金" + item.Name + "不存在");
                        }
                        defaultModel.OneCommission ??= 0;
                        defaultModel.TwoCommission ??= 0;
                        defaultModel.ThreeCommission ??= 0;
                        defaultModel.SpecificationSort = "";
                    }
                }
                else
                {
                    if (demodel.IsCustomSpecification != 1)
                    {
                        return ApiResult.ParamIsNull("无法开启详细设置");
                    }
                }
            }
            demodel.SeparateDistributionMoneyType ??= 1;
            demodel.EnjoyMember ??= 2;
            demodel.SeparateSetMember ??= 2;
            if (demodel.EnjoyMember == 1 && demodel.SeparateSetMember == 1)
            {
                //获取所有会员等级
                if (MGradeList == null)
                {
                    MGradeList = offlineGoodsModule.GetMemberGradeList(new Model.Extend.User.RB_Member_Grade_Extend() { Enabled = 1, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                }
                if (!MGradeList.Any())
                {
                    return ApiResult.ParamIsNull("单独设置会员价需先添加会员等级");
                }
                if (demodel.IsCustomSpecification == 2)
                {
                    if (demodel.MemberPriceList == null || !demodel.MemberPriceList.Any())
                    {
                        return ApiResult.ParamIsNull("请传递会员价格列表");
                    }
                    //转换
                    List<RB_Goods_MemberPrice_Extend> Rlist = new List<RB_Goods_MemberPrice_Extend>();
                    foreach (var item in demodel.MemberPriceList)
                    {
                        if (item.GradePriceList == null || !item.GradePriceList.Any())
                        {
                            return ApiResult.ParamIsNull("请传递会员价格列表");
                        }
                        foreach (var qitem in item.GradePriceList)
                        {
                            Rlist.Add(new RB_Goods_MemberPrice_Extend()
                            {
                                MemberGrade = qitem.MemberGrade,
                                Id = 0,
                                SpecificationSort = item.SpecificationSort,
                                MemberPrice = qitem.MemberPrice
                            });
                        }
                    }
                    if (Rlist.Any())
                    {
                        demodel.MemberPriceList = Rlist;
                    }
                    if (MGradeList.Count() != demodel.MemberPriceList.Count())
                    {
                        return ApiResult.ParamIsNull("会员价格列表数量不正确");
                    }
                    foreach (var item in MGradeList)
                    {
                        var defaultModel = demodel.MemberPriceList.Where(x => x.MemberGrade == item.Grade).FirstOrDefault();
                        if (defaultModel == null)
                        {
                            return ApiResult.ParamIsNull("会员价格" + item.Name + "不存在");
                        }
                        defaultModel.MemberPrice ??= 0;
                        defaultModel.SpecificationSort = "";
                    }
                }
            }
            demodel.IsQuickBuy ??= 2;
            demodel.IsSellWell ??= 2;
            demodel.GoodsType ??= Common.Enum.Goods.OrderTypeEnum.SDGoods;
            demodel.GoodsStatus ??= 2;

            demodel.IsProxy ??= 2;
            demodel.ProxyType ??= 1;
            demodel.ProxyRises ??= 0;
            demodel.ProxyMoney ??= 0;
            demodel.IsProcurement = 2;//新增时
            demodel.PresentFXGrade ??= 0;//赠送粉象等级
            demodel.PresentFXMonth ??= 0;
            demodel.Advertising ??= "";//广告词
            demodel.SubName ??= "";//副标题
            demodel.IsLiveGoods ??= 2;//是否直播商品  1是  2否
            demodel.SendArea ??= "";//发货地
            demodel.GoodsClassify = 1;
            demodel.IntegralComment ??= 0;//评论反积分
            demodel.IntegralCommentType ??= 1;
            demodel.GoodsPageType ??= GoodsPageTypeEnum.All;
            bool flag = offlineGoodsModule.SetProductGoodsInfo(demodel);
            return flag ? ApiResult.Success() : ApiResult.Failed();

        }

        /// <summary>
        /// 删除商品
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelGoodsInfo()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int GoodsId = parms.GetInt("GoodsId", 0);
            if (GoodsId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            bool flag = offlineGoodsModule.DelProcudtGoodsInfo(GoodsId, req.TenantId, req.MallBaseId);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 上下架商品
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetGoodsStatusInfo()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int GoodsId = parms.GetInt("GoodsId", 0);
            if (GoodsId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            bool flag = offlineGoodsModule.SetGoodsStatusInfo(GoodsId, req.TenantId, req.MallBaseId);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 批量上下架商品
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetGoodsBatchStatusInfo()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            string GoodsIds = parms.GetStringValue("GoodsIds");
            int Type = parms.GetInt("Type", 1);//类型 1上架  2下架
            if (string.IsNullOrEmpty(GoodsIds))
            {
                return ApiResult.ParamIsNull();
            }
            bool flag = offlineGoodsModule.SetGoodsBatchStatusInfo(GoodsIds, Type, req.TenantId, req.MallBaseId);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 我的线下服务订单分页列表【小程序】
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetOfflineGoodsMyOrderPageList()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Goods_Order_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Order_Extend>(parms.msg.ToString());
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.UserId = userInfo.UserId;
            demodel.Recycled = 2;
            demodel.OrderClassify = 3;
            if (demodel.OrderStatus == Common.Enum.Goods.OrderStatusEnum.WaitSendGoods)
            {
                demodel.OrderStatusIds = "2,6";//待处理也是待发货状态才有的
                demodel.OrderStatus = 0;
            }
            var list = orderModule.GetOfflineServiceOrderPageListModule(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            //获取订阅消息
            var miniModel = programModule.GetMiniProgramModule(new RB_MiniProgram_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });

            List<string> template_message_list = new List<string>();

            if (miniModel != null)
            {
                if (!string.IsNullOrWhiteSpace(miniModel.RefundTpl))
                {
                    template_message_list.Add(miniModel.RefundTpl);
                }
                if (!string.IsNullOrWhiteSpace(miniModel.OrderCancelTpl))
                {
                    template_message_list.Add(miniModel.OrderCancelTpl);
                }
            }
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                template_message_list,
                x.OrderId,
                x.OrderNo,
                x.Income,
                x.CouponMoney,
                x.PaymentWay,
                PaymentWayName = x.PaymentWay.GetEnumName(),
                DetailList = x.DetailList.Select(y => new
                {
                    y.Id,
                    y.GoodsId,
                    y.CoverImagePath,
                    y.OrderType,
                    OrderTypeName = y.OrderType.GetEnumName(),
                    y.GoodsName,
                    y.ProductCode,
                    y.Final_Price,
                    y.Number,
                    y.IsComment,
                    y.ServiceDate,
                    y.ServiceTime,
                    y.GoodServiceTime,
                    y.ServicepersonalName
                }),
                x.OrderStatus,
                OrderStatusName = x.OrderStatus.GetEnumName(),
                x.TenantId,
                x.MallBaseId,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                x.StoreName,
                x.StoresAddress,
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 获取我的订单详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetOfflineOrderInfo()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parms = JObject.Parse(req.msg.ToString());
            int OrderId = parms.GetInt("OrderId", 0);
            //HK2020-08-08新增
            if (parms.GetInt("NewUserId") > 0)
            {
                userInfo.UserId = parms.GetInt("NewUserId");
            }
            if (OrderId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            return orderModule.GetOfflineMyOrderModule(OrderId, userInfo.UserId, userInfo.TenantId, userInfo.MallBaseId);
        }
    }
}
