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;

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

        private readonly OrderModule orderModule = new OrderModule();
        private readonly Module.User.MiniProgramModule programModule = new Module.User.MiniProgramModule();
        #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;
            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,
                x.InventoryNum,
                x.SpecificationList,
                x.SpecificationSort,
                x.Number,
                x.GoodsStatus,
                x.TenantId,
                x.MallBaseId,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : ""
            });
            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;
            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.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
                }),
                x.OrderStatus,
                OrderStatusName = x.OrderStatus.GetEnumName(),
                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 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);
            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;
            return orderModule.GetAppletGoodsSettlementInfoForZY(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.UpdateDate = DateTime.Now;
            demodel.UserId = userInfo.UserId;
            #endregion

            return orderModule.SetAppletGoodsOrderInfo(demodel);
        }

        /// <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();
            }
            //if (Type == 2) {
            //    if (string.IsNullOrEmpty(Remark)) {
            //        return ApiResult.ParamIsNull("请输入取消申请备注");
            //    }
            //}
            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);
            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, userInfo.UserId, userInfo.TenantId, userInfo.MallBaseId);
        }

        /// <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 mallbaseModel = orderModule.GetMallBaseInfo(userInfo.TenantId, userInfo.MallBaseId);
            //if (mallbaseModel == null) {
            //    return ApiResult.ParamIsNull("请联系管理员，未查询到配置信息");
            //}
            //if (mallbaseModel.AfterTime > 0) {
            //    //获取订单发货时间
            //    var detailModel = orderModule.GetOrderDetailInfo(demodel.OrderDetialId ?? 0);
            //    var omodel = orderModule.GetOrderInfo(detailModel?.OrderId ?? 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 + "天)，无法申请售后");
            //        }
            //    }
            //}

            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, userInfo.TenantId, userInfo.MallBaseId);
        }

        /// <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 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.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("请输入评价内容");
            }
            if (!demodel.CommentGrade.HasValue)
            {
                return ApiResult.ParamIsNull("请选择评分");
            }
            demodel.CommentImage = "";
            if (demodel.CommentImgList != null && demodel.CommentImgList.Any())
            {
                demodel.CommentImage = JsonConvert.SerializeObject(demodel.CommentImgList);
            }
            demodel.UserPhoto ??= 0;
            demodel.Is_Top ??= 2;
            demodel.Is_Show ??= 2;
            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.UpdateDate = DateTime.Now;

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

        #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());

            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.UserId = userInfo.UserId;
            var list = orderModule.GetDistributionOrdersPageList_V2(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            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
                }),
                x.UserId,
                x.UserName,
                x.Photo,
                x.Mobile,
                x.Remark,
                x.Commission,
                x.CommissionState,
                StatusName = x.DistrbutionOrderSelectStatus == 1 ? "待付款" : x.DistrbutionOrderSelectStatus == 5 ? "已完成" : "已付款",
                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 jsonStr = orderModule.GetOrderExpressInfo(model.ExpressCode, ExpressNumber);
                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"));
                    return ApiResult.Success("", list);
                }
                else
                {
                    return ApiResult.Failed("未能查询到该快递信息");
                }
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "GetOrderExpressInfo");
                return ApiResult.Failed("出错了，请联系管理员");
            }
        }
        #endregion
    }
}