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

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

        private readonly ProductModule productModule = new ProductModule();

        #region 商品分类

        /// <summary>
        /// 获取商品分类分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetProductCategoryPageList(object requestMsg)
        {
            var parms = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            if (parms.MallBaseId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Product_Category_Extend demodel = JsonConvert.DeserializeObject<RB_Product_Category_Extend>(parms.msg.ToString());

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            demodel.Enabled = 1;
            demodel.IsShow = 1;
            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,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd") : ""
            });
            return ApiResult.Success("", pagelist);
        }

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

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            demodel.Enabled = 1;
            demodel.IsShow = 1;
            var list = productModule.GetProductCategoryTreeList(demodel);
            return ApiResult.Success("", list);
        }

        /// <summary>
        /// 获取分类样式
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetProductCategoryStyleInfo(object requestMsg)
        {
            var parms = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            if (parms.MallBaseId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            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")
            });
        }

        #endregion

        #region 商品列表

        /// <summary>
        /// 小程序分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAppletGoodsPageList(object requestMsg)
        {
            var parms = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            if (parms.MallBaseId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            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;
            demodel.GoodsStatus = 1;//只查询销售中的
            var list = productModule.GetAppletGoodsPageList(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,
                x.VideoAddress,
                x.SellingPrice,
                x.SalesNum,
                x.IsQuickBuy,
                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 GetAppletGoodsPageListForZY(object requestMsg)
        {
            var parms = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            if (parms.MallBaseId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            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;
            demodel.GoodsStatus = 1;//只查询销售中的
            var list = productModule.GetAppletGoodsPageListForZY(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            List<object> RList = new List<object>();
            int UserId = parms.UserId;
            RB_Member_User_Extend userModel = new RB_Member_User_Extend();
            RB_Member_Grade_Extend memberGrade = new RB_Member_Grade_Extend();
            if (UserId > 0)
            {
                userModel = productModule.GetMemberUserInfo(UserId);
                if (userModel.MemberGrade > 0)
                {
                    memberGrade = productModule.GetMemberGradeList(new RB_Member_Grade_Extend() { Id = userModel.MemberGrade ?? 0, Enabled = 1, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
                }
            }
            if (list.Any())
            {
                foreach (var model in list)
                {
                    #region 组装价格
                    List<object> priceList = new List<object>();
                    if (model.IsCustomSpecification == 1)
                    {
                        if (model.SpecificationPriceList.Any() && model.SpecificationList.Any())
                        {
                            foreach (var item in model.SpecificationPriceList)
                            {
                                var ssarr = item.SpecificationSort.Split(':');
                                int Sort = Convert.ToInt32(ssarr[0]);
                                string pic_url = model.SpecificationList[0].SpecificationValueList.Where(x => x.Sort == Sort).FirstOrDefault()?.ImagePath;
                                List<object> attr_list = new List<object>();
                                for (int i = 0; i < ssarr.Length; i++)
                                {
                                    var smodel = model.SpecificationList[i];
                                    var svmodel = smodel.SpecificationValueList.Where(x => x.Sort == Convert.ToInt32(ssarr[i])).FirstOrDefault();
                                    attr_list.Add(new
                                    {
                                        attr_group_name = smodel.Name,
                                        attr_group_id = smodel.Sort,
                                        attr_id = svmodel.Id,
                                        attr_name = svmodel.Name
                                    });
                                }
                                decimal price_member = item.SellingPrice ?? 0;//未设会员价格的话  就为销售价格
                                if (model.EnjoyMember == 1 && model.SeparateSetMember == 1)
                                {
                                    if (model.MemberPriceList.Any())
                                    {
                                        var mlist = model.MemberPriceList.Where(x => x.SpecificationSort == item.SpecificationSort).ToList();
                                        if (UserId > 0 && userModel.MemberGrade > 0)
                                        {
                                            var gmodel = mlist.Where(x => x.MemberGrade == userModel.MemberGrade).FirstOrDefault();
                                            price_member = gmodel.MemberPrice ?? 0;
                                        }
                                    }
                                }
                                else
                                {
                                    if (UserId > 0 && userModel.MemberGrade > 0)
                                    {
                                        price_member = Math.Round((model.SellingPrice ?? 0) * (memberGrade?.Discount ?? 10) / 10, 2, MidpointRounding.AwayFromZero);
                                    }
                                }
                                priceList.Add(new
                                {
                                    id = item.Id,
                                    goods_id = model.Id,
                                    sign_id = item.SpecificationSort,
                                    stock = item.InventoryNum,
                                    price = item.SellingPrice,
                                    no = item.GoodsNumbers,
                                    weight = item.GoodsWeight,
                                    pic_url,
                                    is_delete = item.Status,
                                    attr_list,
                                    price_member
                                });
                            }
                        }
                    }
                    else
                    {
                        decimal price_member = model.SellingPrice ?? 0;//未设会员价格的话  就为销售价格
                        if (model.EnjoyMember == 1 && model.SeparateSetMember == 1)
                        {
                            if (model.MemberPriceList.Any())
                            {
                                var mlist = model.MemberPriceList;
                                if (UserId > 0 && userModel.MemberGrade > 0)
                                {
                                    var gmodel = mlist.Where(x => x.MemberGrade == userModel.MemberGrade).FirstOrDefault();
                                    price_member = gmodel.MemberPrice ?? 0;
                                }
                            }
                        }
                        else
                        {
                            if (UserId > 0 && userModel.MemberGrade > 0)
                            {
                                price_member = Math.Round((model.SellingPrice ?? 0) * (memberGrade?.Discount ?? 10) / 10, 2, MidpointRounding.AwayFromZero);
                            }
                        }


                        priceList.Add(new
                        {
                            id = 0,
                            goods_id = model.Id,
                            sign_id = "",
                            stock = model.InventoryNum,
                            price = model.SellingPrice ?? 0,
                            no = model.GoodsNumbers,
                            weight = model.GoodsWeight,
                            pic_url = "",
                            is_delete = 0,
                            attr_list = new
                            {
                                attr_group_name = "规格",
                                attr_group_id = 0,
                                attr_id = 0,
                                attr_name = model.DefaultSpecificationName
                            },
                            price_member
                        });
                    }
                    #endregion

                    #region 会员价格
                    decimal memberprice = model.SellingPrice ?? 0;
                    if (UserId > 0 && userModel.MemberGrade > 0 && model.EnjoyMember == 1 && model.SeparateSetMember == 1 && model.MemberPriceList.Any())
                    {
                        memberprice = model.MemberPriceList.Where(x => x.MemberGrade == userModel.MemberGrade).Min(x => x.MemberPrice ?? 0);
                    }
                    else if (UserId > 0 && userModel.MemberGrade > 0)
                    {
                        memberprice = memberprice * (memberGrade?.Discount ?? 10) / 10;
                    }
                    #endregion

                    RList.Add(new
                    {
                        id = model.Id,
                        sign = "",
                        name = model.Name,
                        cover_pic = model.CoverImage,
                        video_url = model.VideoAddress,
                        original_price = model.OriginalPrice,
                        unit = model.Unit,
                        page_url = "/pages/goods/goods?id=" + model.Id,
                        is_negotiable = model.IsGoodsNegotiable,
                        is_level = model.EnjoyMember,
                        level_price = memberprice,
                        price = (model.SellingPrice ?? 0).ToString("#0.00"),
                        price_content = "￥" + (model.SellingPrice ?? 0).ToString("#0.00"),
                        is_sales = model.GoodsStatus,
                        sales = "已售" + model.SalesNum + "件",
                        freeShippingName = model.FreeShippingModel.Name,
                        freeShippingFullMoneyPinkage = model.FreeShippingModel.FullMoneyPinkage ?? 0,
                        freeShippingFullNumPinkage = model.FreeShippingModel.FullNumPinkage ?? 0,
                        attr_groups = model.SpecificationList.Select(x => new
                        {
                            attr_group_id = x.Sort,
                            attr_group_name = x.Name,
                            attr_list = x.SpecificationValueList.Select(z => new
                            {
                                attr_id = z.Sort,
                                attr_name = z.Name,
                                pic_url = z.ImagePath
                            })
                        }),
                        attr = priceList,
                        goods_stock = model.InventoryNum,
                        goods_num = model.InventoryNum
                    });
                }
            }

            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = RList;
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 获取小程序商品详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAppletGoodsInfo(object requestMsg)
        {
            var req = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            if (req.MallBaseId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            JObject prams = JObject.Parse(req.msg.ToString());
            int GoodsId = prams.GetInt("GoodsId", 0);
            if (GoodsId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            int UserId = req.UserId;

            var Robj = productModule.GetAppletGoodsInfo_V2(GoodsId, UserId, req.TenantId, req.MallBaseId);
            return ApiResult.Success("", Robj);
        }

        /// <summary>
        /// 获取小程序商品详情备份
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAppletGoodsInfoBack(object requestMsg)
        {
            var req = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            if (req.MallBaseId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            JObject prams = JObject.Parse(req.msg.ToString());
            int GoodsId = prams.GetInt("GoodsId", 0);
            if (GoodsId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            int UserId = req.UserId;
            RB_Member_User_Extend userModel = new RB_Member_User_Extend();
            List<RB_Member_Grade_Extend> memeberList = new List<RB_Member_Grade_Extend>();
            if (UserId > 0)
            {
                userModel = productModule.GetMemberUserInfo(UserId);
                if (userModel.MemberGrade > 0)
                {
                    memeberList = productModule.GetMemberGradeList(new RB_Member_Grade_Extend() { Enabled = 1, TenantId = req.TenantId, MallBaseId = req.MallBaseId });
                }
            }

            RB_Goods_Extend model = productModule.GetAppletGoodsInfo(GoodsId, UserId, req.TenantId, req.MallBaseId);

            #region 组装价格
            List<object> priceList = new List<object>();
            if (model.IsCustomSpecification == 1)
            {
                if (model.SpecificationPriceList.Any() && model.SpecificationList.Any())
                {
                    foreach (var item in model.SpecificationPriceList)
                    {
                        var ssarr = item.SpecificationSort.Split(':');
                        int Sort = Convert.ToInt32(ssarr[0]);
                        string pic_url = model.SpecificationList[0].SpecificationValueList.Where(x => x.Sort == Sort).FirstOrDefault()?.ImagePath;
                        List<object> attr_list = new List<object>();
                        for (int i = 0; i < ssarr.Length; i++)
                        {
                            var smodel = model.SpecificationList[i];
                            var svmodel = smodel.SpecificationValueList.Where(x => x.Sort == Convert.ToInt32(ssarr[i])).FirstOrDefault();
                            attr_list.Add(new
                            {
                                attr_group_name = smodel.Name,
                                attr_group_id = smodel.Sort,
                                attr_id = svmodel.Id,
                                attr_name = svmodel.Name
                            });
                        }
                        decimal price_member = item.SellingPrice ?? 0;//未设会员价格的话  就为销售价格
                        List<object> member_price_list = new List<object>();
                        if (model.EnjoyMember == 1 && model.SeparateSetMember == 1)
                        {
                            if (model.MemberPriceList.Any())
                            {
                                var mlist = model.MemberPriceList.Where(x => x.SpecificationSort == item.SpecificationSort).ToList();
                                foreach (var qitem in mlist)
                                {
                                    member_price_list.Add(new
                                    {
                                        member_grade = qitem.MemberGrade,
                                        member_price = qitem.MemberPrice
                                    });
                                }
                                if (UserId > 0 && userModel.MemberGrade > 0)
                                {
                                    var gmodel = mlist.Where(x => x.MemberGrade == userModel.MemberGrade).FirstOrDefault();
                                    price_member = gmodel.MemberPrice ?? 0;
                                }
                                else
                                {
                                    price_member = mlist.Max(x => x.MemberPrice ?? 0);
                                }
                            }
                        }
                        else
                        {
                            //根据会员等级查找会员价格
                            foreach (var qitem in memeberList)
                            {
                                var mprice = Math.Round((item.SellingPrice ?? 0) * (qitem.Discount ?? 0) / 10, 2, MidpointRounding.AwayFromZero);
                                member_price_list.Add(new
                                {
                                    member_grade = qitem.Grade,
                                    member_price = mprice
                                });
                            }
                            if (UserId > 0 && userModel.MemberGrade > 0 && memeberList.Any())
                            {
                                var gmodel = memeberList.Where(x => x.Grade == userModel.MemberGrade).FirstOrDefault();
                                price_member = Math.Round((model.SellingPrice ?? 0) * (gmodel?.Discount ?? 10) / 10, 2, MidpointRounding.AwayFromZero);
                            }
                            else if (memeberList.Any())
                            {
                                price_member = Math.Round((model.SellingPrice ?? 0) * (memeberList.Max(x => x.Discount) ?? 10) / 10, 2, MidpointRounding.AwayFromZero);
                            }
                        }
                        priceList.Add(new
                        {
                            id = item.Id,
                            goods_id = model.Id,
                            sign_id = item.SpecificationSort,
                            stock = item.InventoryNum,
                            price = item.SellingPrice,
                            no = item.GoodsNumbers,
                            weight = item.GoodsWeight,
                            pic_url,
                            is_delete = item.Status,
                            attr_list,
                            price_member,
                            member_price_list
                        });
                    }
                }
            }
            else
            {
                decimal price_member = model.SellingPrice ?? 0;//未设会员价格的话  就为销售价格
                List<object> member_price_list = new List<object>();
                if (model.EnjoyMember == 1 && model.SeparateSetMember == 1)
                {
                    if (model.MemberPriceList.Any())
                    {
                        var mlist = model.MemberPriceList;
                        foreach (var qitem in mlist)
                        {
                            member_price_list.Add(new
                            {
                                member_grade = qitem.MemberGrade,
                                member_price = qitem.MemberPrice
                            });
                        }
                        if (UserId > 0 && userModel.MemberGrade > 0)
                        {
                            var gmodel = mlist.Where(x => x.MemberGrade == userModel.MemberGrade).FirstOrDefault();
                            price_member = gmodel.MemberPrice ?? 0;
                        }
                        else
                        {
                            price_member = mlist.Max(x => x.MemberPrice ?? 0);
                        }
                    }
                }
                else
                {
                    //根据会员等级查找会员价格
                    foreach (var qitem in memeberList)
                    {
                        var mprice = Math.Round((model.SellingPrice ?? 0) * (qitem.Discount ?? 10) / 10, 2, MidpointRounding.AwayFromZero);
                        member_price_list.Add(new
                        {
                            member_grade = qitem.Grade,
                            member_price = mprice
                        });
                    }
                    if (UserId > 0 && userModel.MemberGrade > 0 && memeberList.Any())
                    {
                        var gmodel = memeberList.Where(x => x.Grade == userModel.MemberGrade).FirstOrDefault();
                        price_member = Math.Round((model.SellingPrice ?? 0) * (gmodel?.Discount ?? 10) / 10, 2, MidpointRounding.AwayFromZero);
                    }
                    else if (memeberList.Any())
                    {
                        price_member = Math.Round((model.SellingPrice ?? 0) * (memeberList.Max(x => x.Discount) ?? 10) / 10, 2, MidpointRounding.AwayFromZero);
                    }
                }


                priceList.Add(new
                {
                    id = 0,
                    goods_id = model.Id,
                    sign_id = "",
                    stock = model.InventoryNum,
                    price = model.SellingPrice ?? 0,
                    no = model.GoodsNumbers,
                    weight = model.GoodsWeight,
                    pic_url = "",
                    is_delete = 0,
                    attr_list = new List<object>(){ new
                    {
                        attr_group_name = "规格",
                        attr_group_id = 0,
                        attr_id = 0,
                        attr_name = model.DefaultSpecificationName
                    } },
                    price_member,
                    member_price_list
                });
            }
            #endregion
            #region 赠送积分
            int Integral = 0;
            if (model.IntegralPresent > 0)
            {
                Integral = model.IntegralPresent ?? 0;
                if (model.IntegralPresentType == 2)
                {
                    Integral = Convert.ToInt32(Math.Floor((model.SellingPrice ?? 0) * (model.IntegralPresent ?? 0) / 100));
                }
            }
            #endregion
            #region 会员价格
            decimal price_member_max = 0, price_member_min = 0, price_min = 0, price_max = 0;
            if (model.EnjoyMember == 1 && model.SeparateSetMember == 1 && model.MemberPriceList.Any())
            {
                price_member_min = model.MemberPriceList.Min(x => x.MemberPrice ?? 0);
                price_member_max = model.MemberPriceList.Max(x => x.MemberPrice ?? 0);
                if (userModel.MemberGrade > 0)
                {
                    price_min = model.MemberPriceList.Where(x => x.MemberGrade == userModel.MemberGrade).Min(x => x.MemberPrice ?? 0);
                    price_max = model.MemberPriceList.Where(x => x.MemberGrade == userModel.MemberGrade).Max(x => x.MemberPrice ?? 0);
                }
            }
            else
            {

                if (model.IsCustomSpecification == 1)
                {
                    price_member_min = price_min = model.SpecificationPriceList.Min(x => x.SellingPrice ?? 0);
                    price_member_max = price_max = model.SpecificationPriceList.Max(x => x.SellingPrice ?? 0);
                }
                else
                {
                    price_member_min = price_member_max = price_min = price_max = model.SellingPrice ?? 0;
                }
                if (memeberList.Any())
                {
                    List<decimal> pricelist = new List<decimal>();
                    foreach (var item in memeberList)
                    {
                        pricelist.Add(price_member_min * (item.Discount ?? 10) / 10);
                        pricelist.Add(price_member_max * (item.Discount ?? 10) / 10);
                    }
                    price_member_min = pricelist.Min(x => x);
                    price_member_max = pricelist.Max(x => x);
                    if (userModel.MemberGrade > 0)
                    {
                        if (price_min > (model.SellingPrice ?? 0)) { price_min = model.SellingPrice ?? 0; }
                        if (price_max < (model.SellingPrice ?? 0)) { price_max = model.SellingPrice ?? 0; }
                        price_min = price_member_min * (memeberList.Where(x => x.Id == userModel.MemberGrade).FirstOrDefault()?.Discount ?? 10) / 10;
                        price_max = price_member_max * (memeberList.Where(x => x.Id == userModel.MemberGrade).FirstOrDefault()?.Discount ?? 10) / 10;
                    }
                }
            }
            price_member_max = Math.Round(price_member_max, 2, MidpointRounding.AwayFromZero);
            price_member_min = Math.Round(price_member_min, 2, MidpointRounding.AwayFromZero);
            price_min = Math.Round(price_min, 2, MidpointRounding.AwayFromZero);
            price_max = Math.Round(price_max, 2, MidpointRounding.AwayFromZero);
            #endregion
            #region 订单信息

            int payment_people = 0, payment_num = 0, payment_order = 0;//订单用户  商品数量   订单数量
            decimal payment_amount = 0;//订单总金额
            productModule.GetGoodsOrderPeopleInfo(out payment_amount, out payment_num, out payment_order, out payment_people, GoodsId);
            #endregion

            return ApiResult.Success("success", new
            {
                goods = new
                {
                    id = model.Id,
                    mall_id = model.MallBaseId,
                    mch_id = model.TenantId,//暂  商户id
                    //goods_warehouse_id = 0,//
                    status = model.GoodsStatus,
                    price = model.SellingPrice,
                    use_attr = model.IsCustomSpecification,
                    attr_groups = model.SpecificationList.Select(x => new
                    {
                        attr_group_id = x.Sort,
                        attr_group_name = x.Name,
                        attr_list = x.SpecificationValueList.Select(z => new
                        {
                            attr_id = z.Sort,
                            attr_name = z.Name,
                            pic_url = z.ImagePath
                        })
                    }),
                    goods_stock = model.InventoryNum,
                    virtual_sales = model.SalesNum,
                    confine_count = model.LimitBuyGoodsNum,
                    pieces = model.FullNumPinkage,//满件包邮
                    forehead = model.FullMoneyPinkage,//满额包邮
                    freight_id = model.FreightId,
                    give_integral = model.IntegralPresent,
                    give_integral_type = model.IntegralPresentType,
                    forehead_integral = model.PointsDeduction,//暂  积分抵扣
                    forehead_integral_type = model.PointsDeductionType,//暂  积分抵扣类型
                    accumulative = model.IsMultipleDeduction,//多件抵扣
                    individual_share = userModel?.IsDistributor ?? 2,// 是否分销商
                    attr_setting_type = model.SeparateDistributionType,//分销类型
                    is_level = model.EnjoyMember,//是否销售会员价格
                    is_level_alone = model.SeparateSetMember,//是否单独设置会员价
                    share_type = model.SeparateDistributionMoneyType,//分销佣金类型
                    //sign = "",
                    app_share_pic = model.CustomShareImagePath,
                    app_share_title = model.CustomShareTitles,
                    is_default_services = model.IsDefaultService,
                    sort = model.Sort,
                    created_at = model.CreateDate.HasValue ? model.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                    updated_at = model.UpdateDate.HasValue ? model.UpdateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                    //deleted_at = "",
                    is_delete = model.Status,
                    payment_people,//用户数量
                    payment_num,//商品数量
                    payment_amount,//销售总额
                    payment_order,//订单数量
                    confine_order_count = model.LimitBuyOrderNum,
                    is_area_limit = model.IsAreaBuy,
                    area_limit = new List<object>() { new { list = model.AreaList.Select(x => new {
                        area_id=x.AreaId,
                        area_name=x.AreaName,
                        area_type=x.AreaType
                    }) } },
                    form_id = model.FormsId,
                    sales = model.SalesNum + payment_num,//已售出数量 + 订单商品数量//
                    name = model.Name,
                    original_price = model.OriginalPrice,
                    cover_pic = model.CoverImage,
                    unit = model.Unit,
                    detail = model.GoodsDetails,
                    video_url = model.VideoAddress,
                    level_show = (userModel?.MemberGrade ?? 0) > 0 ? 1 : 2,//是否显示会员价
                    is_sales = model.GoodsStatus == 1 && model.InventoryNum > 0 ? 1 : 2,//是否可购买
                    attr = priceList,
                    //goods_num = model.InventoryNum,
                    goods_no = model.GoodsNumbers,
                    goods_weight = model.GoodsWeight,
                    services = model.ServiceList.Select(x => new
                    {
                        id = x.Id,
                        name = x.Name
                    }),
                    price_min,
                    price_max,
                    pic_url = model.CarouselImageList.Select(x => new
                    {
                        id = x.Id,
                        pic_url = x.Path
                    }),
                    share = model.MaxShare,//分销佣金
                    favorite = model.Favorite,//是否收藏
                    //goods_marketing = new
                    //{
                    //    limit = "",
                    //    pickup = "",
                    //    shipping = ""
                    //},
                    goods_marketing_award = new
                    {
                        integral = new
                        {
                            title = "购买可得" + Integral + "积分"
                        }
                    },
                    //plugin_extra = new List<object>(),
                    express = model.Express,//快递费用   读取默认收货地址 如果没有为0  如果有 根据商品运费匹配 找出快递费用
                    price_member_max,
                    price_member_min,
                    extra_quick_share = new
                    {
                        share_pic = model.CarouselImageList.Select(x => new
                        {
                            id = x.Id,
                            pic_url = x.Path
                        }),
                        share_text = model.Name,
                        mall_name = model.MallName,
                        format_time = model.UpdateDate.HasValue ? model.UpdateDate.Value.ToString("yyyy-MM-dd") : ""
                    },
                    is_quick_shop = model.IsQuickBuy,
                    is_sell_well = model.IsSellWell,
                    is_negotiable = model.IsGoodsNegotiable,
                    cats = model.CategoryList.Select(x => new
                    {
                        x.CategoryId,
                        x.CategoryName
                    })//分类
                },
                delivery = ""
            });
        }

        /// <summary>
        /// 小程序商品视频分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAppletGoodsVideoPageList(object requestMsg)
        {
            var parms = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            if (parms.MallBaseId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            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;
            demodel.GoodsStatus = 1;//只查询销售中的
            demodel.IsSelectVideo = 1;//值查询有视频的
            var list = productModule.GetAppletGoodsVideoPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                id = 40887,
                //goods_warehouse_id= 19813,
                mch_id = demodel.TenantId,
                //sign= "",
                name = x.Name,
                cover_pic = x.CoverImage,
                video_url = x.VideoAddress,
                original_price = x.OriginalPrice,
                unit = x.Unit,
                page_url = "/pages/goods/goods?id=" + x.Id,
                is_negotiable = x.IsGoodsNegotiable,
                is_level = x.EnjoyMember,//是否销售会员价格
                //level_price = -1,
                price = x.SellingPrice,
                price_content = "￥" + x.SellingPrice,
                is_sales = x.GoodsStatus == 1 && x.InventoryNum > 0 ? 1 : 2,//是否可购买
                sales = x.SalesNum,
                attr_groups = x.SpecificationList.Select(x => new
                {
                    attr_group_id = x.Sort,
                    attr_group_name = x.Name,
                    attr_list = x.SpecificationValueList.Select(z => new
                    {
                        attr_id = z.Sort,
                        attr_name = z.Name,
                        pic_url = z.ImagePath
                    })
                }),
                attr = GetGoodsAttr(x),
                goods_stock = x.InventoryNum,
                //goods_num= x.InventoryNum,
                app_share_title = x.CustomShareTitles,
                app_share_pic = x.CustomShareImagePath ?? ""
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 获取规格价格
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        private object GetGoodsAttr(RB_Goods_Extend model)
        {
            List<object> priceList = new List<object>();
            if (model.IsCustomSpecification == 1)
            {
                if (model.SpecificationPriceList.Any() && model.SpecificationList.Any())
                {
                    foreach (var item in model.SpecificationPriceList.Where(x => x.SellingPrice > 0))
                    {
                        var ssarr = item.SpecificationSort.Split(':');
                        int Sort = Convert.ToInt32(ssarr[0]);
                        string pic_url = model.SpecificationList[0].SpecificationValueList.Where(x => x.Sort == Sort).FirstOrDefault()?.ImagePath;
                        List<object> attr_list = new List<object>();
                        for (int i = 0; i < ssarr.Length; i++)
                        {
                            var smodel = model.SpecificationList[i];
                            var svmodel = smodel.SpecificationValueList.Where(x => x.Sort == Convert.ToInt32(ssarr[i])).FirstOrDefault();
                            attr_list.Add(new
                            {
                                attr_group_name = smodel.Name,
                                attr_group_id = smodel.Sort,
                                attr_id = svmodel.Id,
                                attr_name = svmodel.Name
                            });
                        }

                        priceList.Add(new
                        {
                            id = item.Id,
                            goods_id = model.Id,
                            sign_id = item.SpecificationSort,
                            stock = item.InventoryNum,
                            price = item.SellingPrice,
                            no = item.GoodsNumbers,
                            weight = item.GoodsWeight,
                            pic_url,
                            is_delete = item.Status,
                            attr_list
                        });
                    }
                }
            }
            else
            {
                priceList.Add(new
                {
                    id = 0,
                    goods_id = model.Id,
                    sign_id = "",
                    stock = model.InventoryNum,
                    price = model.SellingPrice ?? 0,
                    no = model.GoodsNumbers,
                    weight = model.GoodsWeight,
                    pic_url = "",
                    is_delete = 0,
                    attr_list = new
                    {
                        attr_group_name = "规格",
                        attr_group_id = 0,
                        attr_id = 0,
                        attr_name = model.DefaultSpecificationName
                    }
                });
            }

            return priceList;
        }

        /// <summary>
        /// 小程序获取推荐商品列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAppletGoodsRecommendList(object requestMsg)
        {
            var parms = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            if (parms.MallBaseId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            RB_Goods_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Extend>(parms.msg.ToString());
            if (!demodel.RecommendType.HasValue && demodel.RecommendType <= 0)
            {
                return ApiResult.ParamIsNull("请传递推荐类型");
            }

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            demodel.GoodsStatus = 1;//只查询销售中的
            var list = productModule.GetAppletGoodsRecommendList(1, 10, out int RecommendStatus, demodel);
            return ApiResult.Success("", new
            {
                RecommendStatus,
                List = list.Select(x => new
                {
                    x.Id,
                    x.Name,
                    x.Sort,
                    x.CoverImage,
                    x.VideoAddress,
                    x.SellingPrice,
                    x.SalesNum,
                    x.IsQuickBuy,
                    CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : ""
                })
            });
        }

        /// <summary>
        /// 小程序获取推荐商品列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAppletGoodsRecommendListForZY(object requestMsg)
        {
            var parms = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            if (parms.MallBaseId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            RB_Goods_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Extend>(parms.msg.ToString());
            if (!demodel.RecommendType.HasValue && demodel.RecommendType <= 0)
            {
                return ApiResult.ParamIsNull("请传递推荐类型");
            }

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            demodel.GoodsStatus = 1;//只查询销售中的
            var list = productModule.GetAppletGoodsRecommendListForZY(1, 10, out int RecommendStatus, demodel);
            List<object> RList = new List<object>();
            int UserId = demodel.UserId ?? 0;
            RB_Member_User_Extend userModel = new RB_Member_User_Extend();
            RB_Member_Grade_Extend memberGrade = new RB_Member_Grade_Extend();
            if (UserId > 0)
            {
                userModel = productModule.GetMemberUserInfo(UserId);
                if (userModel.MemberGrade > 0)
                {
                    memberGrade = productModule.GetMemberGradeList(new RB_Member_Grade_Extend() { Id = userModel.MemberGrade ?? 0, Enabled = 1, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
                }
            }
            if (list.Any())
            {
                foreach (var model in list)
                {
                    #region 组装价格
                    List<object> priceList = new List<object>();
                    if (model.IsCustomSpecification == 1)
                    {
                        if (model.SpecificationPriceList.Any() && model.SpecificationList.Any())
                        {
                            foreach (var item in model.SpecificationPriceList)
                            {
                                var ssarr = item.SpecificationSort.Split(':');
                                int Sort = Convert.ToInt32(ssarr[0]);
                                string pic_url = model.SpecificationList[0].SpecificationValueList.Where(x => x.Sort == Sort).FirstOrDefault()?.ImagePath;
                                List<object> attr_list = new List<object>();
                                for (int i = 0; i < ssarr.Length; i++)
                                {
                                    var smodel = model.SpecificationList[i];
                                    var svmodel = smodel.SpecificationValueList.Where(x => x.Sort == Convert.ToInt32(ssarr[i])).FirstOrDefault();
                                    attr_list.Add(new
                                    {
                                        attr_group_name = smodel.Name,
                                        attr_group_id = smodel.Sort,
                                        attr_id = svmodel.Id,
                                        attr_name = svmodel.Name
                                    });
                                }
                                decimal price_member = item.SellingPrice ?? 0;//未设会员价格的话  就为销售价格
                                if (model.EnjoyMember == 1 && model.SeparateSetMember == 1)
                                {
                                    if (model.MemberPriceList.Any())
                                    {
                                        var mlist = model.MemberPriceList.Where(x => x.SpecificationSort == item.SpecificationSort).ToList();
                                        if (UserId > 0 && userModel.MemberGrade > 0)
                                        {
                                            var gmodel = mlist.Where(x => x.MemberGrade == userModel.MemberGrade).FirstOrDefault();
                                            price_member = gmodel.MemberPrice ?? 0;
                                        }
                                    }
                                }
                                else
                                {
                                    if (UserId > 0 && userModel.MemberGrade > 0)
                                    {
                                        price_member = Math.Round((model.SellingPrice ?? 0) * (memberGrade?.Discount ?? 10) / 10, 2, MidpointRounding.AwayFromZero);
                                    }
                                }
                                priceList.Add(new
                                {
                                    id = item.Id,
                                    goods_id = model.Id,
                                    sign_id = item.SpecificationSort,
                                    stock = item.InventoryNum,
                                    price = item.SellingPrice,
                                    no = item.GoodsNumbers,
                                    weight = item.GoodsWeight,
                                    pic_url,
                                    is_delete = item.Status,
                                    attr_list,
                                    price_member
                                });
                            }
                        }
                    }
                    else
                    {
                        decimal price_member = model.SellingPrice ?? 0;//未设会员价格的话  就为销售价格
                        if (model.EnjoyMember == 1 && model.SeparateSetMember == 1)
                        {
                            if (model.MemberPriceList.Any())
                            {
                                var mlist = model.MemberPriceList;
                                if (UserId > 0 && userModel.MemberGrade > 0)
                                {
                                    var gmodel = mlist.Where(x => x.MemberGrade == userModel.MemberGrade).FirstOrDefault();
                                    price_member = gmodel.MemberPrice ?? 0;
                                }
                            }
                        }
                        else
                        {
                            if (UserId > 0 && userModel.MemberGrade > 0)
                            {
                                price_member = Math.Round((model.SellingPrice ?? 0) * (memberGrade?.Discount ?? 10) / 10, 2, MidpointRounding.AwayFromZero);
                            }
                        }


                        priceList.Add(new
                        {
                            id = 0,
                            goods_id = model.Id,
                            sign_id = "",
                            stock = model.InventoryNum,
                            price = model.SellingPrice ?? 0,
                            no = model.GoodsNumbers,
                            weight = model.GoodsWeight,
                            pic_url = "",
                            is_delete = 0,
                            attr_list = new
                            {
                                attr_group_name = "规格",
                                attr_group_id = 0,
                                attr_id = 0,
                                attr_name = model.DefaultSpecificationName
                            },
                            price_member
                        });
                    }
                    #endregion

                    #region 会员价格
                    decimal memberprice = model.SellingPrice ?? 0;
                    if (UserId > 0 && userModel.MemberGrade > 0 && model.EnjoyMember == 1 && model.SeparateSetMember == 1 && model.MemberPriceList.Any())
                    {
                        memberprice = model.MemberPriceList.Where(x => x.MemberGrade == userModel.MemberGrade).Min(x => x.MemberPrice ?? 0);
                    }
                    else if (UserId > 0 && userModel.MemberGrade > 0)
                    {
                        memberprice = memberprice * (memberGrade?.Discount ?? 10) / 10;
                    }
                    #endregion

                    RList.Add(new
                    {
                        id = model.Id,
                        sign = "",
                        name = model.Name,
                        cover_pic = model.CoverImage,
                        video_url = model.VideoAddress,
                        original_price = model.OriginalPrice,
                        unit = model.Unit,
                        page_url = "/pages/goods/goods?id=" + model.Id,
                        is_negotiable = model.IsGoodsNegotiable,
                        is_level = model.EnjoyMember,
                        level_price = memberprice,
                        price = (model.SellingPrice ?? 0).ToString("#0.00"),
                        price_content = "￥" + (model.SellingPrice ?? 0).ToString("#0.00"),
                        is_sales = model.GoodsStatus,
                        sales = "已售" + model.SalesNum + "件",
                        attr_groups = model.SpecificationList.Select(x => new
                        {
                            attr_group_id = x.Sort,
                            attr_group_name = x.Name,
                            attr_list = x.SpecificationValueList.Select(z => new
                            {
                                attr_id = z.Sort,
                                attr_name = z.Name,
                                pic_url = z.ImagePath
                            })
                        }),
                        attr = priceList,
                        goods_stock = model.InventoryNum,
                        goods_num = model.InventoryNum
                    });
                }
            }


            return ApiResult.Success("", new
            {
                RecommendStatus,
                List = RList
            });
        }

        /// <summary>
        /// 获取粉象模式   Vip等级id
        /// </summary>
        /// <param name="requestMsg"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAppletVipGradeInfo(object requestMsg)
        {
            var req = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            if (req.MallBaseId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            var Robj = productModule.GetAppletVipGradeInfo(req.TenantId, req.MallBaseId);
            return ApiResult.Success("", Robj);
        }

        #endregion

        #region 生产海报
        /// <summary>
        /// 商品海报
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetGoodsPoster()
        {
            string address = new HtmlToImgHelper().GetHtmlToImage();
            return ApiResult.Success("", address);
        }

        #endregion
    }
}