using Mall.AOP;
using Mall.Common.API;
using Mall.Common.Enum.Goods;
using Mall.Common.Plugin;
using Mall.Model.Extend.Product;
using Mall.Module.Product;
using Mall.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;

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

        private readonly ProductModule productModule = AOPHelper.CreateAOPObject<ProductModule>();
        private readonly ActivityModule activityModule = new ActivityModule();


        #region 素材管理
        /// <summary>
        /// 获取素材分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMaterialInfoPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Material_Info_Extend demodel = JsonConvert.DeserializeObject<RB_Material_Info_Extend>(parms.msg.ToString());

            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            var list = productModule.GetMaterialInfoPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.Name,
                x.Type,
                x.GroupId,
                x.Path,
                x.Image,
                x.VideoTime,
                x.WithHeight,
                x.Recycled,
                x.PathType,
                x.TenantId,
                x.MallBaseId,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd") : ""
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 新增素材信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetMaterialInfo()
        {
            var parms = RequestParm;
            RB_Material_Info_Extend demodel = JsonConvert.DeserializeObject<RB_Material_Info_Extend>(parms.msg.ToString());
            if (string.IsNullOrEmpty(demodel.Name))
            {
                return ApiResult.ParamIsNull("请输入素材名称");
            }
            if (demodel.Type != 1 && demodel.Type != 2 && demodel.Type != 3)
            {
                return ApiResult.ParamIsNull("请传递类型");
            }
            if ((demodel.GroupId ?? 0) < 0)
            {
                return ApiResult.ParamIsNull("请输入分组");
            }
            if (string.IsNullOrEmpty(demodel.Path))
            {
                return ApiResult.ParamIsNull("请传递文件路径");
            }
            //HK2020-09-01修改
            //if (demodel.Type == 1)
            //{
            //    demodel.Path = Config.GetFilePath(demodel.Path);
            //    demodel.Image = Config.GetFilePath(demodel.Image);
            //}

            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            demodel.CreateDate = DateTime.Now;
            demodel.UpdateDate = DateTime.Now;
            demodel.Status = 0;
            demodel.Recycled = 1;
            bool flag = productModule.SetMaterialInfo(demodel);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 新增素材信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetGetMaterialInfo()
        {
            var parms = RequestParm;
            RB_Material_Info_Extend demodel = JsonConvert.DeserializeObject<RB_Material_Info_Extend>(parms.msg.ToString());
            if (string.IsNullOrEmpty(demodel.Name))
            {
                return ApiResult.ParamIsNull("请输入素材名称");
            }
            if (demodel.Type != 1 && demodel.Type != 2 && demodel.Type != 3)
            {
                return ApiResult.ParamIsNull("请传递类型");
            }
            if ((demodel.GroupId ?? 0) < 0)
            {
                return ApiResult.ParamIsNull("请输入分组");
            }
            if (string.IsNullOrEmpty(demodel.Path))
            {
                return ApiResult.ParamIsNull("请传递文件路径");
            }
            //HK2020-09-01修改
            //if (demodel.Type == 1)
            //{
            //    demodel.Path = Config.GetFilePath(demodel.Path);
            //    demodel.Image = Config.GetFilePath(demodel.Image);
            //}

            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            demodel.CreateDate = DateTime.Now;
            demodel.UpdateDate = DateTime.Now;
            demodel.Status = 0;
            demodel.Recycled = 1;
            bool flag = productModule.SetMaterialInfo(demodel);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 获取素材分组列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMaterialGroupList()
        {
            var parms = RequestParm;
            RB_Material_Group_Extend demodel = JsonConvert.DeserializeObject<RB_Material_Group_Extend>(parms.msg.ToString());

            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            var list = productModule.GetMaterialGroupList(demodel);
            return ApiResult.Success("", list.Select(x => new
            {
                x.Id,
                x.Name,
                x.Type,
                x.Sort,
                x.Recycled,
                x.TenantId,
                x.MallBaseId,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd") : ""
            }));
        }

        /// <summary>
        /// 新增修改分组
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetMaterialGroupInfo()
        {
            var parms = RequestParm;
            RB_Material_Group_Extend demodel = JsonConvert.DeserializeObject<RB_Material_Group_Extend>(parms.msg.ToString());
            if (string.IsNullOrEmpty(demodel.Name))
            {
                return ApiResult.ParamIsNull("请输入分组名称");
            }
            if (demodel.Type != 1 && demodel.Type != 2 && demodel.Type != 3)
            {
                return ApiResult.ParamIsNull("请传递类型");
            }

            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            demodel.CreateDate = DateTime.Now;
            demodel.UpdateDate = DateTime.Now;
            demodel.Status = 0;
            demodel.Recycled = 1;
            bool flag = productModule.SetMaterialGroupInfo(demodel);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 设置分组回收
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetMaterialGroupRecycled()
        {
            var requestParm = RequestParm;
            var parms = JObject.Parse(requestParm.msg.ToString());
            int GroupId = parms.GetInt("GroupId", 0);
            if (GroupId < 0)
            {
                return ApiResult.ParamIsNull("请传递分组id");
            }

            bool flag = productModule.SetMaterialGroupRecycled(GroupId, requestParm.uid, requestParm.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 删除分组信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelMaterialGroupInfo()
        {
            var requestParm = RequestParm;
            var parms = JObject.Parse(requestParm.msg.ToString());
            int GroupId = parms.GetInt("GroupId", 0);
            if (GroupId < 0)
            {
                return ApiResult.ParamIsNull("请传递分组id");
            }

            bool flag = productModule.DelMaterialGroupInfo(GroupId, requestParm.uid, requestParm.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 设置分组还原
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetMaterialGroupRestore()
        {
            var requestParm = RequestParm;
            var parms = JObject.Parse(requestParm.msg.ToString());
            int GroupId = parms.GetInt("GroupId", 0);
            if (GroupId < 0)
            {
                return ApiResult.ParamIsNull("请传递分组id");
            }

            bool flag = productModule.SetMaterialGroupRestore(GroupId, requestParm.uid, requestParm.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }


        /// <summary>
        /// 设置素材回收
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetMaterialInfoRecycled()
        {
            var requestParm = RequestParm;
            var parms = JObject.Parse(requestParm.msg.ToString());
            string MaterialIds = parms.GetStringValue("MaterialIds");
            if (string.IsNullOrEmpty(MaterialIds))
            {
                return ApiResult.ParamIsNull("请传递素材ids");
            }

            bool flag = productModule.SetMaterialInfoRecycled(MaterialIds, requestParm.uid, requestParm.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 删除素材信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelMaterialInfo()
        {
            var requestParm = RequestParm;
            var parms = JObject.Parse(requestParm.msg.ToString());
            string MaterialIds = parms.GetStringValue("MaterialIds");
            if (string.IsNullOrEmpty(MaterialIds))
            {
                return ApiResult.ParamIsNull("请传递素材ids");
            }

            bool flag = productModule.DelMaterialInfo(MaterialIds, requestParm.uid, requestParm.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 设置素材还原
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetMaterialInfoRestore()
        {
            var requestParm = RequestParm;
            var parms = JObject.Parse(requestParm.msg.ToString());
            string MaterialIds = parms.GetStringValue("MaterialIds");
            if (string.IsNullOrEmpty(MaterialIds))
            {
                return ApiResult.ParamIsNull("请传递素材ids");
            }

            bool flag = productModule.SetMaterialInfoRestore(MaterialIds, requestParm.uid, requestParm.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 设置素材转移
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetMaterialInfoTransfer()
        {
            var requestParm = RequestParm;
            var parms = JObject.Parse(requestParm.msg.ToString());
            string MaterialIds = parms.GetStringValue("MaterialIds");
            int GroupId = parms.GetInt("GroupId", 0);
            int Type = parms.GetInt("Type", 0);
            if (string.IsNullOrEmpty(MaterialIds))
            {
                return ApiResult.ParamIsNull("请传递素材ids");
            }
            if (GroupId <= 0)
            {
                return ApiResult.ParamIsNull("请传递分组id");
            }

            bool flag = productModule.SetMaterialInfoTransfer(MaterialIds, GroupId, Type, requestParm.uid, requestParm.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }






        #endregion

        #region 商品分类

        /// <summary>
        /// 获取商品分类树形列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetProductCategoryPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Product_Category_Extend demodel = JsonConvert.DeserializeObject<RB_Product_Category_Extend>(parms.msg.ToString());

            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            var list = productModule.GetProductCategoryPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.Name,
                x.Tier,
                x.ParentId,
                x.Sort,
                x.Icon,
                x.IconPath,
                x.BigIcon,
                x.BigIconPath,
                x.AdvertisingImage,
                x.AdvertisingImagePath,
                x.AdvertisingAddress,
                x.Enabled,
                x.IsShow,
                x.TenantId,
                x.MallBaseId,
                CategoryPageTypeStr = x.CategoryPageType.GetEnumName(),
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd") : ""
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 获取分类树形结构
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetProductCategoryTreeList()
        {
            var parms = RequestParm;
            RB_Product_Category_Extend demodel = JsonConvert.DeserializeObject<RB_Product_Category_Extend>(parms.msg.ToString());

            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            var list = productModule.GetProductCategoryTreeList(demodel);
            return ApiResult.Success("", list);
        }


        /// <summary>
        /// 获取分类详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetProductCategoryInfo()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int CategoryId = parms.GetInt("CategoryId", 0);
            if (CategoryId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            var model = productModule.GetProductCategoryInfo(CategoryId);
            return ApiResult.Success("", new
            {
                model.Id,
                model.Name,
                model.Tier,
                model.ParentId,
                model.Sort,
                model.Icon,
                model.IconPath,
                model.BigIcon,
                model.BigIconPath,
                model.AdvertisingImage,
                model.AdvertisingImagePath,
                model.AdvertisingAddress,
                model.Enabled,
                model.IsShow,
                model.Parent1Name,
                model.Parent2Name,
                model.TenantId,
                model.MallBaseId,
                model.IsForeignShare,
                model.CategoryPageType,
                CreateDate = model.CreateDate.HasValue ? model.CreateDate.Value.ToString("yyyy-MM-dd") : ""
            });
        }

        /// <summary>
        /// 保存分类
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetProductCategoryInfo()
        {
            var req = RequestParm;
            RB_Product_Category_Extend demodel = JsonConvert.DeserializeObject<RB_Product_Category_Extend>(req.msg.ToString());
            if ((demodel.Tier ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请选择层级");
            }
            if (string.IsNullOrEmpty(demodel.Name))
            {
                return ApiResult.ParamIsNull("请输入分类名称");
            }
            if (!demodel.Sort.HasValue)
            {
                return ApiResult.ParamIsNull("请输入排序");
            }
            if (demodel.Tier == 1)
            {
                demodel.ParentId = 0;
            }
            else if (demodel.Tier > 1)
            {
                if ((demodel.ParentId ?? 0) <= 0)
                {
                    return ApiResult.ParamIsNull("请选择上级");
                }
            }

            demodel.TenantId = Convert.ToInt32(req.uid);
            demodel.MallBaseId = req.MallBaseId;
            demodel.Icon ??= 0;
            demodel.BigIcon ??= 0;
            demodel.AdvertisingImage ??= 0;
            demodel.AdvertisingAddress ??= "";
            demodel.Enabled ??= 1;
            demodel.IsShow ??= 1;
            demodel.Status ??= 0;
            demodel.IsForeignShare ??= 2;
            demodel.CreateDate = DateTime.Now;
            demodel.UpdateDate = DateTime.Now;
            bool flag = productModule.SetProductCategoryInfo(demodel);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }

        }

        /// <summary>
        /// 删除分类
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelProductCategoryInfo()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int CategoryId = parms.GetInt("CategoryId", 0);
            if (CategoryId <= 0)
            {
                return ApiResult.ParamIsNull("请选择需删除分类id");
            }

            bool flag = productModule.DelProductCategoryInfo(CategoryId, req.TenantId, req.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 保存分类转移
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetProductCategoryTransfer()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int CategoryId = parms.GetInt("CategoryId", 0);
            int ParentId = parms.GetInt("ParentId", 0);
            if (CategoryId <= 0)
            {
                return ApiResult.ParamIsNull("请选择需转移分类id");
            }
            if (ParentId < 0)
            {
                return ApiResult.ParamIsNull("请选择转入分类id");
            }
            if (CategoryId == ParentId)
            {
                return ApiResult.ParamIsNull("不能转入同一分类下");
            }

            var list = productModule.GetProductCategoryForALLChlid(CategoryId, Convert.ToInt32(req.uid), req.MallBaseId);
            if (list.Where(x => x.Id == ParentId).Any())
            {
                return ApiResult.ParamIsNull("不能转入当前分类的子集分类");
            }
            var model = list.Where(x => x.Id == CategoryId).FirstOrDefault();
            if (model == null)
            {
                return ApiResult.ParamIsNull("分类不存在，请核实后再试");
            }
            if (model.ParentId == ParentId)
            {
                return ApiResult.ParamIsNull("已在当前分类下，未转移");
            }

            bool flag = productModule.SetProductCategoryTransfer(model, ParentId, list);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 保存分类排序
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetProductCategorySort()
        {
            var req = RequestParm;
            List<RB_Product_CategorySort> delist = JsonConvert.DeserializeObject<List<RB_Product_CategorySort>>(req.msg.ToString());
            if (delist == null || !delist.Any())
            {
                return ApiResult.ParamIsNull();
            }

            bool flag = productModule.SetProductCategorySort(delist, req.TenantId, req.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 获取分类样式
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetProductCategoryStyleInfo()
        {
            var parms = RequestParm;

            var model = productModule.GetProductCategoryStyleInfo(parms.TenantId, parms.MallBaseId);
            return ApiResult.Success("", new
            {
                model.Id,
                model.Type,
                model.Style,
                model.CategoryNum,
                model.RowNum,
                UpdateDate = model.UpdateDate.Value.ToString("yyyy-MM-dd HH:mm:ss")
            });
        }

        /// <summary>
        /// 保存分类样式
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetProductCategoryStyleInfo()
        {
            var req = RequestParm;
            RB_Product_CategoryStyle_Extend demodel = JsonConvert.DeserializeObject<RB_Product_CategoryStyle_Extend>(req.msg.ToString());

            demodel.CategoryNum ??= 1;
            demodel.CreateDate = DateTime.Now;
            demodel.MallBaseId = req.MallBaseId;
            demodel.RowNum ??= 1;
            demodel.Style ??= 1;
            demodel.TenantId = req.TenantId;
            demodel.Type ??= 1;
            demodel.UpdateDate = DateTime.Now;
            bool flag = productModule.SetProductCategoryStyleInfo(demodel);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 分类显示 + 影藏
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetProductCategoryShow()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int IsShow = parms.GetInt("IsShow", 2);//2 显示 1隐藏

            bool flag = productModule.SetProductCategoryShow(IsShow, req.TenantId, req.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        #endregion

        #region 商品规格

        /// <summary>
        /// 获取商品规格分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetProductSpecificationPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Product_Specification_Extend demodel = JsonConvert.DeserializeObject<RB_Product_Specification_Extend>(parms.msg.ToString());

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = productModule.GetProducSpecificationPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.Name,
                x.SpecList,
                x.TenantId,
                x.MallBaseId,
                UpdateDate = x.UpdateDate.HasValue ? x.UpdateDate.Value.ToString("yyyy-MM-dd") : ""
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 获取规格列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetProductSpecificationList()
        {
            var parms = RequestParm;
            RB_Product_Specification_Extend demodel = JsonConvert.DeserializeObject<RB_Product_Specification_Extend>(parms.msg.ToString());

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = productModule.GetProducSpecificationList(demodel);
            return ApiResult.Success("", list.Select(x => new
            {
                x.Id,
                x.Name,
                x.SpecList,
                x.TenantId,
                x.MallBaseId,
                UpdateDate = x.UpdateDate.HasValue ? x.UpdateDate.Value.ToString("yyyy-MM-dd") : ""
            }));
        }

        /// <summary>
        /// 保存修改规格
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetProductSpecificationInfo()
        {
            var req = RequestParm;
            RB_Product_Specification_Extend demodel = JsonConvert.DeserializeObject<RB_Product_Specification_Extend>(req.msg.ToString());
            if (string.IsNullOrEmpty(demodel.Name))
            {
                return ApiResult.ParamIsNull("请输入规格名");
            }
            if (demodel.SpecList == null || !demodel.SpecList.Any())
            {
                return ApiResult.ParamIsNull("请输入规格值");
            }
            demodel.Content = JsonConvert.SerializeObject(demodel.SpecList);
            demodel.TenantId = req.TenantId;
            demodel.MallBaseId = req.MallBaseId;
            demodel.CreateDate = DateTime.Now;
            demodel.UpdateDate = DateTime.Now;
            demodel.Status = 0;
            bool flag = productModule.SetProductSpecificationInfo(demodel);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 删除商品规格
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelProductSpecificationInfo()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int SpecificationId = parms.GetInt("SpecificationId", 0);
            if (SpecificationId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            bool flag = productModule.DelProductSpecificationInfo(SpecificationId, req.TenantId, req.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        #endregion

        #region 快速购买
        /// <summary>
        /// 获取商品快速购买分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetProductQuickBuyPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Product_QuickBuy_Extend demodel = JsonConvert.DeserializeObject<RB_Product_QuickBuy_Extend>(parms.msg.ToString());

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = productModule.GetProductQuickBuyPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.CategoryId,
                x.CategoryName,
                x.Icon,
                x.IconPath,
                x.Sort,
                x.TenantId,
                x.MallBaseId,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : ""
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 获取快速购买列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetProductQuickBuyList()
        {
            var parms = RequestParm;
            RB_Product_QuickBuy_Extend demodel = JsonConvert.DeserializeObject<RB_Product_QuickBuy_Extend>(parms.msg.ToString());

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = productModule.GetProductQuickBuyList(demodel);
            return ApiResult.Success("", list.Select(x => new
            {
                x.Id,
                x.CategoryId,
                x.CategoryName,
                x.Icon,
                x.IconPath,
                x.Sort,
                x.TenantId,
                x.MallBaseId
            }));
        }

        /// <summary>
        /// 保存修改快速购买
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetProductQuickBuyInfo()
        {
            var req = RequestParm;
            RB_Product_QuickBuy_Extend demodel = JsonConvert.DeserializeObject<RB_Product_QuickBuy_Extend>(req.msg.ToString());
            if ((demodel.CategoryId ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请选择分类");
            }
            if (!demodel.Sort.HasValue)
            {
                return ApiResult.ParamIsNull("请输入排序");
            }
            if (productModule.ValidateQuickBuyCategory(demodel.Id, demodel.CategoryId, req.TenantId, req.MallBaseId))
            {
                return ApiResult.Failed("该分类已存在，无法再次添加");
            }

            demodel.TenantId = req.TenantId;
            demodel.MallBaseId = req.MallBaseId;
            demodel.CreateDate = DateTime.Now;
            demodel.UpdateDate = DateTime.Now;
            demodel.Status = 0;
            bool flag = productModule.SetProductQuickBuyInfo(demodel);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 删除商品快速购买
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelProductQuickBuyInfo()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int QuickBuyId = parms.GetInt("QuickBuyId", 0);
            if (QuickBuyId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            bool flag = productModule.DelProductQuickBuyInfo(QuickBuyId, req.TenantId, req.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }


        #endregion

        #region 推荐设置

        /// <summary>
        /// 获取推荐设置详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetProductRecommendSetInfo()
        {
            var req = RequestParm;
            var model = productModule.GetProductRecommendSetInfo(req.TenantId, req.MallBaseId);
            return ApiResult.Success("", new
            {
                model.Id,
                model.DetailRecommendStatus,
                model.DetailRecommendSame,
                model.DetailRecommendNum,
                model.OrderCompleteStatus,
                model.IsOrderRecommend,
                model.OrderProductIds,
                model.OrderProductList,
                model.CommentRecommentStatus,
                model.IsCommentRecommend,
                model.CommentProductIds,
                model.CommentProductList
            });
        }

        /// <summary>
        /// 保存推荐设置
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetProductRecommendSetInfo()
        {
            var req = RequestParm;
            RB_Product_Recommend_Extend demodel = JsonConvert.DeserializeObject<RB_Product_Recommend_Extend>(req.msg.ToString());

            if (demodel.IsOrderRecommend == 1)
            {
                if (demodel.OrderProductList == null || !demodel.OrderProductList.Any())
                {
                    return ApiResult.ParamIsNull("请选择自定义推荐商品");
                }
                demodel.OrderProductIds = string.Join(",", demodel.OrderProductList.Select(x => x.Id).Distinct());
            }
            if (demodel.IsCommentRecommend == 1)
            {
                if (demodel.CommentProductList == null || !demodel.CommentProductList.Any())
                {
                    return ApiResult.ParamIsNull("请选择自定义推荐商品");
                }
                demodel.CommentProductIds = string.Join(",", demodel.CommentProductList.Select(x => x.Id).Distinct());
            }

            demodel.TenantId = req.TenantId;
            demodel.MallBaseId = req.MallBaseId;
            demodel.OrderProductIds ??= "";
            demodel.CommentProductIds ??= "";
            demodel.CreateDate = DateTime.Now;
            demodel.UpdateDate = DateTime.Now;
            bool flag = productModule.SetProductRecommendSetInfo(demodel);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        #endregion

        #region 商品服务

        /// <summary>
        /// 获取商品服务分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetProductServicePageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Product_Service_Extend demodel = JsonConvert.DeserializeObject<RB_Product_Service_Extend>(parms.msg.ToString());

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = productModule.GetProductServicePageList(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.Remark,
                x.IsDefault,
                x.TenantId,
                x.MallBaseId,
                UpdateDate = x.UpdateDate.HasValue ? x.UpdateDate.Value.ToString("yyyy-MM-dd") : ""
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 获取服务列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetProductServiceList()
        {
            var parms = RequestParm;
            RB_Product_Service_Extend demodel = JsonConvert.DeserializeObject<RB_Product_Service_Extend>(parms.msg.ToString());

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = productModule.GetProductServiceList(demodel);
            return ApiResult.Success("", list.Select(x => new
            {
                x.Id,
                x.Name,
                x.Sort,
                x.Remark,
                x.IsDefault
            }));
        }

        /// <summary>
        /// 获取服务详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetProductServiceInfo()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int ServiceId = parms.GetInt("ServiceId", 0);
            if (ServiceId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            var model = productModule.GetProductServiceInfo(ServiceId);
            return ApiResult.Success("", new
            {
                model.Id,
                model.Name,
                model.Sort,
                model.Remark,
                model.IsDefault
            });
        }

        /// <summary>
        /// 保存修改服务
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetProductServiceInfo()
        {
            var req = RequestParm;
            RB_Product_Service_Extend demodel = JsonConvert.DeserializeObject<RB_Product_Service_Extend>(req.msg.ToString());
            if (string.IsNullOrEmpty(demodel.Name))
            {
                return ApiResult.ParamIsNull("请输入服务名称");
            }
            if (!demodel.Sort.HasValue)
            {
                return ApiResult.ParamIsNull("请输入排序");
            }

            demodel.TenantId = req.TenantId;
            demodel.MallBaseId = req.MallBaseId;
            demodel.IsDefault ??= 1;
            demodel.CreateDate = DateTime.Now;
            demodel.UpdateDate = DateTime.Now;
            demodel.Status = 0;
            bool flag = productModule.SetProductServiceInfo(demodel);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 删除商品服务
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelProductServiceInfo()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int ServiceId = parms.GetInt("ServiceId", 0);
            if (ServiceId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            bool flag = productModule.DelProductServiceInfo(ServiceId, req.TenantId, req.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        #endregion

        #region 商品列表

        /// <summary>
        /// 商品后台分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetProductGoodsPageList()
        {
            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"),
                IsSelectSellOut = parameters.GetInt("IsSelectSellOut"),
                CategoryIds = parameters.GetStringValue("CategoryIds"),
                Id = parameters.GetInt("Id"),
                StartTime = parameters.GetStringValue("StartTime"),
                EndTime = parameters.GetStringValue("EndTime"),
                OrderBy = parameters.GetInt("OrderBy"),
                RetailStore = parameters.GetInt("RetailStore", -1),
                CreateBy = parameters.GetInt("EmpId", -1),
                Q_GoodsEduType = parameters.GetInt("Q_GoodsEduType", 0),
                GoodsEduType = parameters.GetInt("GoodsEduType", 0),
                MaterialId = parameters.GetInt("MaterialId", 0)
            };

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            if (parms.TenantId == 1 && parms.MallBaseId == 1)
            {
                if (parameters.GetInt("IsOtherUpdateGoods", 0) > 0)
                {
                    demodel.CreateBy = -1;
                }
            }
            else
            {
                demodel.CreateBy = -1;
            }

            decimal MinProfitRate = 0;
            if (demodel.TenantId == 1)
            {
                //MinProfitRate = Convert.ToDecimal(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("MinProfitRate")["TenantId1"]);
            }
            if (demodel.IsSelectLowProfit == 1)
            {
                demodel.MinProfitRate = MinProfitRate;
            }
            var list = productModule.GetProductGoodsPageList(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.InventoryNum,
                x.SalesNum,
                x.GoodsBuyNum,
                x.IsQuickBuy,
                x.IsProxy,
                x.IsProcurement,
                x.ProcurementStatus,
                x.GoodsStatus,
                x.TenantId,
                x.MallBaseId,
                x.SendArea,
                x.Remark,
                GoodsPageTypeStr = x.GoodsPageType.GetEnumName(),
                CarouselImageList = x.CarouselImageList.Select(qitem => qitem.Path).ToList(),
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                x.IsNoTax,
                IsLowProfit = MinProfitRate > 0 ? x.MinProfitRate < MinProfitRate ? 1 : 2 : 2,
                x.CreateBy,
                x.SourceGoodsId,
                x.RetailStore,
                x.SupplierName,
                x.GoodsEduType,
                x.MaterialId
            });
            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 },
                    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;
                decimal MinProfitRate = 0;
                if (demodel.TenantId == 1)
                {
                    //MinProfitRate = Convert.ToDecimal(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("MinProfitRate")["TenantId1"]);
                }
                if (demodel.IsSelectLowProfit == 1)
                {
                    demodel.MinProfitRate = MinProfitRate;
                }
                var list = productModule.GetProductGoodsListForExcel(demodel);
                #region 组装数据
                int Num = 0;
                foreach (var item in list)
                {
                    Num++;
                    string GGZ = "";
                    string GGMX = "";
                    if (item.IsCustomSpecification == 1)
                    {
                        var obj = item.SpecificationList.Select(x => new
                        {
                            x.Id,
                            x.GoodsId,
                            x.Name,
                            x.Sort,
                            x.EnabledImage,
                            SpecificationValueList = x.SpecificationValueList.Select(z => new
                            {
                                z.Id,
                                z.GoodsId,
                                z.SpecificationId,
                                z.Name,
                                z.Image,
                                z.Sort
                            })
                        });
                        GGZ = JsonConvert.SerializeObject(obj);//序列化

                        GGMX = JsonConvert.SerializeObject(item.SpecificationPriceList.Select(x => new
                        {
                            x.Id,
                            x.GoodsId,
                            x.SpecificationSort,
                            x.SellingPrice,
                            x.InventoryNum,
                            x.GoodsWeight,
                            x.GoodsNumbers
                        }));
                    }
                    else
                    {
                        List<object> objList = new List<object>();
                        List<object> SpecificationValueList = new List<object>
                        {
                            new
                            {
                                Id = 0,
                                GoodsId = item.Id,
                                SpecificationId = 0,
                                Name = item.DefaultSpecificationName,
                                Image = "",
                                Sort = 0
                            }
                        };
                        objList.Add(new
                        {
                            Id = 0,
                            GoodsId = item.Id,
                            Name = "规格",
                            Sort = 0,
                            EnabledImage = 2,
                            SpecificationValueList
                        });
                        GGZ = JsonConvert.SerializeObject(objList);//序列化
                        List<object> SpecificationPriceList = new List<object>
                        {
                            new
                            {
                                Id = 0,
                                GoodsId = item.Id,
                                SpecificationSort = "",
                                item.SellingPrice,
                                item.InventoryNum,
                                item.GoodsWeight,
                                item.GoodsNumbers
                            }
                        };
                        GGMX = JsonConvert.SerializeObject(SpecificationPriceList);//序列化
                    }
                    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.Unit){ },
                            new ExcelColumn(value:(item.SellingPrice??0).ToString()){ },

                            new ExcelColumn(value:(item.IsCustomSpecification??2).ToString()){ },
                            new ExcelColumn(value:GGZ.ToString()){ },

                            new ExcelColumn(value:(item.InventoryNum??0).ToString()){ },
                            new ExcelColumn(value:(item.SalesNum??0).ToString()){ },
                            new ExcelColumn(value:(item.LimitBuyGoodsNum??0).ToString()){ },
                            new ExcelColumn(value:(item.FullNumPinkage??0).ToString()){ },
                            new ExcelColumn(value:(item.FullMoneyPinkage??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.LimitBuyOrderNum??0).ToString()){ },

                            new ExcelColumn(value:(item.IsAreaBuy??0).ToString()){ },
                            new ExcelColumn(value:AreaList.ToString()){ },
                            new ExcelColumn(value:GGMX.ToString()){ },

                            new ExcelColumn(value:(item.IsQuickBuy??0).ToString()){ },
                            new ExcelColumn(value:(item.IsSellWell??0).ToString()){ },
                            new ExcelColumn(value:(item.IsGoodsNegotiable??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 GetProductGoodsDialogList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Goods_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Extend>(parms.msg.ToString());
            JObject parameters = JObject.Parse(RequestParm.msg.ToString());
            int IsGetSpec = parameters.GetInt("IsGetSpec", 0);
            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = productModule.GetProductGoodsPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel, IsGetSpec: IsGetSpec);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.Name,
                x.CoverImage,
                x.CarouselImageList,
                x.SellingPrice,
                x.SalesNum,
                CategoryList = x.CategoryList.Select(y => new { y.Id, y.CategoryName }),
                x.InventoryNum,
                x.Sort,
                x.OriginalPrice,
                x.DefaultSpecificationName,
                x.GoodsNumbers,
                x.GoodsWeight,
                x.IsDefaultService,
                x.GoodsService,
                x.SpecificationList,
                x.SpecificationPriceList,
                x.SendArea,
                x.IsNoTax
            });
            return ApiResult.Success("", pagelist);
        }


        /// <summary>
        /// 获取商品列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetProductGoodsDialogList_V2()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Goods_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Extend>(parms.msg.ToString());
            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = productModule.GetProductGoodsDialogList_V2(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.Name,
                x.CoverImage,
                x.CarouselImageList,
                x.SellingPrice,
                CategoryList = x.CategoryList.Select(y => new { y.Id, y.CategoryName })
            });
            return ApiResult.Success("", pagelist);
        }



        /// <summary>
        /// 获取商品列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetProductGoodsDialogList_V3()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Goods_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Extend>(parms.msg.ToString());
            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = productModule.GetProductGoodsDialogList_V3(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.Name,
                x.CoverImage,
                x.CarouselImageList,
                x.SellingPrice,
                CategoryList = x.CategoryList.Select(y => new { y.Id, y.CategoryName })
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 获取商品列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetListByGoodsClassify()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Goods_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Extend>(parms.msg.ToString());
            JObject parameters = JObject.Parse(RequestParm.msg.ToString());
            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = productModule.GetListByGoodsClassify(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.Name,
                x.CoverImage,
                x.CarouselImageList,
                x.SellingPrice,
                x.SalesNum,
                x.InventoryNum,
                x.Sort,
                x.OriginalPrice,
                x.DefaultSpecificationName,
                x.GoodsNumbers,
                x.GoodsWeight,
                x.IsDefaultService,
                x.GoodsService,
                x.SpecificationList,
                x.SpecificationPriceList,
                x.SendArea,
                x.IsNoTax
            });
            return ApiResult.Success("", pagelist);
        }

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

            var model = productModule.GetProductGoodsInfo(GoodsId, req.TenantId, req.MallBaseId);
            object obj = new object();
            if (model != null)
            {
                var tempLogo = new MarketingLogoItem();
                if (!string.IsNullOrEmpty(model?.MarketingLogo))
                {
                    try
                    {
                        tempLogo = JsonHelper.DeserializeObject<MarketingLogoItem>(model?.MarketingLogo);
                    }
                    catch
                    {
                        tempLogo = new MarketingLogoItem();
                    }
                }
                obj = new
                {
                    model?.Id,
                    model?.Name,
                    model?.CarouselImage,
                    model?.VideoAddress,
                    model?.CustomShareTitles,
                    model?.CustomShareImage,
                    model?.CustomShareImagePath,
                    model?.GoodsStatus,
                    model?.InventoryNum,
                    model?.DefaultSpecificationName,
                    model?.IsCustomSpecification,
                    model?.Sort,
                    model?.SellingPrice,
                    model?.OriginalPrice,
                    model?.Unit,
                    model?.CostPrice,
                    model?.IsGoodsNegotiable,
                    model?.SalesNum,
                    model?.GoodsNumbers,
                    model?.GoodsWeight,
                    model?.IsDefaultService,
                    model?.GoodsService,
                    model?.FreightId,
                    model?.FreightName,
                    model?.FormsId,
                    model?.FormsName,
                    model?.LimitBuyGoodsNum,
                    model?.LimitBuyOrderNum,
                    model?.FullNumPinkage,
                    model?.FullMoneyPinkage,
                    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?.IsQuickBuy,
                    model?.SupplierId,
                    model?.IsProxy,
                    model?.ProxyType,
                    model?.ProxyRises,
                    model?.ProxyMoney,
                    model?.IsProcurement,
                    model?.Commission,
                    model?.IsLiveGoods,
                    model?.SendArea,
                    model?.Remark,
                    model?.GoodsPageType,
                    model?.IsNoTax,
                    CategoryList = model?.CategoryList.Select(x => new
                    {
                        x.Id,
                        x.CategoryId,
                        x.CategoryName
                    }),
                    SpecificationList = model?.SpecificationList.Select(x => new
                    {
                        x.Id,
                        x.EnabledImage,
                        x.Name,
                        x.Sort,
                        x.IsDateFormat,
                        SpecificationValueList = x.SpecificationValueList.Select(y => new
                        {
                            y.Id,
                            y.Image,
                            y.ImagePath,
                            y.Name,
                            y.Sort
                        })
                    }),
                    SpecificationPriceList = model?.SpecificationPriceList.Select(x => new
                    {
                        x.Id,
                        x.GoodsNumbers,
                        x.GoodsWeight,
                        x.InventoryNum,
                        x.SellingPrice,
                        x.SpecificationSort,
                        x.AttrList,
                        x.Commission,
                        x.CostMoney
                    }),
                    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?.CarouselImageList,
                    model?.ServiceList,
                    model?.PresentFXGrade,
                    model?.PresentFXMonth,
                    model?.Advertising,
                    model?.SubName,
                    MarketingLogo = tempLogo,
                    model?.ShelvesDate,
                    model?.DownDate,
                    model?.VideoType,
                    model?.IntegralComment,
                    model?.IntegralCommentType,
                    model?.GoodsCountry,
                    model?.FatCode,
                    model?.GoodsUrl,
                    model?.goodsLogo,
                    model?.GoodsEduType,
                    model?.MaterialId,
                    RelevanceList = model?.RelevanceList.Select(qitem => new { qitem.RelevanceId, qitem.RelevanceName, qitem.RelevancePrice, qitem.Unit })
                };
            }
            return ApiResult.Success("", obj);
        }

        /// <summary>
        /// 新增修改商品信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetProductGoodsInfo()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            RB_Goods_Extend demodel = new RB_Goods_Extend()
            {
                Id = parms.GetInt("Id"),
                Name = parms.GetStringValue("Name"),
                VideoAddress = parms.GetStringValue("VideoAddress"),
                CustomShareTitles = parms.GetStringValue("CustomShareTitles"),
                CustomShareImage = parms.GetStringValue("CustomShareImage"),
                CustomShareImagePath = parms.GetStringValue("CustomShareImagePath"),
                IsLiveGoods = parms.GetInt("IsLiveGoods"),
                GoodsStatus = parms.GetInt("GoodsStatus"),
                InventoryNum = parms.GetInt("InventoryNum"),
                DefaultSpecificationName = parms.GetStringValue("DefaultSpecificationName"),
                SellingPrice = parms.GetDecimal("SellingPrice"),
                OriginalPrice = parms.GetDecimal("OriginalPrice"),
                Unit = parms.GetStringValue("Unit"),
                CostPrice = parms.GetDecimal("CostPrice"),
                IsGoodsNegotiable = parms.GetInt("IsGoodsNegotiable"),
                SalesNum = parms.GetInt("SalesNum"),
                GoodsNumbers = parms.GetStringValue("GoodsNumbers"),
                IsCustomSpecification = parms.GetInt("IsCustomSpecification"),
                GoodsWeight = parms.GetInt("GoodsWeight"),
                IsDefaultService = parms.GetInt("IsDefaultService"),
                FreightId = parms.GetInt("FreightId"),
                FreightName = parms.GetStringValue("FreightName"),
                FormsId = parms.GetInt("FormsId", -1),
                FormsName = parms.GetStringValue("FormsName"),
                LimitBuyGoodsNum = parms.GetInt("LimitBuyGoodsNum", -1),
                LimitBuyOrderNum = parms.GetInt("LimitBuyOrderNum", -1),
                IsAreaBuy = parms.GetInt("IsAreaBuy"),
                IntegralPresent = parms.GetInt("IntegralPresent"),
                IntegralPresentType = parms.GetInt("IntegralPresentType"),
                PointsDeduction = parms.GetInt("PointsDeduction"),
                PointsDeductionType = parms.GetInt("PointsDeductionType"),
                IsMultipleDeduction = parms.GetInt("IsMultipleDeduction"),
                GoodsDetails = parms.GetStringValue("GoodsDetails"),
                SeparateDistribution = parms.GetInt("SeparateDistribution"),
                SeparateDistributionType = parms.GetInt("SeparateDistributionType"),
                SeparateDistributionMoneyType = parms.GetInt("SeparateDistributionMoneyType"),
                EnjoyMember = parms.GetInt("EnjoyMember"),
                SeparateSetMember = parms.GetInt("SeparateSetMember"),
                IsQuickBuy = parms.GetInt("IsQuickBuy"),
                FullNumPinkage = parms.GetInt("FullNumPinkage"),
                FullMoneyPinkage = parms.GetDecimal("FullMoneyPinkage"),
                SupplierId = parms.GetInt("SupplierId"),
                Sort = parms.GetInt("Sort"),
                Commission = parms.GetDecimal("Commission"),
                PresentFXGrade = parms.GetInt("PresentFXGrade"),
                PresentFXMonth = parms.GetInt("PresentFXMonth"),
                Advertising = parms.GetStringValue("Advertising"),
                SubName = parms.GetStringValue("SubName"),
                SendArea = parms.GetStringValue("SendArea"),
                VideoType = parms.GetInt("VideoType"),
                GoodsPageType = (GoodsPageTypeEnum)parms.GetInt("GoodsPageType"),
                Remark = parms.GetStringValue("Remark"),
                IsNoTax = parms.GetInt("IsNoTax"),
                GoodsCountry = parms.GetStringValue("GoodsCountry"),
                FatCode = parms.GetStringValue("FatCode"),
                GoodsUrl = parms.GetStringValue("GoodsUrl"),
                goodsLogo = parms.GetStringValue("goodsLogo"),
                RetailStore = parms.GetInt("RetailStore"),
                CreateBy = parms.GetInt("EmpId", 0),
                GoodsEduType = parms.GetInt("GoodsEduType", 0),
                MaterialId = parms.GetInt("MaterialId", 0)
            };
            if (!string.IsNullOrEmpty(parms.GetStringValue("ShelvesDate")))
            {
                demodel.ShelvesDate = parms.GetDateTime("ShelvesDate");
            }
            else
            {
                demodel.ShelvesDate = null;
            }

            if (!string.IsNullOrEmpty(parms.GetStringValue("DownDate")))
            {
                demodel.DownDate = parms.GetDateTime("DownDate");
            }
            else
            {
                demodel.DownDate = null;
            }

            int IsKorea = parms.GetInt("IsKorea", 0);//是否为韩国馆项目(1-是)
            demodel.CategoryList = JsonHelper.DeserializeObject<List<RB_Goods_Category_Extend>>(parms.GetStringValue("CategoryList"));
            demodel.CarouselImageList = JsonHelper.DeserializeObject<List<RB_ImageCommonModel>>(parms.GetStringValue("CarouselImageList"));
            demodel.SpecificationList = JsonHelper.DeserializeObject<List<RB_Goods_Specification_Extend>>(parms.GetStringValue("SpecificationList"));
            demodel.SpecificationPriceList = new List<RB_Goods_SpecificationPrice_Extend>();
            JArray priceArray = JArray.Parse(parms.GetStringValue("SpecificationPriceList"));
            foreach (var item in priceArray)
            {
                JObject jObj = JObject.Parse(item.ToString());
                RB_Goods_SpecificationPrice_Extend pModel = new RB_Goods_SpecificationPrice_Extend()
                {
                    Commission = jObj.GetDecimal("Commission"),
                    CostMoney = jObj.GetDecimal("CostMoney"),
                    GoodsNumbers = jObj.GetStringValue("GoodsNumbers"),
                    GoodsWeight = jObj.GetInt("GoodsWeight"),
                    InventoryNum = jObj.GetInt("InventoryNum"),
                    SellingPrice = jObj.GetDecimal("SellingPrice"),
                    SpecificationSort = jObj.GetStringValue("SpecificationSort"),
                    AttrList = new object()
                };
                var arrList = new List<object>();
                JArray sArray = JArray.Parse(jObj.GetStringValue("AttrList"));
                foreach (var sItem in sArray)
                {
                    JObject sObj = JObject.Parse(sItem.ToString());
                    arrList.Add(new
                    {
                        SName = sObj.GetStringValue("SName"),
                        SVId = sObj.GetInt("SVId"),
                        SVName = sObj.GetStringValue("SVName")
                    });
                }
                pModel.AttrList = arrList;
                demodel.SpecificationPriceList.Add(pModel);
            }

            demodel.ServiceList = JsonHelper.DeserializeObject<List<RB_ImageCommonModel>>(parms.GetStringValue("ServiceList"));
            demodel.AreaList = JsonHelper.DeserializeObject<List<RB_Goods_Area_Extend>>(parms.GetStringValue("AreaList"));
            demodel.DistributionCommissionList = JsonHelper.DeserializeObject<List<RB_Goods_DistributionCommission_Extend>>(parms.GetStringValue("DistributionCommissionList"));
            var marketingLogo = JsonHelper.DeserializeObject<MarketingLogoItem>(parms.GetStringValue("MarketingLogo"));
            demodel.MarketingLogo = JsonHelper.Serialize(marketingLogo);//待完善
            demodel.TenantId = RequestParm.TenantId;
            demodel.MallBaseId = RequestParm.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 (IsKorea == 0 && (demodel.SellingPrice ?? 0) < 0)
            {
                return ApiResult.ParamIsNull("请输入售价");
            }
            if (IsKorea == 0 && (demodel.OriginalPrice ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请输入原价");
            }
            if (IsKorea == 0 && string.IsNullOrEmpty(demodel.Unit))
            {
                return ApiResult.ParamIsNull("请输入单位");
            }
            demodel.IsCustomSpecification ??= 1;
            demodel.InventoryNum ??= 0;
            List<Model.Extend.User.RB_Distributor_Grade_Extend> DGradeList = null;
            List<Model.Extend.User.RB_Member_Grade_Extend> MGradeList = null;
            demodel.MinProfitRate = 0;
            if (demodel.IsCustomSpecification == 1)
            {
                demodel.InventoryNum = 0;
                if (demodel.SpecificationList == null || !demodel.SpecificationList.Any())
                {
                    return ApiResult.ParamIsNull("请传递规格列表");
                }
                if (demodel.SpecificationPriceList == null || !demodel.SpecificationPriceList.Any())
                {
                    return ApiResult.ParamIsNull("请传递规格价格库存列表");
                }
                if (demodel.SpecificationList.Count() != demodel.SpecificationList.Select(x => x.Sort).Distinct().Count())
                {
                    return ApiResult.ParamIsNull("规格名排序有误");
                }
                int TotalNum = 1;
                foreach (var item in demodel.SpecificationList)
                {
                    if (item.SpecificationValueList == null || !item.SpecificationValueList.Any())
                    {
                        return ApiResult.ParamIsNull("请传递规格值列表");
                    }
                    if (item.SpecificationValueList.Count() != item.SpecificationValueList.Select(x => x.Sort).Distinct().Count())
                    {
                        return ApiResult.ParamIsNull("规格值排序有误");
                    }
                    TotalNum *= item.SpecificationValueList.Count();
                    if (item.EnabledImage == 1)
                    {
                        foreach (var qitem in item.SpecificationValueList)
                        {
                            if ((qitem.Image ?? "") == "")
                            {
                                return ApiResult.ParamIsNull("请选择规格图片");
                            }
                        }
                    }
                }
                //验证总keys数量
                if (demodel.SpecificationPriceList.Count() != TotalNum)
                {
                    return ApiResult.ParamIsNull("规格价格数量有误");
                }
                //初始化所有keys
                List<string> KeyList = new List<string>();
                for (var i = 1; i <= TotalNum; i++)
                {
                    KeyList.Add("");
                }
                int MGBJNum = 1;
                //组装所有keys
                foreach (var item in demodel.SpecificationList)
                {
                    int LBBJNum = TotalNum / item.SpecificationValueList.Count() / MGBJNum;
                    int KeyIndex = 0;
                    for (var i = 1; i <= LBBJNum; i++)
                    {
                        foreach (var qitem in item.SpecificationValueList)
                        {
                            for (var j = 1; j <= MGBJNum; j++)
                            {
                                KeyList[KeyIndex] = KeyList[KeyIndex] + ":" + qitem.Sort;
                                KeyIndex++;
                            }
                        }
                    }
                }
                //验证所有keys
                foreach (var item in KeyList)
                {
                    string keys = item[1..];
                    var pricemodel = demodel.SpecificationPriceList.Where(x => x.SpecificationSort == keys).FirstOrDefault();
                    if (pricemodel == null)
                    {
                        return ApiResult.ParamIsNull("规格价格Key有误");
                    }
                    if ((pricemodel.SellingPrice ?? 0) < 0)
                    {
                        return ApiResult.ParamIsNull("请输入规格列表价格");
                    }
                    if ((pricemodel.InventoryNum ?? 0) < 0)
                    {
                        return ApiResult.ParamIsNull("规格列表库存不正确");
                    }
                    pricemodel.InventoryNum ??= 0;
                    pricemodel.SellingPrice ??= 0;
                    pricemodel.GoodsNumbers ??= "";
                    pricemodel.GoodsWeight ??= 0;
                    demodel.InventoryNum += (pricemodel.InventoryNum ?? 0);
                }
                demodel.SellingPrice = 0;
                //主表价格  如果有自定义规格，直接取最小值
                if (demodel.SpecificationPriceList != null && demodel.SpecificationPriceList.Count > 0)
                {
                    var SellingPrice = demodel.SpecificationPriceList.Where(x => x.SellingPrice > 0)?.Min(x => x.SellingPrice);
                    if (SellingPrice != null)
                    {
                        demodel.SellingPrice = SellingPrice;
                    }
                    try
                    {
                        var minlist = demodel.SpecificationPriceList.Where(x => x.SellingPrice > 0 && x.CostMoney > 0 && x.Commission > 0);
                        if (minlist.Any())
                        {
                            demodel.MinProfitRate = minlist.Min(x => Math.Round(((x.SellingPrice ?? 0) - x.CostMoney - x.Commission) / (x.SellingPrice ?? 0), 2, MidpointRounding.AwayFromZero));
                        }
                    }
                    catch
                    {

                    }
                }

                //分销佣金
                if (demodel.SeparateDistribution == 1)
                {
                    if (DGradeList == null)
                    {
                        DGradeList = productModule.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.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 (demodel.SeparateDistributionType == 1)
                    {
                        //普通设置  直接根据等级验证数量
                        if (DGradeList.Count() != demodel.DistributionCommissionList.Count())
                        {
                            return ApiResult.ParamIsNull("分销佣金列表数量不正确");
                        }
                        foreach (var item in DGradeList)
                        {
                            var gradeList = demodel.DistributionCommissionList.Where(x => x.DistributorGrade == item.Id).ToList();
                            if (!gradeList.Any())
                            {
                                return ApiResult.ParamIsNull("分销佣金" + item.Name + "列表不存在");
                            }

                            var gcmodel = gradeList.Where(x => x.SpecificationSort == "").FirstOrDefault();
                            if (gcmodel == null)
                            {
                                return ApiResult.ParamIsNull("分销Key有误");
                            }
                            gcmodel.OneCommission ??= 0;
                            gcmodel.TwoCommission ??= 0;
                            gcmodel.ThreeCommission ??= 0;
                        }
                    }
                    else
                    {
                        //普通设置  直接根据等级验证数量
                        if (DGradeList.Count() * TotalNum != demodel.DistributionCommissionList.Count())
                        {
                            LogHelper.Write(DGradeList.Count().ToString() + "|||" + JsonConvert.SerializeObject(DGradeList));
                            LogHelper.Write("TotalNum:" + TotalNum.ToString());
                            LogHelper.Write(JsonConvert.SerializeObject(demodel.DistributionCommissionList));
                            return ApiResult.ParamIsNull("分销佣金列表数量不正确");
                        }
                        foreach (var item in DGradeList)
                        {
                            var gradeList = demodel.DistributionCommissionList.Where(x => x.DistributorGrade == item.Id).ToList();
                            if (!gradeList.Any())
                            {
                                return ApiResult.ParamIsNull("分销佣金" + item.Name + "列表不存在");
                            }
                            if (gradeList.Count() != TotalNum)
                            {
                                return ApiResult.ParamIsNull("分销佣金" + item.Name + "列表数量不正确");
                            }
                            foreach (var qitem in KeyList)
                            {
                                string keys = qitem[1..];
                                var gcmodel = gradeList.Where(x => x.SpecificationSort == keys).FirstOrDefault();
                                if (gcmodel == null)
                                {
                                    return ApiResult.ParamIsNull("分销Key有误");
                                }
                                gcmodel.OneCommission ??= 0;
                                gcmodel.TwoCommission ??= 0;
                                gcmodel.ThreeCommission ??= 0;
                            }
                        }
                    }

                }
                //会员价格
                if (demodel.EnjoyMember == 1 && demodel.SeparateSetMember == 1)
                {
                    // 获取所有会员等级
                    if (MGradeList == null)
                    {
                        MGradeList = productModule.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.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() * TotalNum != demodel.MemberPriceList.Count())
                    {
                        return ApiResult.ParamIsNull("分销佣金列表数量不正确");
                    }
                    foreach (var item in MGradeList)
                    {
                        var gradeList = demodel.MemberPriceList.Where(x => x.MemberGrade == item.Id).ToList();
                        if (!gradeList.Any())
                        {
                            return ApiResult.ParamIsNull("会员价格" + item.Name + "列表不存在");
                        }
                        if (gradeList.Count() != TotalNum)
                        {
                            return ApiResult.ParamIsNull("会员价格" + item.Name + "列表数量不正确");
                        }
                        foreach (var qitem in KeyList)
                        {
                            string keys = qitem.Substring(1, qitem.Length - 1);
                            var gcmodel = gradeList.Where(x => x.SpecificationSort == keys).FirstOrDefault();
                            if (gcmodel == null)
                            {
                                return ApiResult.ParamIsNull("会员价格Key有误");
                            }
                            gcmodel.MemberPrice ??= 0;
                        }
                    }
                }
            }

            #region 默认值
            demodel.VideoAddress ??= "";
            demodel.CustomShareTitles ??= "";
            demodel.CustomShareImage ??= "";
            demodel.GoodsStatus ??= 2;
            demodel.DefaultSpecificationName ??= "";
            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;
            #endregion
            demodel.SeparateDistribution ??= 2;
            demodel.SeparateDistributionType ??= 1;
            if (demodel.SeparateDistribution == 1)
            {
                //获取所有分销商等级
                if (DGradeList == null)
                {
                    DGradeList = productModule.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("请传递分销佣金列表");
                    }
                    //普通设置  直接根据等级验证数量
                    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 = productModule.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("请传递会员价格列表");
                    }
                    if (MGradeList.Count() != demodel.MemberPriceList.Count())
                    {
                        return ApiResult.ParamIsNull("会员价格列表数量不正确");
                    }
                    foreach (var item in MGradeList)
                    {
                        var defaultModel = demodel.MemberPriceList.Where(x => x.MemberGrade == item.Id).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.Mall;
            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.Remark ??= "";//发货地
            demodel.GoodsClassify = 0;
            demodel.IntegralComment ??= 0;//评论反积分
            demodel.IntegralCommentType ??= 1;
            demodel.GoodsPageType ??= Common.Enum.Goods.GoodsPageTypeEnum.All;
            if (demodel.IsProxy == 1 && demodel.CostPrice > 0)
            {
                decimal ProxyMoney = 0;
                if (demodel.ProxyType == 1)
                {
                    ProxyMoney = Math.Round((demodel.CostPrice ?? 0) * (1 + (demodel.ProxyRises ?? 0)), 2, MidpointRounding.AwayFromZero);
                }
                else
                {
                    ProxyMoney = (demodel.CostPrice ?? 0) + (demodel.ProxyRises ?? 0);
                }
                if (ProxyMoney != (demodel.ProxyMoney ?? 0))
                {
                    return ApiResult.ParamIsNull("代理价格不正确");
                }
            }

            bool flag = productModule.SetProductGoodsInfo(demodel);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 商品快速更新
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetProductGoodsQuickUpdate()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            string GoodsIds = parms.GetStringValue("GoodsIds");
            int Type = parms.GetInt("Type", 0);//1排序  2商品名称  3快速购买  4上架  5下架  6删除  7运费  8限购  9积分  10快速购买  11面议,12 供应商,13 同步到分销平台
            int Sort = parms.GetInt("Sort", 0);
            string GoodsName = parms.GetStringValue("GoodsName");
            int FreightId = parms.GetInt("FreightId", 0);//运费
            int LimitBuyGoodsNum = parms.GetInt("LimitBuyGoodsNum", 0);//限制商品数量
            int LimitBuyOrderNum = parms.GetInt("LimitBuyOrderNum", 0);//限制订单数量
            int IntegralPresent = parms.GetInt("IntegralPresent", 0);//积分
            int IntegralPresentType = parms.GetInt("IntegralPresentType", 1);//积分类型f
            decimal PointsDeduction = parms.GetDecimal("PointsDeduction");//积分抵扣
            int PointsDeductionType = parms.GetInt("PointsDeductionType", 1);//抵扣类型
            int IsMultipleDeduction = parms.GetInt("IsMultipleDeduction", 2);//是否多件抵扣
            int IsQuickBuy = parms.GetInt("IsQuickBuy", 2);//快速购买
            int IsGoodsNegotiable = parms.GetInt("IsGoodsNegotiable", 2);//商品面议
            int SupplierId = parms.GetInt("SupplierId", 0);//供应商
            int RetailStore = parms.GetInt("RetailStore", 0);//是否同步到分销平台1-取消，2-是
            if (string.IsNullOrEmpty(GoodsIds))
            {
                return ApiResult.ParamIsNull();
            }
            if (Type == 2)
            {
                if (string.IsNullOrEmpty(GoodsName))
                {
                    return ApiResult.ParamIsNull("请传递商品名称");
                }
            }
            else if (Type == 12)
            {
                if (SupplierId == 0 && req.TenantId == 1 && req.MallBaseId == 1)
                {
                    return ApiResult.ParamIsNull("请选择供应商");
                }
            }
            else if (Type == 13)
            {
                var goodsList = productModule.GetGoodsList(new RB_Goods_Extend { GoodsIds = GoodsIds });
                if (goodsList != null && goodsList.Any())
                {
                    if (goodsList.Any(x => x.SourceGoodsId > 0))
                    {
                        return ApiResult.ParamIsNull("同步商品不能加入分销平台");
                    }
                }
            }



            bool flag = productModule.SetProductGoodsQuickUpdate(GoodsIds, Type, Sort, GoodsName, FreightId, LimitBuyGoodsNum, LimitBuyOrderNum, IntegralPresent
                , IntegralPresentType, PointsDeduction, PointsDeductionType, IsMultipleDeduction, IsQuickBuy, IsGoodsNegotiable, SupplierId, RetailStore, req.TenantId, req.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 删除商品
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelProcudtGoodsInfo()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int GoodsId = parms.GetInt("GoodsId", 0);
            if (GoodsId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            bool flag = productModule.DelProcudtGoodsInfo(GoodsId, req.TenantId, req.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 保存商品分类转移
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetGoodsCategoryTransfer()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int CategoryId = parms.GetInt("CategoryId", 0);
            int NewCategoryId = parms.GetInt("NewCategoryId", 0);//新分类
            if (CategoryId <= 0)
            {
                return ApiResult.ParamIsNull("请选择需转移分类id");
            }
            if (NewCategoryId < 0)
            {
                return ApiResult.ParamIsNull("请选择转入分类id");
            }
            if (CategoryId == NewCategoryId)
            {
                return ApiResult.ParamIsNull("不能转入同一分类下");
            }

            string msg = productModule.SetGoodsCategoryTransfer(CategoryId, NewCategoryId, req.TenantId, req.MallBaseId, req.EmpId);
            if (msg.Contains("转移成功"))
            {
                return ApiResult.Success(msg);
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }


        /// <summary>
        /// 获取商品版面类型枚举
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GoodsPageTypeEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(Common.Enum.Goods.GoodsPageTypeEnum));
            return ApiResult.Success("", list.OrderBy(x => Convert.ToInt32(x.Value)).Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }

        #endregion

        #region 商品代理

        /// <summary>
        /// 商品代理分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetProductGoodsProxyPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Goods_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Extend>(parms.msg.ToString());

            demodel.NotTenantId = parms.TenantId;
            //demodel.MallBaseId = parms.MallBaseId;
            demodel.IsProxy = 1;
            demodel.IsProcurement = 2;
            demodel.GoodsStatus = 1;
            var list = productModule.GetProductGoodsProxyPageList(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.ProxyMoney,
                x.InventoryNum,
                SalesNum = (x.SalesNum ?? 0) + (x.GoodsBuyNum ?? 0),
                x.IsProcurement,
                x.ProcurementStatus,
                x.ProcurementGoodsId,
                x.GoodsStatus,
                x.TenantId,
                x.MallBaseId,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : ""
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 设置商品代理
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetProductGoodsProxy()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int GoodsId = parms.GetInt("GoodsId", 0);
            string CategoryStr = parms.GetStringValue("CategoryStr");
            if (GoodsId <= 0)
            {
                return ApiResult.ParamIsNull("请传递商品id");
            }
            if (string.IsNullOrEmpty(CategoryStr) || CategoryStr == "[]")
            {
                return ApiResult.ParamIsNull("请选择分类");
            }
            List<int> CategoryList = JsonConvert.DeserializeObject<List<int>>(CategoryStr);

            return productModule.SetProductGoodsProxy(GoodsId, CategoryList, req.TenantId, req.MallBaseId);
        }

        /// <summary>
        /// 取消商品代理
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult CancelGoodsProxy()
        {

            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int GoodsId = parms.GetInt("GoodsId", 0);
            int Type = parms.GetInt("Type", 1);//类型  1原商品id   2代理商品id
            if (GoodsId <= 0)
            {
                return ApiResult.ParamIsNull("请传递商品id");
            }

            bool flag = productModule.CancelGoodsProxy(GoodsId, Type, req.TenantId, req.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 采购商品上下架
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetGoodsProxyStatus()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int GoodsId = parms.GetInt("GoodsId", 0);
            int Type = parms.GetInt("Type", 1);//类型  1上架   2下架
            if (GoodsId <= 0)
            {
                return ApiResult.ParamIsNull("请传递商品id");
            }

            bool flag = productModule.SetGoodsProxyStatus(GoodsId, Type, req.TenantId, req.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        #endregion

        #region 商品导入

        /// <summary>
        /// 商品导入
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetGoodsBatchImport()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            string FilePath = parms.GetStringValue("FilePath");
            int GoodsStatus = parms.GetInt("GoodsStatus", 0);
            string CategoryList = parms.GetStringValue("CategoryList");

            if (string.IsNullOrEmpty(FilePath))
            {
                return ApiResult.ParamIsNull("文件路径不存在");
            }
            if (GoodsStatus <= 0)
            {
                return ApiResult.ParamIsNull("请选择商品状态");
            }
            if (string.IsNullOrEmpty(CategoryList))
            {
                return ApiResult.ParamIsNull("请选择商品分类");
            }
            List<int> CategoryIdList;
            try
            {
                CategoryIdList = JsonConvert.DeserializeObject<List<int>>(CategoryList);
            }
            catch (Exception)
            {
                return ApiResult.ParamIsNull("商品分类传递不正确");
            }

            string msg = productModule.SetGoodsBatchImport(FilePath, GoodsStatus, CategoryIdList, req.TenantId, req.MallBaseId);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        #endregion

        #region 同步商品规格返佣

        /// <summary>
        /// 同步商品规格佣金
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SyncGoodsSpecificationCommission()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int TenantId = parms.GetInt("TenantId", 0);
            int MallBaseId = parms.GetInt("MallBaseId", 0);

            if (TenantId <= 0 || MallBaseId <= 0)
            {
                return ApiResult.Failed();
            }

            bool flag = productModule.SyncGoodsSpecificationCommission(TenantId, MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        #endregion

        #region 活动管理

        /// <summary>
        /// 获取活动分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetGoodsActivityPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Goods_Activity_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Activity_Extend>(parms.msg.ToString());

            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            var list = activityModule.GetGoodsActivityPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.ActivityName,
                x.Tier,
                x.Type,
                x.OrderNum,
                x.OrderMoney,
                x.GoodsNum,
                x.RangeType,
                x.RangeIds,
                x.RangeList,
                x.Way,
                x.CodeLength,
                x.PrizeName,
                x.PrizeImage,
                StartTime = x.StartTime.ToString("yyyy-MM-dd"),
                EndTime = x.EndTime.ToString("yyyy-MM-dd"),
                x.CoverImage,
                x.Description,
                ReceiveTime = x.ReceiveTime.ToString("yyyy-MM-dd"),
                x.Enable,
                x.ActiveObject,
                x.TenantId,
                x.MallBaseId,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd") : ""
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 获取活动详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetGoodsActivityInfo()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            int ActivityId = parms.GetInt("ActivityId", 0);
            if (ActivityId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            var model = activityModule.GetGoodsActivityInfo(ActivityId);
            return ApiResult.Success("", new
            {
                model.Id,
                model.ActivityName,
                model.Tier,
                model.Type,
                model.OrderNum,
                model.OrderMoney,
                model.GoodsNum,
                model.RangeType,
                model.RangeIds,
                model.RangeList,
                model.Way,
                model.CodeLength,
                model.PrizeName,
                model.PrizeImage,
                StartTime = model.StartTime.ToString("yyyy-MM-dd"),
                EndTime = model.EndTime.ToString("yyyy-MM-dd"),
                model.CoverImage,
                model.Description,
                model.ActiveObject,
                ReceiveTime = model.ReceiveTime.ToString("yyyy-MM-dd")
            });
        }

        /// <summary>
        /// 新增修改活动
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetGoodsActivityInfo()
        {
            var parms = RequestParm;
            RB_Goods_Activity_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Activity_Extend>(parms.msg.ToString());
            if (string.IsNullOrEmpty(demodel.ActivityName))
            {
                return ApiResult.ParamIsNull("请输入活动名称");
            }
            if (demodel.Type == 1)
            {
                if (demodel.OrderNum <= 0)
                {
                    return ApiResult.ParamIsNull("请输入分销订单数量");
                }
            }
            else if (demodel.Type == 2)
            {
                if (demodel.OrderMoney <= 0)
                {
                    return ApiResult.ParamIsNull("请输入分销订单金额");
                }
            }
            else
            {
                if (demodel.GoodsNum <= 0)
                {
                    return ApiResult.ParamIsNull("请输入分销商品数量");
                }
            }
            if (string.IsNullOrEmpty(demodel.RangeIds))
            {
                return ApiResult.ParamIsNull("请选择适配分类/商品");
            }
            if (demodel.CodeLength < 4)
            {
                return ApiResult.ParamIsNull("请选择验证码长度");
            }
            if (string.IsNullOrEmpty(demodel.PrizeName))
            {
                return ApiResult.ParamIsNull("请输入奖品名称");
            }
            if (string.IsNullOrEmpty(demodel.PrizeImage))
            {
                return ApiResult.ParamIsNull("请选择奖品图片");
            }
            if (string.IsNullOrEmpty(demodel.CoverImage))
            {
                return ApiResult.ParamIsNull("请选择封面图");
            }

            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            demodel.CreateDate = DateTime.Now;
            demodel.UpdateDate = DateTime.Now;
            demodel.Status = 0;
            demodel.StartTime = Convert.ToDateTime(demodel.StartTime.ToString("yyyy-MM-dd"));
            demodel.EndTime = Convert.ToDateTime(demodel.EndTime.ToString("yyyy-MM-dd") + " 23:59:59");
            demodel.ReceiveTime = Convert.ToDateTime(demodel.ReceiveTime.ToString("yyyy-MM-dd") + " 23:59:59");
            demodel.ActiveObject = demodel.ActiveObject == 0 ? 1 : demodel.ActiveObject;

            bool flag = activityModule.SetGoodsActivityInfo(demodel);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 设置活动启用/删除
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetGoodsActivityState()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            int ActivityId = parms.GetInt("ActivityId", 0);
            int Type = parms.GetInt("Type", 1);// 类型  1启用  2禁用  3删除

            if (ActivityId <= 0)
            {
                return ApiResult.ParamIsNull("请传递活动参数");
            }
            string msg = activityModule.SetGoodsActivityState(ActivityId, Type);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 获取活动中奖人员分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetGoodsActivityGetUserPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Goods_Activity_Get_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Activity_Get_Extend>(parms.msg.ToString());

            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            var list = activityModule.GetGoodsActivityGetUserPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.ActivityId,
                x.ActivityName,
                x.CoverImage,
                x.UserId,
                x.Name,
                x.Photo,
                x.Code,
                x.State,
                x.Way,
                x.OrderList,
                x.PrizeName,
                x.PrizeImage,
                x.TenantId,
                x.MallBaseId,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd") : ""
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 设置中奖人员状态
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetGoodsActivityUserState()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            int PrizeId = parms.GetInt("PrizeId", 0);
            int Type = parms.GetInt("Type", 1);// 类型  1已兑换   2已失效

            if (PrizeId <= 0)
            {
                return ApiResult.ParamIsNull("请传递中奖参数");
            }
            string msg = activityModule.SetGoodsActivityUserState(PrizeId, Type);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        #endregion

        #region 分享平台


        /// <summary>
        /// 商品后台分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetProductGoodsSynchroPageList()
        {
            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"),
                IsSelectSellOut = parameters.GetInt("IsSelectSellOut"),
                CategoryIds = parameters.GetStringValue("CategoryIds"),
                Id = parameters.GetInt("Id"),
                StartTime = parameters.GetStringValue("StartTime"),
                EndTime = parameters.GetStringValue("EndTime"),
                OrderBy = parameters.GetInt("OrderBy"),
                Isynchro = parameters.GetInt("Isynchro", 0),
                TenantId = parameters.GetInt("SupplierId", 0)
            };

            demodel.SourceMallBaseId = parms.MallBaseId;
            demodel.SourceTenantId = parms.TenantId;
            demodel.CreateBy = -1;
            decimal MinProfitRate = 0;
            if (demodel.TenantId == 1)
            {
                //MinProfitRate = Convert.ToDecimal(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("MinProfitRate")["TenantId1"]);
            }
            if (demodel.IsSelectLowProfit == 1)
            {
                demodel.MinProfitRate = MinProfitRate;
            }
            var list = productModule.GetSynchroPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            //List<RB_Goods_Extend> goodsList = new List<RB_Goods_Extend>();
            //if (list != null && list.Any())
            //{
            //    string GoodsIds = string.Join(",", list.Select(x => x.Id));//商品ids
            //    //根据商品id获取商品信息
            //    goodsList = productModule.GetGoodsList(new RB_Goods_Extend { SourceGoodsIdIds = GoodsIds, TenantId = parms.TenantId, MallBaseId = parms.MallBaseId });

            //}

            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.InventoryNum,
                x.SalesNum,
                x.GoodsBuyNum,
                x.IsQuickBuy,
                x.IsProxy,
                x.IsProcurement,
                x.ProcurementStatus,
                x.GoodsStatus,
                x.TenantId,
                x.MallBaseId,
                x.SendArea,
                x.Remark,
                GoodsPageTypeStr = x.GoodsPageType.GetEnumName(),
                CarouselImageList = x.CarouselImageList.Select(qitem => qitem.Path).ToList(),
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                x.IsNoTax,
                IsLowProfit = MinProfitRate > 0 ? x.MinProfitRate < MinProfitRate ? 1 : 2 : 2,
                x.CreateBy,
                x.SourceGoodsId,
                x.RetailStore,
                x.SupplierName,
                x.Isynchro
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 把分享平台的商品加入商品列表
        /// </summary>
        /// <returns></returns>
        public ApiResult SynchroGoods()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var CategoryList = JsonHelper.DeserializeObject<List<RB_Goods_Category_Extend>>(parms.GetStringValue("CategoryList"));//商品分类
            string GoodsIds = parms.GetStringValue("GoodsIds");//商品ids
                                                               //根据商品id获取商品信息
            var goodsList = productModule.GetGoodsList(new RB_Goods_Extend { GoodsIds = GoodsIds });
            if (goodsList.Any(x => x.SourceGoodsId > 0 && x.TenantId == RequestParm.TenantId && x.MallBaseId == RequestParm.MallBaseId))
            {
                return ApiResult.Failed("分享平台的商品不能多次分享添加");
            }
            //获取商品的规格以及价格
            var goodsSpecificationList = productModule.GetSpecificationList(new RB_Goods_Specification_Extend { GoodsIds = GoodsIds });
            var goodsSpecificationValueList = productModule.GetSpecificationValueList(new RB_Goods_SpecificationValue_Extend { GoodsIds = GoodsIds });
            var goodsSpecificationPriceList = productModule.GetSpecificationPriceList(new RB_Goods_SpecificationPrice_Extend { GoodsIds = GoodsIds });
            var newGoodsList = new List<RB_Goods_Extend>();
            foreach (var item in goodsList)
            {
                int TenantId = item.TenantId;
                int MallBaseId = item.MallBaseId;

                RB_Goods_Extend model = new RB_Goods_Extend();
                item.IsDefaultService = 1;
                item.IsAreaBuy = 2;
                item.SeparateDistribution = 2;
                item.SeparateSetMember = 2;
                item.EnjoyMember = 2;
                item.FreightId = 0;
                item.FreightName = "";
                item.FormsId = -1;
                item.FormsName = "";
                item.PresentFXGrade = 0;
                item.PresentFXMonth = 0;
                item.CostPrice = 0;
                item.IsNoTax = 0;
                item.CategoryList = CategoryList;
                item.SpecificationList = new List<RB_Goods_Specification_Extend>();
                item.SpecificationList = goodsSpecificationList.Where(x => x.GoodsId == item.Id).ToList();
                foreach (var itemSpecification in item.SpecificationList)
                {
                    itemSpecification.SpecificationValueList = new List<RB_Goods_SpecificationValue_Extend>();
                    itemSpecification.SpecificationValueList = goodsSpecificationValueList.Where(x => x.GoodsId == item.Id && x.SpecificationId == itemSpecification.Id).ToList();
                    if (itemSpecification.SpecificationValueList != null && itemSpecification.SpecificationValueList.Any())
                    {
                        itemSpecification.SpecificationValueList.ForEach(x => x.Id = 0);
                        itemSpecification.SpecificationValueList.ForEach(x => x.TenantId = RequestParm.TenantId);
                        itemSpecification.SpecificationValueList.ForEach(x => x.MallBaseId = RequestParm.MallBaseId);
                        itemSpecification.SpecificationValueList.ForEach(x => x.CreateDate = System.DateTime.Now);
                    }
                }
                item.SpecificationList.ForEach(x => x.Id = 0);
                item.SpecificationList.ForEach(x => x.TenantId = RequestParm.TenantId);
                item.SpecificationList.ForEach(x => x.CreateDate = System.DateTime.Now);
                item.SpecificationList.ForEach(x => x.MallBaseId = RequestParm.MallBaseId);
                item.SpecificationPriceList = new List<RB_Goods_SpecificationPrice_Extend>();
                item.SpecificationPriceList = goodsSpecificationPriceList.Where(x => x.GoodsId == item.Id).ToList();
                item.SpecificationPriceList.ForEach(x => x.Id = 0);
                item.SpecificationPriceList.ForEach(x => x.TenantId = RequestParm.TenantId);
                item.SpecificationPriceList.ForEach(x => x.CostMoney = 0);
                item.SpecificationPriceList.ForEach(x => x.CreateDate = System.DateTime.Now);
                item.SpecificationPriceList.ForEach(x => x.MallBaseId = RequestParm.MallBaseId);
                model = item;

                model.SourceTenantId = TenantId;
                model.SourceMallBaseId = MallBaseId;
                model.TenantId = RequestParm.TenantId;
                model.MallBaseId = RequestParm.MallBaseId;
                model.SourceGoodsId = item.Id;
                model.RetailStore = 0;
                model.Id = 0;
                model.SupplierId = 0;
                model.CreateDate = System.DateTime.Now;
                model.UpdateDate = System.DateTime.Now;
                newGoodsList.Add(model);
            }

            bool result = productModule.SynchroGoods(newGoodsList);
            return result ? ApiResult.Success("") : ApiResult.Failed("加入到商品列表失败");
        }
        #endregion

        /// <summary>
        /// 把分享平台的商品加入商品列表
        /// </summary>
        /// <returns></returns>
        public ApiResult CreateSkuCalendar()
        {
            List<object> list = new List<object>();
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            string startDate = parms.GetStringValue("StartDate");
            string endDate = parms.GetStringValue("EndDate");

            if (string.IsNullOrEmpty(startDate))
            {
                startDate = Common.ConvertHelper.FormatDate(DateTime.Now);
                endDate = Common.ConvertHelper.FormatDate(DateTime.Now.AddMonths(1));
            }

            DateTime start = Convert.ToDateTime(startDate);
            DateTime end = Convert.ToDateTime(endDate);
            List<StockItem> stockList = new List<StockItem>();
            int days = (end - start).Days;
            DateTime todayDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
            for (var i = 0; i <= days; i++)
            {
                var newDateTime = start.AddDays(i);
                stockList.Add(new StockItem()
                {
                    Year = newDateTime.Year,
                    Month = newDateTime.Month,
                    Day = newDateTime.Day,
                    DayStr = Common.ConvertHelper.FormatDate(newDateTime),
                    YearMonth = Common.ConvertHelper.FormatYearMonth(newDateTime),
                    IsEdit = newDateTime > todayDate
                });
            }

            var yearMonthList = stockList
                ?.GroupBy(qitem => new { qitem.Year, qitem.Month, qitem.YearMonth })
                ?.Select(qitem => new { qitem.Key.Year, qitem.Key.Month, qitem.Key.YearMonth });
            foreach (var rItem in yearMonthList)
            {
                list.Add(new
                {
                    rItem.YearMonth,
                    DateList = stockList?.Where(qitem => qitem.Year == rItem.Year && qitem.Month == rItem.Month)?.ToList() ?? new List<StockItem>()
                });
            }
            return ApiResult.Success(data: list);
        }
    }

    /// <summary>
    /// 库存项
    /// </summary>
    public class StockItem
    {
        /// <summary>
        /// 年
        /// </summary>
        public int Year { get; set; }

        /// <summary>
        /// 月
        /// </summary>
        public int Month { get; set; }

        /// <summary>
        /// 日
        /// </summary>
        public int Day { get; set; }

        /// <summary>
        /// yyyy-MM
        /// </summary>
        public string YearMonth { get; set; }

        /// <summary>
        /// 天
        /// </summary>
        public string DayStr { get; set; }

        /// <summary>
        /// 是否可编辑
        /// </summary>
        public  bool IsEdit { get; set; }
    }
}