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;
using Mall.Model.Entity.BaseSetUp;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Authorization;
using Mall.Common.Enum.Goods;

namespace Mall.WebApi.Controllers.MallBase
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class AppletOrderController : BaseController
    {
        private readonly IHttpContextAccessor _accessor;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="accessor"></param>
        public AppletOrderController(IHttpContextAccessor accessor)
        {
            _accessor = accessor;
        }

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

        #region 购物车

        /// <summary>
        /// 获取用户购物车
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetGoodsShoppingCartPageList()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Goods_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Extend>(parms.msg.ToString());

            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.UserId = userInfo.UserId;
            demodel.SmallShopsId = parms.SmallShopsId;
            var list = orderModule.GetGoodsShoppingCartPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            var MallModel = orderModule.GetMiniProgramExtend(userInfo.MallBaseId);
            var listobj = list.Select(x => new
            {
                x.Id,
                x.GoodsId,
                x.GoodsName,
                x.CoverImage,
                x.Price,
                InventoryNum = x.GoodsClassify == 2 ? 1 : x.InventoryNum,
                x.SpecificationList,
                x.SpecificationSort,
                Number = x.GoodsClassify == 2 ? 1 : x.Number,
                x.GoodsStatus,
                x.TenantId,
                x.MallBaseId,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                FreeShippingName = x.FreeShippingModel.Name,
                FreeShippingFullMoneyPinkage = x.FreeShippingModel.FullMoneyPinkage ?? 0,
                FreeShippingFullNumPinkage = x.FreeShippingModel.FullNumPinkage ?? 0,
                x.FreeShippingModel.FreeShippingUrl,
                x.MarketingLogo,
                x.CourseScore
            });
            List<object> robj = new List<object>() {
                 new {
                     MallId =MallModel?.MallBaseId??0,
                     MallName =MallModel?.MallName??"",
                     GoodsList=listobj
                }
            };
            pagelist.pageData = robj;
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 加入购物车
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetGoodsShoppingCartInfo()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            RB_Goods_ShoppingCart_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_ShoppingCart_Extend>(req.msg.ToString());
            if ((demodel.GoodsId ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请传递商品id");
            }
            if ((demodel.Number ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("数量必须大于0");
            }
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.UserId = userInfo.UserId;
            demodel.SpecificationSort ??= "";
            return orderModule.SetGoodsShoppingCartGetInfo(demodel);
        }

        /// <summary>
        /// 设置购物车数量
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetGoodsShoppingCartNumGetInfo()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject prams = JObject.Parse(req.msg.ToString());
            int ShoppingCartId = prams.GetInt("ShoppingCartId", 0);
            int Number = prams.GetInt("Number", 0);
            if (ShoppingCartId <= 0 || Number <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            bool flag = orderModule.SetGoodsShoppingCartNumGetInfo(ShoppingCartId, Number, userInfo.TenantId, userInfo.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 删除购物车
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelGoodsShoppingCartInfo()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject prams = JObject.Parse(req.msg.ToString());
            string ShoppingCartIds = prams.GetStringValue("ShoppingCartIdList");
            if (string.IsNullOrEmpty(ShoppingCartIds))
            {
                return ApiResult.ParamIsNull();
            }
            try
            {
                List<int> scList = JsonConvert.DeserializeObject<List<int>>(ShoppingCartIds);
                ShoppingCartIds = string.Join(",", scList);
            }
            catch (Exception)
            {
                return ApiResult.ParamIsNull("");
            }

            bool flag = orderModule.DelGoodsShoppingCartInfo(ShoppingCartIds, userInfo.UserId, userInfo.TenantId, userInfo.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        #endregion

        #region 订单管理

        /// <summary>
        /// 我的订单分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAppletGoodsMyOrderPageList()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Goods_Order_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Order_Extend>(parms.msg.ToString());

            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.UserId = userInfo.UserId;
            demodel.Recycled = 2;
            demodel.OrderClassify = 0;
            if (demodel.OrderStatus == Common.Enum.Goods.OrderStatusEnum.WaitSendGoods)
            {
                demodel.OrderStatusIds = "2,6";//待处理也是待发货状态才有的
                demodel.OrderStatus = 0;
            }
            var list = orderModule.GetAppletGoodsMyOrderPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            //获取订阅消息
            var miniModel = programModule.GetMiniProgramModule(new RB_MiniProgram_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });

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

            if (miniModel != null)
            {
                if (!string.IsNullOrWhiteSpace(miniModel.RefundTpl))
                {
                    template_message_list.Add(miniModel.RefundTpl);
                }
                if (!string.IsNullOrWhiteSpace(miniModel.OrderCancelTpl))
                {
                    template_message_list.Add(miniModel.OrderCancelTpl);
                }
            }
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                template_message_list,
                x.OrderId,
                x.OrderNo,
                x.DeliveryMethod,
                DeliveryMethodName = x.DeliveryMethod.GetEnumName(),
                x.Income,
                x.FreightMoney,
                x.CouponMoney,
                x.DepositId,
                x.DepositMoney,
                x.PaymentWay,
                PaymentWayName = x.PaymentWay.GetEnumName(),
                DetailList = x.DetailList.Select(y => new
                {
                    y.Id,
                    y.GoodsId,
                    y.CoverImagePath,
                    y.OrderType,
                    OrderTypeName = y.OrderType.GetEnumName(),
                    y.GoodsName,
                    y.SpecificationSort,
                    SpecificationList = JsonConvert.DeserializeObject<List<string>>(y.Specification),
                    y.ProductCode,
                    y.Final_Price,
                    y.Number,
                    y.IsComment,
                    y.FreeShippingRemarks,
                    InsuranceMoney = y.InsuranceMoney ?? 0
                }),
                x.OrderStatus,
                OrderStatusName = x.OrderStatus.GetEnumName(),
                x.VersionSource,
                x.TenantId,
                x.MallBaseId,
                x.PresentFXGrade,
                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 GetAppletGoodsOrderNumStatistics()
        {
            var userInfo = AppletUserInfo;
            return orderModule.GetAppletGoodsOrderNumStatistics(userInfo.UserId, userInfo.TenantId, userInfo.MallBaseId);
        }

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

        /// <summary>
        /// 获取我的订单快递信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAppletMyOrderExpressInfo()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parms = JObject.Parse(req.msg.ToString());
            int OrderId = parms.GetInt("OrderId", 0);
            if (OrderId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            var Robj = orderModule.GetAppletMyOrderExpressInfo(OrderId, userInfo.TenantId, userInfo.MallBaseId);
            return ApiResult.Success("", Robj);
        }

        /// <summary>
        /// 结算页面详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAppletGoodsSettlementInfo()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            RB_Goods_Order_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Order_Extend>(req.msg.ToString());

            if (demodel.DetailList == null || !demodel.DetailList.Any())
            {
                return ApiResult.ParamIsNull("请传递商品信息");
            }
            foreach (var item in demodel.DetailList)
            {
                if ((item.GoodsId ?? 0) <= 0)
                {
                    return ApiResult.ParamIsNull("请传递商品id");
                }
                if ((item.Number ?? 0) <= 0)
                {
                    return ApiResult.ParamIsNull("请传递商品数量");
                }
            }
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.UserId = userInfo.UserId;
            return orderModule.GetAppletGoodsSettlementInfo(demodel);
        }

        /// <summary>
        /// 结算页面详情(赞羊字段)
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAppletGoodsSettlementInfoForZY()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            RB_Goods_Order_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Order_Extend>(req.msg.ToString());

            if (demodel.DetailList == null || !demodel.DetailList.Any())
            {
                return ApiResult.ParamIsNull("请传递商品信息");
            }
            foreach (var item in demodel.DetailList)
            {
                if ((item.GoodsId ?? 0) <= 0)
                {
                    return ApiResult.ParamIsNull("请传递商品id");
                }
                if ((item.Number ?? 0) <= 0)
                {
                    return ApiResult.ParamIsNull("请传递商品数量");
                }
            }
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.UserId = userInfo.UserId;
            demodel.SmallShopsId = req.SmallShopsId;
            return orderModule.GetAppletGoodsSettlementInfoForZY(demodel);
        }

        /// <summary>
        /// 结算页面详情(教育)
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAppletCourseSettlementInfo()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            RB_Goods_Order_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Order_Extend>(req.msg.ToString());

            if (demodel.DetailList == null || !demodel.DetailList.Any())
            {
                return ApiResult.ParamIsNull("请传递商品信息");
            }
            foreach (var item in demodel.DetailList)
            {
                if ((item.GoodsId ?? 0) <= 0)
                {
                    return ApiResult.ParamIsNull("请传递商品id");
                }
                if ((item.Number ?? 0) <= 0)
                {
                    return ApiResult.ParamIsNull("请传递商品数量");
                }
            }
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.UserId = userInfo.UserId;
            demodel.SmallShopsId = req.SmallShopsId;
            return orderModule.GetAppletCourseSettlementInfo(demodel);
        }

        /// <summary>
        /// 结算页面修改快递，获取快递费用
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAppletGoodsSettlementExpress()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            RB_Goods_Order_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Order_Extend>(req.msg.ToString());
            if ((demodel.ShoppingAddressId ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请传递收货地址id");
            }
            if (demodel.DetailList == null || !demodel.DetailList.Any())
            {
                return ApiResult.ParamIsNull("请传递商品信息");
            }
            foreach (var item in demodel.DetailList)
            {
                if ((item.GoodsId ?? 0) <= 0)
                {
                    return ApiResult.ParamIsNull("请传递商品id");
                }
                if ((item.Number ?? 0) <= 0)
                {
                    return ApiResult.ParamIsNull("请传递商品数量");
                }
            }
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.UserId = userInfo.UserId;
            return orderModule.GetAppletGoodsSettlementExpress(demodel);
        }

        /// <summary>
        /// 商城下单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetAppletGoodsOrderInfo()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            RB_Goods_Order_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Order_Extend>(req.msg.ToString());
            if (demodel.IsFormShoppingCart == 1)
            {
                if (demodel.ShoppingCartIdList == null || !demodel.ShoppingCartIdList.Any())
                {
                    return ApiResult.ParamIsNull("请传递购物车id");
                }
            }
            if (string.IsNullOrEmpty(demodel.Consignee))
            {
                return ApiResult.ParamIsNull("请传递收件人");
            }
            if (string.IsNullOrEmpty(demodel.Mobile))
            {
                return ApiResult.ParamIsNull("请传递收件人手机号码");
            }
            if (demodel.DeliveryMethod != Common.Enum.Goods.OrderDeliveryMethodEnum.VerificationShop)
            {
                if ((demodel.District ?? 0) <= 0)
                {
                    return ApiResult.ParamIsNull("收货地址有误");
                }
                if (string.IsNullOrEmpty(demodel.ShoppingAddress))
                {
                    return ApiResult.ParamIsNull("收货详细地址不能为空");
                }
            }

            if (demodel.DetailList == null || !demodel.DetailList.Any())
            {
                return ApiResult.ParamIsNull("请传递商品信息");
            }
            foreach (var item in demodel.DetailList)
            {
                if ((item.GoodsId ?? 0) <= 0)
                {
                    return ApiResult.ParamIsNull("请传递商品id");
                }
                if ((item.Number ?? 0) <= 0)
                {
                    return ApiResult.ParamIsNull("请传递商品数量");
                }
                if (item.SpecificationList == null || !item.SpecificationList.Any())
                {
                    return ApiResult.ParamIsNull("请传递规格名SpecificationList");
                }
                item.Specification = JsonConvert.SerializeObject(item.SpecificationList);
            }

            if ((demodel.Income ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("订单金额不正确");
            }

            demodel.BuyerMessage ??= "";//买家留言
            demodel.OrderSource ??= UserSourceEnum.WeiXin;
            #region 赋默认值
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.Country ??= 2;
            demodel.OrderStatus = Common.Enum.Goods.OrderStatusEnum.NonPayment;
            demodel.CreateDate = DateTime.Now;
            demodel.Fee ??= 0;
            demodel.FreightMoney ??= 0;
            demodel.HistoryOrderStatus ??= 0;
            demodel.IsApplyForCancel ??= 2;
            demodel.IsOrderCommission ??= 2;
            demodel.MerchantsNo ??= "";
            demodel.Recycled ??= 2;
            demodel.Refund ??= 0;
            demodel.Status = 0;
            demodel.AnchorName ??= "";
            demodel.UpdateDate = DateTime.Now;
            demodel.UserId = userInfo.UserId;
            demodel.SmallShopsId = req.SmallShopsId;
            demodel.OrderClassify = 0;
            #endregion

            return orderModule.SetAppletGoodsOrderInfo(demodel);
        }

        /// <summary>
        /// 教育下单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetAppletCourseOrderInfo()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            RB_Goods_Order_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Order_Extend>(req.msg.ToString());
            if (demodel.IsFormShoppingCart == 1)
            {
                if (demodel.ShoppingCartIdList == null || !demodel.ShoppingCartIdList.Any())
                {
                    return ApiResult.ParamIsNull("请传递购物车id");
                }
            }

            if (demodel.DetailList == null || !demodel.DetailList.Any())
            {
                return ApiResult.ParamIsNull("请传递商品信息");
            }
            foreach (var item in demodel.DetailList)
            {
                if ((item.GoodsId ?? 0) <= 0)
                {
                    return ApiResult.ParamIsNull("请传递商品id");
                }
                if ((item.Number ?? 0) <= 0)
                {
                    return ApiResult.ParamIsNull("请传递商品数量");
                }
            }

            if ((demodel.Use_Education_Id ?? 0) == 0 && (demodel.Income ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("订单金额不正确");
            }

            demodel.BuyerMessage ??= "";//买家留言
            demodel.OrderSource ??= UserSourceEnum.WeiXin;
            #region 赋默认值
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.Country ??= 2;
            demodel.OrderStatus = Common.Enum.Goods.OrderStatusEnum.NonPayment;
            demodel.CreateDate = DateTime.Now;
            demodel.Fee ??= 0;
            demodel.FreightMoney ??= 0;
            demodel.HistoryOrderStatus ??= 0;
            demodel.IsApplyForCancel ??= 2;
            demodel.IsOrderCommission ??= 2;
            demodel.MerchantsNo ??= "";
            demodel.Recycled ??= 2;
            demodel.Refund ??= 0;
            demodel.Status = 0;
            demodel.AnchorName ??= "";
            demodel.UpdateDate = DateTime.Now;
            demodel.UserId = userInfo.UserId;
            demodel.SmallShopsId = req.SmallShopsId;
            demodel.OrderClassify = 2;
            #endregion

            return orderModule.SetAppletCourseOrderInfo(demodel);
        }

        /// <summary>
        /// 司导下单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetAppletSDGoodsOrderInfo()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            RB_Goods_Order_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Order_Extend>(req.msg.ToString());
            if (string.IsNullOrEmpty(demodel.Consignee))
            {
                return ApiResult.ParamIsNull("请传递联系人");
            }
            if (string.IsNullOrEmpty(demodel.Mobile))
            {
                return ApiResult.ParamIsNull("请传递联系人手机号码");
            }
            demodel.DeliveryMethod = Common.Enum.Goods.OrderDeliveryMethodEnum.VerificationShop;

            if ((demodel.District ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("接送地址有误");
            }
            if (string.IsNullOrEmpty(demodel.ShoppingAddress))
            {
                return ApiResult.ParamIsNull("接送地址不能为空");
            }
            if (!demodel.TripSTime.HasValue)
            {
                return ApiResult.ParamIsNull("请传递出发时间");
            }

            if (demodel.DetailList == null || !demodel.DetailList.Any())
            {
                return ApiResult.ParamIsNull("请传递商品信息");
            }
            foreach (var item in demodel.DetailList)
            {
                if ((item.GoodsId ?? 0) <= 0)
                {
                    return ApiResult.ParamIsNull("请传递商品id");
                }
                if ((item.Number ?? 0) <= 0)
                {
                    return ApiResult.ParamIsNull("请传递商品数量");
                }
            }

            if ((demodel.Income ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("订单金额不正确");
            }

            demodel.BuyerMessage ??= "";//买家留言
            demodel.OrderSource ??= Common.Enum.User.UserSourceEnum.WeiXin;
            #region 赋默认值
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.Country ??= 2;
            demodel.OrderStatus = Common.Enum.Goods.OrderStatusEnum.NonPayment;
            demodel.CreateDate = DateTime.Now;
            demodel.Fee ??= 0;
            demodel.FreightMoney ??= 0;
            demodel.HistoryOrderStatus ??= 0;
            demodel.IsApplyForCancel ??= 2;
            demodel.IsOrderCommission ??= 2;
            demodel.MerchantsNo ??= "";
            demodel.Recycled ??= 2;
            demodel.Refund ??= 0;
            demodel.Status = 0;
            demodel.AnchorName ??= "";
            demodel.UpdateDate = DateTime.Now;
            demodel.UserId = userInfo.UserId;
            demodel.SmallShopsId = req.SmallShopsId;
            demodel.OrderClassify = 1;
            demodel.DestinationAddress ??= "";
            #endregion

            return orderModule.SetAppletSDGoodsOrderInfo(demodel);
        }

        /// <summary>
        /// 线下服务下单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetAppletOfflineGoodsOrderInfo()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            RB_Goods_Order_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Order_Extend>(req.msg.ToString());
            if (string.IsNullOrEmpty(demodel.Mobile))
            {
                return ApiResult.ParamIsNull("请传递联系人手机号码");
            }
            demodel.DeliveryMethod = Common.Enum.Goods.OrderDeliveryMethodEnum.VerificationShop;

            if ((demodel.Income ?? 0) < 0)
            {
                return ApiResult.ParamIsNull("订单金额不正确");
            }
            if (demodel.StoresId <= 0)
            {
                return ApiResult.ParamIsNull("请选择服务门店");
            }
            demodel.Consignee = userInfo.Name;
            demodel.BuyerMessage ??= "";//买家留言
            demodel.OrderSource ??= Common.Enum.User.UserSourceEnum.WeiXin;
            #region 赋默认值
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;

            demodel.Country ??= 2;
            demodel.OrderStatus = Common.Enum.Goods.OrderStatusEnum.NonPayment;
            demodel.CreateDate = DateTime.Now;
            demodel.Fee ??= 0;
            demodel.FreightMoney ??= 0;
            demodel.HistoryOrderStatus ??= 0;
            demodel.IsApplyForCancel ??= 2;
            demodel.IsOrderCommission ??= 2;
            demodel.MerchantsNo ??= "";
            demodel.Recycled ??= 2;
            demodel.Refund ??= 0;
            demodel.Status = 0;
            demodel.AnchorName ??= "";
            demodel.UpdateDate = DateTime.Now;
            demodel.UserId = userInfo.UserId;
            demodel.SmallShopsId = req.SmallShopsId;
            demodel.OrderClassify = 3;
            demodel.DestinationAddress ??= "";
            #endregion
            bool flag= orderModule.SetAppletOfflineGoodsOrderModule(demodel,out string message);
            return flag ? ApiResult.Success(message: message,data: new { demodel.OrderId}) : ApiResult.Failed(message: message);
        }

        /// <summary>
        /// 修改订单线下服务人员
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetOfflineOrderServicepersion()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parms = JObject.Parse(req.msg.ToString());
            int OrderId = parms.GetInt("OrderId");
            int ServicepersonalId = parms.GetInt("ServicepersonalId");
            bool flag = orderModule.SetOfflineOrderServicepersionModule(OrderId, ServicepersonalId);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// ERP下单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ApiResult SetERPGoodsOrderInfo()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int NewUserId = parms.GetInt("NewUserId");
            var userInfo = UserReidsCache.GetAppletUserLoginInfo(NewUserId);
            RB_Goods_Order_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Order_Extend>(req.msg.ToString());
            if (demodel.IsFormShoppingCart == 1)
            {
                if (demodel.ShoppingCartIdList == null || !demodel.ShoppingCartIdList.Any())
                {
                    return ApiResult.ParamIsNull("请传递购物车id");
                }
            }
            if (string.IsNullOrEmpty(demodel.Consignee))
            {
                return ApiResult.ParamIsNull("请传递收件人");
            }
            if (string.IsNullOrEmpty(demodel.Mobile))
            {
                return ApiResult.ParamIsNull("请传递收件人手机号码");
            }
            if (demodel.DeliveryMethod != Common.Enum.Goods.OrderDeliveryMethodEnum.VerificationShop)
            {
                if ((demodel.District ?? 0) <= 0)
                {
                    return ApiResult.ParamIsNull("收货地址有误");
                }
                if (string.IsNullOrEmpty(demodel.ShoppingAddress))
                {
                    return ApiResult.ParamIsNull("收货详细地址不能为空");
                }
            }

            if (demodel.DetailList == null || !demodel.DetailList.Any())
            {
                return ApiResult.ParamIsNull("请传递商品信息");
            }
            foreach (var item in demodel.DetailList)
            {
                if ((item.GoodsId ?? 0) <= 0)
                {
                    return ApiResult.ParamIsNull("请传递商品id");
                }
                if ((item.Number ?? 0) <= 0)
                {
                    return ApiResult.ParamIsNull("请传递商品数量");
                }
                if (item.SpecificationList == null || !item.SpecificationList.Any())
                {
                    return ApiResult.ParamIsNull("请传递规格名SpecificationList");
                }
                item.Specification = JsonConvert.SerializeObject(item.SpecificationList);
            }

            if ((demodel.Income ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("订单金额不正确");
            }

            demodel.BuyerMessage ??= "";//买家留言
            demodel.OrderSource ??= UserSourceEnum.WeiXin;
            #region 赋默认值
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.Country ??= 2;
            demodel.OrderStatus = Common.Enum.Goods.OrderStatusEnum.NonPayment;
            demodel.CreateDate = DateTime.Now;
            demodel.Fee ??= 0;
            demodel.FreightMoney ??= 0;
            demodel.HistoryOrderStatus ??= 0;
            demodel.IsApplyForCancel ??= 2;
            demodel.IsOrderCommission ??= 2;
            demodel.MerchantsNo ??= "";
            demodel.Recycled ??= 2;
            demodel.Refund ??= 0;
            demodel.Status = 0;
            demodel.AnchorName ??= "";
            demodel.UpdateDate = DateTime.Now;
            demodel.UserId = userInfo.UserId;
            demodel.SmallShopsId = parms.GetInt("NewShopId");
            demodel.OrderClassify = 0;
            #endregion

            return orderModule.SetAppletGoodsOrderInfo(demodel);
        }

        /// <summary>
        /// ERP修改订单状态
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ApiResult UpdateERPGoodsOrderInfo()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            RB_Goods_Order_Extend extModel = new RB_Goods_Order_Extend()
            {
                OrderId = parms.GetInt("OrderId"),
                MerchantsNo = parms.GetStringValue("MerchantsNo"),
                OrderStatus = OrderStatusEnum.WaitSendGoods,
                PaymentTime = DateTime.Now,
            };

            RB_Goods_Online_Trade_Extend tradeModel = new RB_Goods_Online_Trade_Extend()
            {
                User_Id = parms.GetInt("User_Id"),
                Type = 1,
                OrderId = parms.GetInt("OrderId"),
                Out_Trade_No = parms.GetStringValue("Out_Trade_No"),
                Transaction_Id = parms.GetStringValue("Transaction_Id"),
                PayWay = (OrderPayTypeEnum)parms.GetInt("PayWay"),
                PayType = "JSAPI",
                Money = parms.GetDecimal("Money"),
                Remarks = parms.GetStringValue("Remarks"),
                Pay_Result = 0,
                Pay_Date = DateTime.Now,
                IsRefund = 2,
                RefundMoney = 0,
                RefundStatus = 0,
                RefundTrade_Order = "",
                Refund_Id = "",
                Refund_Date = null,
                FinanceId = 0,
                MallBaseId = 1,
                TenantId = 1,
                CreateDate = DateTime.Now,
            };
            bool flag = orderModule.UpdateERPGoodsOrderInfoModule(extModel, tradeModel);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 返佣初始化
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetAppletOrderCommissionInitialize()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int OrderId = parms.GetInt("OrderId", 0);

            bool flag = orderModule.SetAppletOrderCommissionInitialize(OrderId);
            return ApiResult.Success("", flag);
        }

        /// <summary>
        /// 设置订单其他付款
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetAppletGoodsOrderOtherPay()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parms = JObject.Parse(req.msg.ToString());
            int OrderId = parms.GetInt("OrderId", 0);
            int Type = parms.GetInt("Type", 1);//1 货到付款  2 余额付款
            if (OrderId <= 0)
            {
                return ApiResult.ParamIsNull("请传递订单id");
            }
            if (Type != 1 && Type != 2)
            {
                return ApiResult.ParamIsNull("类型不正确");
            }

            string msg = orderModule.SetAppletGoodsOrderOtherPay(OrderId, Type, userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 未付款取消订单/已付款申请取消订单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult CancelAppletGoodsOrderInfo()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parms = JObject.Parse(req.msg.ToString());
            int OrderId = parms.GetInt("OrderId", 0);
            int Type = parms.GetInt("Type", 1);//1未付款取消  2已付款未发货申请取消
            string Remark = parms.GetStringValue("Remark");//type=2 申请备注
            if (OrderId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            var omodel = orderModule.GetOrderInfo(OrderId);
            if (omodel == null)
            {
                return ApiResult.Failed("订单不存在");
            }
            if (omodel.OrderClassify == 1)
            {
                //验证可提前取消时间
                string msg = orderModule.ValidateSDOrderCanCancel(omodel);
                if (msg != "")
                {
                    return ApiResult.Failed(msg);
                }
            }
            if (string.IsNullOrEmpty(Remark))
            {
                Remark = "无";
            }
            bool flag = orderModule.CancelAppletGoodsOrderInfo(OrderId, Type, Remark, userInfo.UserId, userInfo.TenantId, userInfo.MallBaseId);
            if (flag) { return ApiResult.Success(); } else { return ApiResult.Failed(); }
        }

        /// <summary>
        /// 确认收货
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetAppletOrderGoodsReceiving()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parms = JObject.Parse(req.msg.ToString());
            int OrderId = parms.GetInt("OrderId", 0);
            if (OrderId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            bool flag = orderModule.SetAppletOrderGoodsReceiving(OrderId, userInfo.UserId, userInfo.TenantId, userInfo.MallBaseId, _accessor);
            if (flag) { return ApiResult.Success(); } else { return ApiResult.Failed(); }
        }

        #endregion

        #region 订单售后

        /// <summary>
        /// 获取我的订单商品售后申请页面 订单信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAppletMyOrderAfterSaleInfo()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parms = JObject.Parse(req.msg.ToString());
            int OrderDetailId = parms.GetInt("OrderDetailId", 0);
            if (OrderDetailId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            return orderModule.GetAppletMyOrderAfterSaleInfo(OrderDetailId);
        }

        /// <summary>
        /// 申请售后
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetAppletMyOrderAfterSale()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            RB_Goods_OrderAfterSale_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_OrderAfterSale_Extend>(req.msg.ToString());
            if ((demodel.OrderDetialId ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请传递订单明细id");
            }
            if (string.IsNullOrEmpty(demodel.Remark))
            {
                return ApiResult.ParamIsNull("请输入退换货原因");
            }
            if (demodel.Type == 1)
            {
                if ((demodel.Refund ?? 0) <= 0)
                {
                    return ApiResult.ParamIsNull("请输入退款金额");
                }
            }
            if ((demodel.ReNumber ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("数量不正确");
            }

            var detailModel = orderModule.GetOrderDetailInfo(demodel.OrderDetialId ?? 0);
            var omodel = orderModule.GetOrderInfo(detailModel?.OrderId ?? 0);
            if (omodel == null)
            {
                return ApiResult.ParamIsNull("订单不存在");
            }
            if (omodel.OrderStatus != Common.Enum.Goods.OrderStatusEnum.WaitReceiving && omodel.OrderStatus != Common.Enum.Goods.OrderStatusEnum.Received && omodel.OrderStatus != Common.Enum.Goods.OrderStatusEnum.Completed)
            {
                return ApiResult.ParamIsNull("订单状态不正确");
            }

            //查询售后时间
            var mallbaseModel = orderModule.GetMallBaseInfo(userInfo.TenantId, userInfo.MallBaseId);
            if (mallbaseModel != null)
            {
                if (mallbaseModel.AfterTime > 0)
                {
                    //获取订单发货时间                    
                    if (omodel != null && omodel.OrderStatus > Common.Enum.Goods.OrderStatusEnum.WaitReceiving && omodel.ReceivingTime.HasValue)
                    {
                        if (omodel.ReceivingTime.Value.AddDays(mallbaseModel.AfterTime) < DateTime.Now)
                        {
                            return ApiResult.ParamIsNull("已超过售后期限(" + mallbaseModel.AfterTime + "天)，无法申请售后");
                        }
                        else
                        {
                            //验证 佣金是否已发放
                            if (orderModule.GetOrderCommissionIsSend(demodel.OrderDetialId ?? 0))
                            {
                                return ApiResult.ParamIsNull("该订单已返佣，无法申请售后");
                            }
                        }
                    }
                }
                else
                {
                    if (omodel.OrderStatus != Common.Enum.Goods.OrderStatusEnum.WaitReceiving)
                    {
                        return ApiResult.ParamIsNull("订单状态不正确");
                    }
                }
            }

            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.UserId = userInfo.UserId;
            demodel.Status = 0;
            demodel.ReOrderStatus = Common.Enum.Goods.OrderAfterSaleStatusEnum.Auditing;
            if (demodel.VoucherList != null && demodel.VoucherList.Any())
            {
                demodel.Voucher = JsonConvert.SerializeObject(demodel.VoucherList);
            }
            bool flag = orderModule.SetAppletMyOrderAfterSale(demodel);
            if (flag) { return ApiResult.Success(); } else { return ApiResult.Failed(); }
        }

        /// <summary>
        /// 获取买家发货页面详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAppletOrderBuyerToDeliverInfo()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parms = JObject.Parse(req.msg.ToString());
            int ReOrderId = parms.GetInt("ReOrderId", 0);
            if (ReOrderId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            return orderModule.GetAppletOrderBuyerToDeliverInfo(ReOrderId);
        }

        /// <summary>
        /// 用户发货
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetAppletOrderSendGoods()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parms = JObject.Parse(req.msg.ToString());
            int ReOrderId = parms.GetInt("ReOrderId", 0);
            int ExpressId = parms.GetInt("ExpressId", 0);
            string ExpressNumber = parms.GetStringValue("ExpressNumber");
            if (ReOrderId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            if (ExpressId <= 0)
            {
                return ApiResult.ParamIsNull("请选择快递");
            }
            if (string.IsNullOrEmpty(ExpressNumber))
            {
                return ApiResult.ParamIsNull("请输入快递单号");
            }

            bool flag = orderModule.SetAppletOrderSendGoods(ReOrderId, ExpressId, ExpressNumber, userInfo.TenantId, userInfo.MallBaseId);
            if (flag) { return ApiResult.Success(); } else { return ApiResult.Failed(); }
        }

        /// <summary>
        /// 获取售后订单详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAppletOrderAfterSaleInfo()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parms = JObject.Parse(req.msg.ToString());
            int ReOrderId = parms.GetInt("ReOrderId", 0);
            if (ReOrderId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            return orderModule.GetAppletOrderAfterSaleInfo(ReOrderId, userInfo.TenantId, userInfo.MallBaseId);
        }

        /// <summary>
        /// 售后订单分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAppletOrderAfterPageList()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Goods_OrderAfterSale_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_OrderAfterSale_Extend>(parms.msg.ToString());

            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.UserId = userInfo.UserId;
            var list = orderModule.GetAppletOrderAfterPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.ReOrderId,
                x.ReOrderNo,
                OrderDetailModel = new
                {
                    x.OrderDetailModel.Id,
                    x.OrderDetailModel.GoodsName,
                    x.OrderDetailModel.GoodsId,
                    x.OrderDetailModel.CoverImagePath,
                    SpecificationList = JsonConvert.DeserializeObject<List<string>>(x.OrderDetailModel.Specification),
                    x.OrderDetailModel.Final_Price
                },
                x.Type,
                x.ReNumber,
                x.Remark,
                x.Income,
                x.Refund,
                x.RefundActual,
                x.ReOrderStatus,
                ReOrderStatusName = x.ReOrderStatus.GetEnumName(),
                x.TenantId,
                x.MallBaseId,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : ""
            });
            return ApiResult.Success("", pagelist);
        }

        #region 获取快递公司信息
        public ApiResult GetExpressInfo()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            var query = new RB_Logistics_Express();
            var list = orderModule.GetLogisticsExpressList(query);
            var result = list.Select(x => new
            {
                x.ID,
                x.Name,
                x.ExpressCode
            });
            return ApiResult.Success("获取成功", result);
        }
        #endregion

        #endregion

        #region 订单评价

        /// <summary>
        /// 获取商品待评论列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAppletGoodsWaitCommentPageList()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Goods_OrderDetail_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_OrderDetail_Extend>(parms.msg.ToString());

            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.UserId = userInfo.UserId;
            var list = orderModule.GetAppletGoodsWaitCommentPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                OrderDetailId = x.Id,
                x.GoodsId,
                x.GoodsName,
                x.CoverImage,
                x.SpecificationList,
                x.IsComment,
                x.OrderId,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                x.CarName,
                x.CarColorName,
                x.CarBrandName,
                x.GuideName,
                x.GuidePhoto,
                x.ServiceDate,
                x.ServiceTime,
                x.ServicepersonalId,
                x.ServicepersonalName,
                x.StoresIds,
                x.ServicepersonalHead,
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 获取商品评论分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAppletGoodsCommentPageList()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Goods_Comment_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Comment_Extend>(parms.msg.ToString());

            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.Is_Show = 1;
            var list = orderModule.GetAppletGoodsCommentPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.UserId,
                UserName = x.Is_Anonymity == 1 ? "匿名用户" : x.UserName,
                UserPhotoPath = x.UserPhotoPath ?? "",
                x.CommentGrade,
                CommentGradeName = x.CommentGrade.GetEnumName(),
                x.CommentScore,
                x.CommentImgList,
                x.Content,
                x.Reply,
                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 GetAppletGoodsCommentStatistics()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parms = JObject.Parse(req.msg.ToString());
            int GoodsId = parms.GetInt("GoodsId", 0);

            return orderModule.GetAppletGoodsCommentStatistics(GoodsId, userInfo.TenantId, userInfo.MallBaseId);
        }

        /// <summary>
        /// 用户新增评论
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetGoodsCommentInfo()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            RB_Goods_Comment_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Comment_Extend>(req.msg.ToString());
            if ((demodel.OrderDetailId ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请传递订单明细OrderDetailId");
            }
            if ((demodel.GoodsId ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请传递商品");
            }
            if (string.IsNullOrEmpty(demodel.Content))
            {
                return ApiResult.ParamIsNull("请输入评价内容");
            }
            demodel.CommentImage = "";
            if (demodel.CommentImgList != null && demodel.CommentImgList.Any())
            {
                demodel.CommentImage = JsonConvert.SerializeObject(demodel.CommentImgList);
            }
            demodel.CommentGrade ??= Common.Enum.Goods.GoodsCommentTypeEnum.Praise;
            demodel.CommentScore ??= 5;
            if (demodel.CommentScore == 3 || demodel.CommentScore == 2)
            {
                demodel.CommentGrade = Common.Enum.Goods.GoodsCommentTypeEnum.Medium;
            }
            else if (demodel.CommentScore == 1)
            {
                demodel.CommentGrade = Common.Enum.Goods.GoodsCommentTypeEnum.Negative;
            }

            demodel.UserPhoto ??= 0;
            demodel.Is_Top ??= 2;
            demodel.Is_Show ??= 1;
            demodel.Is_Anonymity ??= 2;
            demodel.UserId ??= 0;
            demodel.Reply ??= "";

            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.UserId = userInfo.UserId;
            demodel.UserName = userInfo.Name;
            demodel.PlatformSource = userInfo.Source;
            demodel.Status = 0;
            demodel.CreateDate = DateTime.Now;
            demodel.UpdateDate = DateTime.Now;

            bool flag = orderModule.SetGoodsCommentInfo(demodel);
            if (flag)
            {

                var dmodel = orderModule.GetOrderDetailInfo(demodel.OrderDetailId ?? 0);
                if (dmodel != null && dmodel.CommentGiveIntegral > 0 && demodel.UserId > 0)
                {
                    Model.Entity.User.RB_Member_Integral memberIntegralModel = new Model.Entity.User.RB_Member_Integral
                    {
                        UserId = demodel.UserId,
                        Type = Common.Enum.MarketingCenter.RecordTypeEnum.Income,
                        PlatformType = demodel.PlatformSource,
                        Integral = dmodel.CommentGiveIntegral,
                        Description = "评论赠送" + dmodel.CommentGiveIntegral + "积分",
                        TenantId = demodel.TenantId,
                        MallBaseId = demodel.MallBaseId,
                        Remarks = "评论商品" + dmodel.GoodsName + "赠送" + dmodel.CommentGiveIntegral + "积分",
                        CreateDate = demodel.CreateDate,
                        OrderId = dmodel.OrderId
                    };
                    bool integralResult = orderModule.AddMemberIntegral(memberIntegralModel);
                    if (integralResult)
                    {
                        return ApiResult.CouponSuccess(ResultCode.Success,2, "", dmodel.CommentGiveIntegral.ToString());
                    }
                    else
                    {
                        return ApiResult.CouponSuccess(ResultCode.Fail, 2, "", "");
                    }
                }

                return ApiResult.CouponSuccess(ResultCode.Fail,2, "", "");


            }
            else { return ApiResult.CouponFailed(ResultCode.Fail, 2, "", ""); }
        }

        #endregion

        #region 分销中心

        /// <summary>
        /// 获取用户分销订单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetUserDistributionOrdersPageList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            RB_Goods_OrderCommission_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_OrderCommission_Extend>(req.msg.ToString());
            //HK 2020-08-27新增
            JObject parms = JObject.Parse(req.msg.ToString());

            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.UserId = userInfo.UserId;
            List<RB_Goods_OrderCommission_Extend> list = new List<RB_Goods_OrderCommission_Extend>();
            long count = 0;
            if (parms.GetInt("NewUserId") > 0)
            {
                demodel.UserId = parms.GetInt("NewUserId");
                list = orderModule.GetDistributionOrdersPageListModule(pagelist.pageIndex, pagelist.pageSize, out count, demodel);
            }
            else
            {
                list = orderModule.GetDistributionOrdersPageList_V2(pagelist.pageIndex, pagelist.pageSize, out count, demodel);
            }

            List<RB_Member_User_Extend> memberList = new List<RB_Member_User_Extend>();
            if (list != null && list.Count > 0)
            {
                var userIds = string.Join(",", list.Select(qitem => qitem.UserId));
                if (!string.IsNullOrWhiteSpace(userIds))
                {
                    memberList = userModule.GetUserListExtModule(new RB_Member_User_Extend() { UserIds = userIds });
                }
            }
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.OrderId,
                x.OrderNo,
                x.Grade,
                x.GradeDescription,
                DetailList = x.OrderDetailList.Select(y => new
                {
                    y.Id,
                    y.CoverImagePath,
                    y.OrderType,
                    OrderTypeName = y.OrderType.GetEnumName(),
                    y.GoodsName,
                    SpecificationList = JsonConvert.DeserializeObject<List<string>>(y.Specification),
                    y.ProductCode,
                    y.Final_Price,
                    y.Number
                }),
                Icon = memberList?.Where(qitem => qitem.Id == x.UserId)?.FirstOrDefault()?.Icon ?? "",
                x.UserId,
                x.UserName,
                x.Photo,
                x.Mobile,
                x.Remark,
                x.Commission,
                x.CommissionState,
                StatusName = x.DistrbutionOrderSelectStatus == 1 ? "待付款" : x.DistrbutionOrderSelectStatus == 5 ? "已完成" : "已付款",
                x.OrderClassify,
                x.TenantId,
                x.MallBaseId,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : ""
            });
            return ApiResult.Success("", pagelist);
        }

        #endregion

        #region 查询物流

        /// <summary>
        /// 获取快递信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetOrderExpressInfo()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parms = JObject.Parse(req.msg.ToString());
            int ExpressId = parms.GetInt("ExpressId", 0);
            string ExpressNumber = parms.GetStringValue("ExpressNumber");
            if (ExpressId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            if (string.IsNullOrEmpty(ExpressNumber))
            {
                return ApiResult.ParamIsNull();
            }

            try
            {
                var model = orderModule.GerExpressModel(ExpressId);
                if (model == null)
                {
                    return ApiResult.Failed("快递不存在");
                }

                //获取快递配置

                var configModel = orderModule.GetExpressConfig(userInfo.TenantId, userInfo.MallBaseId);
                if (configModel == null) {
                    return ApiResult.Failed("未配置快递参数，无法查询");
                }
                if (configModel.Type == 1)
                {
                    string alimsg = orderModule.GetOrderExpressInfoForAliyun(ExpressNumber, model.ExpressCode, configModel.AppCode, configModel.RquUrl);
                    JObject Rparms = JObject.Parse(alimsg);
                    if (Rparms.GetStringValue("Success").ToLower() == "true")
                    {
                        List<Model.Query.ExpressTraces> list = JsonConvert.DeserializeObject<List<Model.Query.ExpressTraces>>(Rparms.GetStringValue("Traces"));
                        if (list.Any())
                        {
                            list = list.OrderByDescending(x => x.AcceptTime).ToList();
                        }
                        return ApiResult.Success("", list);
                    }
                    else
                    {
                        return ApiResult.Failed("未能查询到该快递信息");
                    }
                }
                else if (configModel.Type == 2)
                {
                    var jsonStr = orderModule.GetOrderExpressInfo(model.ExpressCode, ExpressNumber, configModel.AppID, configModel.AppKey, configModel.RquUrl);
                    JObject Rparms = JObject.Parse(jsonStr);
                    if (Rparms.GetStringValue("Success").ToLower() == "true")
                    {
                        List<Model.Query.ExpressTraces> list = JsonConvert.DeserializeObject<List<Model.Query.ExpressTraces>>(Rparms.GetStringValue("Traces"));
                        if (list.Any())
                        {
                            list = list.OrderByDescending(x => x.AcceptTime).ToList();
                        }
                        return ApiResult.Success("", list);
                    }
                    else
                    {
                        return ApiResult.Failed("未能查询到该快递信息");
                    }
                }
                else {
                    return ApiResult.Failed("未查询到快递配置");
                }
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "GetOrderExpressInfo");
                return ApiResult.Failed("出错了，请联系管理员");
            }
        }
        #endregion

        #region 活动管理

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

            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.Enable = 1;
            var list = activityModule.GetGoodsActivityPageListForApplet(pagelist.pageIndex, pagelist.pageSize, out long count, demodel, userInfo.UserId);

            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,
                MyOrderMoney = x.Final_Price,
                MyGoodsNum = x.Number,
                MyOrderNum = x.OrderTNum,
                x.RangeType,
                x.RangeList,
                x.Way,
                x.PrizeName,
                x.PrizeImage,
                StartTime = x.StartTime.ToString("yyyy-MM-dd"),
                EndTime = x.EndTime.ToString("yyyy-MM-dd"),
                SurplusDay = demodel.QActivityState == 1 ? (x.EndTime - DateTime.Now).Days : 0,
                SurplusHour = demodel.QActivityState == 1 ? (x.EndTime - DateTime.Now).Hours : 0,
                SurplusMin = demodel.QActivityState == 1 ? (x.EndTime - DateTime.Now).Minutes : 0,
                x.CoverImage,
                x.Description,
                x.IsFinish,
                ReceiveTime = x.ReceiveTime.ToString("yyyy-MM-dd")
            });
            return ApiResult.Success("", pagelist);
        }

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

            var model = activityModule.GetGoosdActivityInfo(ActivityId, userInfo.UserId);
            return ApiResult.Success("", new
            {
                model.Id,
                model.ActivityName,
                model.Tier,
                model.Type,
                model.OrderNum,
                model.OrderMoney,
                model.GoodsNum,
                model.RangeType,
                model.RangeList,
                model.Way,
                model.PrizeName,
                model.PrizeImage,
                StartTime = model.StartTime.ToString("yyyy-MM-dd"),
                EndTime = model.EndTime.ToString("yyyy-MM-dd"),
                SurplusDay = Math.Ceiling((model.EndTime - DateTime.Now).TotalDays),
                model.CoverImage,
                model.Description,
                model.ActiveObject,
                ReceiveTime = model.ReceiveTime.ToString("yyyy-MM-dd")
            });
        }

        /// <summary>
        /// 获取我的奖励
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetGoodsMyActivityPrizeList() {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            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 = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.UserId = userInfo.UserId;
            var list = activityModule.GetGoodsMyActivityPrizeList(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.Code,
                x.State,
                x.CoverImage,
                x.PrizeName,
                x.PrizeImage,
                ReceiveTime = x.ReceiveTime.ToString("yyyy-MM-dd"),
                SurplusDay = Math.Ceiling((x.ReceiveTime - DateTime.Now).TotalDays),
                x.Way
            });
            return ApiResult.Success("", pagelist);
        }

        #endregion
    }
}