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.Common.Enum.Goods;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Mall.AOP;

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

        private readonly IHttpContextAccessor _accessor;

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


        private readonly OrderModule orderModule = AOPHelper.CreateAOPObject<OrderModule>();
        private readonly MiniProgramMsgModule miniProgramMsgModule = new MiniProgramMsgModule();

        #region 订单列表

        /// <summary>
        /// 商品订单后台分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetGoodsOrderPageList()
        {
            var parms = RequestParm;
            JObject newParms = JObject.Parse(RequestParm.msg.ToString());
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Goods_Order_Extend demodel = new RB_Goods_Order_Extend()
            {
                UserName = newParms.GetStringValue("UserName"),
                OrderSource = (UserSourceEnum)newParms.GetInt("OrderSource"),
                OrderType = newParms.GetInt("OrderType"),
                DeliveryMethod = (OrderDeliveryMethodEnum)newParms.GetInt("DeliveryMethod"),
                OrderId = newParms.GetInt("OrderId"),
                StartTime = newParms.GetStringValue("StartTime"),
                EndTime = newParms.GetStringValue("EndTime"),
                OrderStatus = (OrderStatusEnum)newParms.GetInt("OrderStatus"),
                OrderNo = newParms.GetStringValue("OrderNo"),
                MerchantsNo = newParms.GetStringValue("MerchantsNo"),
                UserId = newParms.GetInt("UserId"),
                GoodsName = newParms.GetStringValue("GoodsName"),
                Consignee = newParms.GetStringValue("Consignee"),
                Recycled = newParms.GetInt("Recycled"),
                AnchorName = newParms.GetStringValue("AnchorName"),
                IsSelectPayMoney = newParms.GetInt("IsSelectPayMoney", 0)
            };

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = orderModule.GetGoodsOrderPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.OrderId,
                x.OrderNo,
                x.MerchantsNo,
                x.OrderSource,
                OrderSourceName = x.OrderSource.GetEnumName(),
                x.UserId,
                x.UserName,
                x.DeliveryMethod,
                DeliveryMethodName = x.DeliveryMethod.GetEnumName(),
                x.Income,
                x.FreightMoney,
                x.PaymentWay,
                DeductionCommission = x.DeductionCommission ?? 0,
                PaymentWayName = x.PaymentWay.GetEnumName(),
                CouponMoney = x.CouponMoney ?? 0,
                IntegralMoney = (x.DetailList != null && x.DetailList.Any()) ? (x.DetailList.Sum(x => x.IntegralMoney ?? 0)) : 0,
                IntegralNumber = (x.DetailList != null && x.DetailList.Any()) ? (x.DetailList.Sum(x => x.IntegralNumber ?? 0)) : 0,
                x.DepositId,
                x.DepositMoney,
                MemberDiscountCouponList = x.MemberDiscountCouponList.Select(y => new
                {
                    y.Name,
                    y.MinConsumePrice,
                    y.MaxDiscountsPrice,
                    y.UseType,
                    y.CouponType,
                    y.DiscountsPrice
                }),
                DetailList = x.DetailList.Select(y => new
                {
                    y.SupplierId,
                    y.SupplierName,
                    y.FreightCostMoney,
                    y.FreightMoney,
                    y.CostMoney,
                    y.Id,
                    y.CoverImage,
                    y.CoverImagePath,
                    y.OrderType,
                    OrderTypeName = y.OrderType.GetEnumName(),
                    y.GoodsName,
                    SpecificationList = JsonConvert.DeserializeObject<List<string>>(y.Specification),
                    y.ProductCode,
                    y.Final_Price,
                    y.Number,
                    y.IsBindExpress,
                    y.FreeShippingRemarks,
                    y.SmallShopsCostPrice,
                    y.YSMoney,
                    y.RealMoney,
                    y.YFMoney,
                    y.PayMoney,
                    CouponMoney = y.CouponMoney ?? 0,
                    InsuranceMoney = y.InsuranceMoney ?? 0,
                    InsuranceCostMoney = y.InsuranceCostMoney ?? 0,
                    IntegralMoney = y.IntegralMoney ?? 0,
                    IntegralNumber = y.IntegralNumber ?? 0,
                    DeductionCommission = y.DeductionCommission ?? 0,
                    y.IsApplyForAfterSale,
                    SFinanceList = y.FinanceList.Where(z => z.Type == 1).Select(z => new
                    {
                        z.FrID,
                        z.Status,
                        z.Is_Cashier
                    }),
                    ZFinanceList = y.FinanceList.Where(z => z.Type == 2).Select(z => new
                    {
                        z.FrID,
                        z.Status,
                        z.Is_Cashier
                    })
                }),
                x.Consignee,
                x.Mobile,
                x.DistrictAddress,
                x.ShoppingAddress,
                x.BuyerMessage,
                x.Remark,
                x.OrderStatus,
                OrderStatusName = x.OrderStatus.GetEnumName(),
                PaymentTime = x.PaymentTime.HasValue ? x.PaymentTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                DeliveryTime = x.DeliveryTime.HasValue ? x.DeliveryTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                ReceivingTime = x.ReceivingTime.HasValue ? x.ReceivingTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                FinishTime = x.FinishTime.HasValue ? x.FinishTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                x.Country,
                x.Province,
                x.City,
                x.District,
                x.TenantId,
                x.MallBaseId,
                x.SmallShopsId,
                x.SmallShopsName,
                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 GetOrderListExportEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(OrderListExportEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }

        /// <summary>
        /// 商品订单下载
        /// </summary>
        [HttpPost]
        public FileContentResult GetMemberUserListToExcel()
        {
            var parms = RequestParm;
            RB_Goods_Order_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Order_Extend>(parms.msg.ToString());
            string ExcelName = "订单列表" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            List<ExcelDataSource> slist = new List<ExcelDataSource>();
            if (demodel.ExcelEnumIds == null || !demodel.ExcelEnumIds.Any())
            {
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }
            var Enumlist = EnumHelper.GetEnumList(typeof(OrderListExportEnum));
            ExcelDataSource header = new ExcelDataSource()
            {
                ExcelRows = new List<ExcelColumn>(30) {
                    new ExcelColumn(value: "序号") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER }
                }
            };
            foreach (var item in demodel.ExcelEnumIds)
            {
                var Name = Enumlist.Where(x => x.Value == item.ToString()).FirstOrDefault().Key ?? "";
                header.ExcelRows.Add(new ExcelColumn(value: Name) { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER });
            }

            slist.Add(header);

            try
            {
                demodel.TenantId = Convert.ToInt32(parms.uid);
                demodel.MallBaseId = parms.MallBaseId;
                if (!(demodel.OrderStatus > 0))
                {
                    demodel.IsNotSelectCancel = 1;
                }
                var list = orderModule.GetGoodsOrderPageList(1, 10000, out long count, demodel);
                #region 组装数据
                int Num = 0;
                foreach (var item in list)
                {
                    foreach (var item2 in item.DetailList)
                    {
                        Num++;
                        ExcelDataSource datarow = new ExcelDataSource()
                        {
                            ExcelRows = new List<ExcelColumn>(30) {
                                new ExcelColumn(value:Num.ToString()){ },
                            },
                            ColumnHight = 30
                        };
                        List<string> arr = JsonConvert.DeserializeObject<List<string>>(item2.Specification);
                        item2.Specification = string.Join("，", arr);
                        foreach (var qitem in demodel.ExcelEnumIds)
                        {
                            switch (qitem)
                            {
                                case 1:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderSource.GetEnumName()) { }); break;
                                case 2:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderNo) { }); break;
                                case 3:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.MerchantsNo) { }); break;
                                case 4:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.UserName) { }); break;
                                case 5:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item2.GoodsName) { }); break;
                                case 28:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item2.GoodsSubName) { }); break;
                                case 6:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item2.Specification) { }); break;
                                case 7:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: (item2.Number ?? 0).ToString()) { }); break;
                                case 8:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item2.ProductCode) { }); break;
                                case 9:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: (item2.CostMoney ?? 0).ToString()) { }); break;
                                case 10:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.Consignee) { }); break;
                                case 11:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.Mobile) { }); break;
                                case 12:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: (item.DistrictAddress ?? "") + " " + (item.ShoppingAddress ?? "")) { }); break;
                                case 13:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: (item2.Original_Price ?? 0).ToString()) { }); break;
                                case 14:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: (item2.Final_Price ?? 0).ToString()) { }); break;
                                case 15:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: (item2.FreightMoney ?? 0).ToString()) { }); break;
                                case 16:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss")) { }); break;
                                case 17:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.PaymentWay.GetEnumName()) { }); break;
                                case 18:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderStatus.GetEnumName()) { }); break;
                                case 19:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderStatus > OrderStatusEnum.NonPayment ? "已付款" : "未付款") { }); break;
                                case 20:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.PaymentTime.HasValue ? item.PaymentTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "") { }); break;
                                case 21:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderStatus > OrderStatusEnum.WaitSendGoods ? "已发货" : "未发货") { }); break;
                                case 22:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.DeliveryTime.HasValue ? item.DeliveryTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "") { }); break;
                                case 23:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderStatus > OrderStatusEnum.WaitReceiving ? "已收货" : "未收货") { }); break;
                                case 24:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.ReceivingTime.HasValue ? item.ReceivingTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "") { }); break;
                                case 25:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: "") { }); break;
                                case 26:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.Remark) { }); break;
                                case 27:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.BuyerMessage) { }); break;

                            }
                        }
                        slist.Add(datarow);
                    }
                }
                #endregion

                var byteData = ExcelTempLateHelper.ToExcelExtend(slist);

                return File(byteData, "application/octet-stream", ExcelName);
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, string.Format("GetFileFromWebApi_requestData: {0}", JsonHelper.Serialize(RequestParm)));
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }

        }

        #region 司导列表

        /// <summary>
        /// 司导商品订单后台分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSDGoodsOrderPageList()
        {
            var parms = RequestParm;
            JObject newParms = JObject.Parse(RequestParm.msg.ToString());
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Goods_Order_Extend demodel = new RB_Goods_Order_Extend()
            {
                UserName = newParms.GetStringValue("UserName"),
                OrderSource = (UserSourceEnum)newParms.GetInt("OrderSource"),
                OrderType = newParms.GetInt("OrderType"),
                DeliveryMethod = (OrderDeliveryMethodEnum)newParms.GetInt("DeliveryMethod"),
                OrderId = newParms.GetInt("OrderId"),
                StartTime = newParms.GetStringValue("StartTime"),
                EndTime = newParms.GetStringValue("EndTime"),
                OrderStatus = (OrderStatusEnum)newParms.GetInt("OrderStatus"),
                OrderNo = newParms.GetStringValue("OrderNo"),
                MerchantsNo = newParms.GetStringValue("MerchantsNo"),
                UserId = newParms.GetInt("UserId"),
                GoodsName = newParms.GetStringValue("GoodsName"),
                Consignee = newParms.GetStringValue("Consignee"),
                Recycled = newParms.GetInt("Recycled"),
                AnchorName = newParms.GetStringValue("AnchorName"),
                IsSelectPayMoney = newParms.GetInt("IsSelectPayMoney", 0)
            };

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = orderModule.GetSDGoodsOrderPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.OrderId,
                x.OrderNo,
                x.MerchantsNo,
                x.OrderSource,
                OrderSourceName = x.OrderSource.GetEnumName(),
                x.UserId,
                x.UserName,
                x.DeliveryMethod,
                DeliveryMethodName = x.DeliveryMethod.GetEnumName(),
                x.Income,
                x.FreightMoney,
                x.PaymentWay,
                PaymentWayName = x.PaymentWay.GetEnumName(),
                CouponMoney = x.CouponMoney ?? 0,
                InsuranceMoney = (x.DetailList != null && x.DetailList.Any()) ? (x.DetailList.Sum(x => x.InsuranceMoney ?? 0)) : 0,
                IntegralMoney = (x.DetailList != null && x.DetailList.Any()) ? (x.DetailList.Sum(x => x.IntegralMoney ?? 0)) : 0,
                IntegralNumber = (x.DetailList != null && x.DetailList.Any()) ? (x.DetailList.Sum(x => x.IntegralNumber ?? 0)) : 0,
                MemberDiscountCouponList = x.MemberDiscountCouponList.Select(y => new
                {
                    y.Name,
                    y.MinConsumePrice,
                    y.MaxDiscountsPrice,
                    y.UseType,
                    y.CouponType,
                    y.DiscountsPrice
                }),
                DetailList = x.DetailList.Select(y => new
                {
                    y.SupplierId,
                    y.SupplierName,
                    y.FreightCostMoney,
                    y.FreightMoney,
                    y.CostMoney,
                    y.Id,
                    y.CoverImage,
                    y.CoverImagePath,
                    y.OrderType,
                    OrderTypeName = y.OrderType.GetEnumName(),
                    y.GoodsName,
                    y.ProductCode,
                    y.Final_Price,
                    y.Number,
                    y.IsBindExpress,
                    y.FreeShippingRemarks,
                    y.SmallShopsCostPrice,
                    y.YSMoney,
                    y.RealMoney,
                    y.YFMoney,
                    y.PayMoney,
                    CouponMoney = y.CouponMoney ?? 0,
                    InsuranceMoney = y.InsuranceMoney ?? 0,
                    InsuranceCostMoney = y.InsuranceCostMoney ?? 0,
                    IntegralMoney = y.IntegralMoney ?? 0,
                    IntegralNumber = y.IntegralNumber ?? 0,
                    SFinanceList = y.FinanceList.Where(z => z.Type == 1).Select(z => new
                    {
                        z.FrID,
                        z.Status,
                        z.Is_Cashier
                    }),
                    ZFinanceList = y.FinanceList.Where(z => z.Type == 2).Select(z => new
                    {
                        z.FrID,
                        z.Status,
                        z.Is_Cashier
                    }),
                    y.SiteName,
                    y.SiteId,
                    y.GuideId,
                    y.GuideName,
                    y.CarId,
                    y.CarName,
                    y.CarColorId,
                    y.CarColorName,
                    y.CarNumber,
                    y.LineName,
                    TripSTime = y.TripSTime.HasValue ? y.TripSTime.Value.ToString("yyyy-MM-dd HH:mm") : "",
                    TripETime = y.TripETime.HasValue ? y.TripETime.Value.ToString("yyyy-MM-dd HH:mm") : "",
                    y.CarType,
                    CarTypeName = y.CarType.GetEnumName(),
                    y.UseDay,
                    y.IsSpell,
                    y.CommentGiveIntegral
                }),
                x.Consignee,
                x.Mobile,
                x.DistrictAddress,
                x.ShoppingAddress,
                x.DestinationAddress,
                x.BuyerMessage,
                x.Remark,
                x.OrderStatus,
                OrderStatusName = x.OrderStatus.GetEnumName(),
                PaymentTime = x.PaymentTime.HasValue ? x.PaymentTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                DeliveryTime = x.DeliveryTime.HasValue ? x.DeliveryTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                ReceivingTime = x.ReceivingTime.HasValue ? x.ReceivingTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                FinishTime = x.FinishTime.HasValue ? x.FinishTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                x.Country,
                x.Province,
                x.City,
                x.District,
                x.TenantId,
                x.MallBaseId,
                x.SmallShopsId,
                x.SmallShopsName,
                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 GetOrderListExportForSDEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(OrderListExportForSDEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }

        /// <summary>
        /// 商品订单下载
        /// </summary>
        [HttpPost]
        public FileContentResult GetSDGoodsOrderListToExcel()
        {
            var parms = RequestParm;
            RB_Goods_Order_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Order_Extend>(parms.msg.ToString());
            string ExcelName = "司导订单列表" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            List<ExcelDataSource> slist = new List<ExcelDataSource>();
            if (demodel.ExcelEnumIds == null || !demodel.ExcelEnumIds.Any())
            {
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }
            var Enumlist = EnumHelper.GetEnumList(typeof(OrderListExportForSDEnum));
            ExcelDataSource header = new ExcelDataSource()
            {
                ExcelRows = new List<ExcelColumn>(30) {
                    new ExcelColumn(value: "序号") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER }
                }
            };
            foreach (var item in demodel.ExcelEnumIds)
            {
                var Name = Enumlist.Where(x => x.Value == item.ToString()).FirstOrDefault().Key ?? "";
                header.ExcelRows.Add(new ExcelColumn(value: Name) { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER });
            }

            slist.Add(header);

            try
            {
                demodel.TenantId = Convert.ToInt32(parms.uid);
                demodel.MallBaseId = parms.MallBaseId;
                if (!(demodel.OrderStatus > 0))
                {
                    demodel.IsNotSelectCancel = 1;
                }
                var list = orderModule.GetSDGoodsOrderPageList(1, 10000, out long count, demodel);
                #region 组装数据
                int Num = 0;
                foreach (var item in list)
                {
                    foreach (var item2 in item.DetailList)
                    {
                        Num++;
                        ExcelDataSource datarow = new ExcelDataSource()
                        {
                            ExcelRows = new List<ExcelColumn>(30) {
                                new ExcelColumn(value:Num.ToString()){ },
                            },
                            ColumnHight = 30
                        };
                        foreach (var qitem in demodel.ExcelEnumIds)
                        {
                            switch (qitem)
                            {
                                case 1:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderSource.GetEnumName()) { }); break;
                                case 2:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderNo) { }); break;
                                case 3:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.MerchantsNo) { }); break;
                                case 4:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.UserName) { }); break;
                                case 5:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item2.GoodsName) { }); break;
                                case 28:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item2.GoodsSubName) { }); break;
                                case 7:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: (item2.Number ?? 0).ToString()) { }); break;
                                case 9:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: (item2.CostMoney ?? 0).ToString()) { }); break;
                                case 10:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.Consignee) { }); break;
                                case 11:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.Mobile) { }); break;
                                case 12:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: (item.DistrictAddress ?? "") + " " + (item.ShoppingAddress ?? "")) { }); break;
                                case 13:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: (item2.Original_Price ?? 0).ToString()) { }); break;
                                case 14:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: (item2.Final_Price ?? 0).ToString()) { }); break;
                                case 15:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: (item2.FreightMoney ?? 0).ToString()) { }); break;
                                case 16:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss")) { }); break;
                                case 17:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.PaymentWay.GetEnumName()) { }); break;
                                case 18:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderStatus.GetEnumName()) { }); break;
                                case 19:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderStatus > OrderStatusEnum.NonPayment ? "已付款" : "未付款") { }); break;
                                case 20:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.PaymentTime.HasValue ? item.PaymentTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "") { }); break;
                                case 21:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderStatus > OrderStatusEnum.WaitSendGoods ? "已确认" : "待确认") { }); break;
                                case 22:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.DeliveryTime.HasValue ? item.DeliveryTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "") { }); break;
                                case 23:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderStatus > OrderStatusEnum.WaitReceiving ? "出行中" : "待出行") { }); break;
                                case 24:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.ReceivingTime.HasValue ? item.ReceivingTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "") { }); break;
                                case 29:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: (item2.GuideName ?? "")) { }); break;
                                case 30:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: (item2.CarName ?? "")) { }); break;
                                case 31:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: (item2.CarNumber ?? "")) { }); break;
                                case 32:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: (item2.CarType.GetEnumName() ?? "")) { }); break;
                                case 25:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: "") { }); break;
                                case 26:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.Remark) { }); break;
                                case 27:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.BuyerMessage) { }); break;

                            }
                        }
                        slist.Add(datarow);
                    }
                }
                #endregion

                var byteData = ExcelTempLateHelper.ToExcelExtend(slist);

                return File(byteData, "application/octet-stream", ExcelName);
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, string.Format("GetFileFromWebApi_requestData: {0}", JsonHelper.Serialize(RequestParm)));
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }

        }

        /// <summary>
        /// 获取订单详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSDGoodsOrderInfo()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int OrderId = parms.GetInt("OrderId", 0);
            if (OrderId <= 0)
            {
                return ApiResult.Failed();
            }

            return orderModule.GetSDGoodsOrderInfo(OrderId, req.TenantId, req.MallBaseId);
        }
        #endregion


        /// <summary>
        /// 获取商品订单类型枚举
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetOrderTypeEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(OrderTypeEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }

        /// <summary>
        /// 获取商品订单配送类型
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetOrderDeliveryMethodEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(OrderDeliveryMethodEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }

        /// <summary>
        /// 获取商品订单状态枚举
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetOrderStatusEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(OrderStatusEnum));
            return ApiResult.Success("", list.OrderBy(x => Convert.ToInt32(x.Value)).Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }

        /// <summary>
        /// 下单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetGoodsOrderInfo()
        {
            var req = RequestParm;
            RB_Goods_Order_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Order_Extend>(req.msg.ToString());

            if (demodel.DetailList == null || !demodel.DetailList.Any())
            {
                return ApiResult.ParamIsNull("请选择下单商品");
            }
            //等小程序登录  收货地址做了之后
            return ApiResult.Success();
        }

        /// <summary>
        /// 获取订单详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetGoodsOrderInfo()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int OrderId = parms.GetInt("OrderId", 0);
            if (OrderId <= 0)
            {
                return ApiResult.Failed();
            }

            return orderModule.GetGoodsOrderInfo(OrderId, req.TenantId, req.MallBaseId);
        }

        /// <summary>
        /// 订单发货
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetOrderSendGoods()
        {
            var req = RequestParm;
            RB_Goods_OrderExpress_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_OrderExpress_Extend>(req.msg.ToString());
            if ((demodel.OrderId ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请传递订单id");
            }
            if (demodel.OrderDetailIdList == null || !demodel.OrderDetailIdList.Any())
            {
                return ApiResult.ParamIsNull("请传递订单明细id");
            }
            if (demodel.Type == 1)
            {
                if (!demodel.ExpressId.HasValue || demodel.ExpressId <= 0)
                {
                    return ApiResult.ParamIsNull("请选择快递公司");
                }
                if (string.IsNullOrEmpty(demodel.ExpressNumber))
                {
                    return ApiResult.ParamIsNull("请输入快递单号");
                }
            }
            else
            {
                if (string.IsNullOrEmpty(demodel.Remark))
                {
                    return ApiResult.ParamIsNull("请输入物流内容");
                }
            }
            var omodel = orderModule.GetOrderInfo(demodel.OrderId ?? 0);
            if (omodel.OrderStatus != OrderStatusEnum.WaitSendGoods && omodel.OrderStatus != OrderStatusEnum.WaitReceiving)
            {
                return ApiResult.ParamIsNull("状态不对");
            }

            demodel.TenantId = req.TenantId;
            demodel.MallBaseId = req.MallBaseId;
            demodel.CreateDate = DateTime.Now;
            demodel.UpdateDate = DateTime.Now;

            var flag = orderModule.SetOrderSendGoods(demodel, out string msg);
            return flag ? ApiResult.Success() : ApiResult.Failed(msg);
        }

        /// <summary>
        /// 根据订单id获取物流id
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetOrderSendGoodsExpressIdByOrderId()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int OrderId = parms.GetInt("OrderId", 0);
            if (OrderId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            var erlist = orderModule.GetGoodsExpressRelevanceByOrderId(OrderId, req.TenantId, req.MallBaseId);
            if (erlist.Any())
            {
                if (erlist.Select(x => x.OrderExpressId).Distinct().Count() == 1)
                {
                    return ApiResult.Success("", erlist.Select(x => x.OrderExpressId).Distinct().FirstOrDefault());
                }
                else
                {
                    return ApiResult.Failed("该订单有多个物流,请到订单详情修改物流信息");
                }
            }
            return ApiResult.Failed("未能查询到物流信息");
        }

        /// <summary>
        /// 获取订单发货信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetOrderSendGoodsInfo()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int OrderExpressId = parms.GetInt("OrderExpressId", 0);
            if (OrderExpressId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            var Robj = orderModule.GetOrderSendGoodsInfo(OrderExpressId, req.TenantId, req.MallBaseId);
            return ApiResult.Success("", Robj);
        }

        /// <summary>
        /// 设置订单操作
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetOrderOperation()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int OrderId = parms.GetInt("OrderId", 0);
            int Type = parms.GetInt("Type", 0);//类型  1修改备注  2修改金额  3强制取消  4放入回收站  5确认收货  6确认完成  7回收恢复 8回收删除
            string Remark = parms.GetStringValue("Remark");
            decimal Income = parms.GetDecimal("Income");
            if (OrderId <= 0)
            {
                return ApiResult.ParamIsNull("请传递id");
            }
            var omodel = orderModule.GetOrderInfo(OrderId);
            if (omodel == null)
            {
                return ApiResult.ParamIsNull("订单不存在，请核实后再试");
            }
            if (omodel.Status == 1)
            {
                return ApiResult.Failed("已删除订单无法操作");
            }
            if (Type == 1)
            {
                if (omodel.Recycled == 1)
                {
                    return ApiResult.ParamIsNull("回收站订单无法修改备注");
                }
            }
            else if (Type == 2)
            {
                if (omodel.Recycled == 1)
                {
                    return ApiResult.ParamIsNull("回收站订单无法修改付款金额");
                }
                if (omodel.OrderStatus != OrderStatusEnum.NonPayment)
                {
                    return ApiResult.Failed("不是未付款状态，无法修改付款金额");
                }
                if (Income <= 0)
                {
                    return ApiResult.ParamIsNull("请传递金额");
                }
            }
            else if (Type == 3)
            {
                if (omodel.Recycled == 1)
                {
                    return ApiResult.ParamIsNull("回收站订单无法取消");
                }
                if (omodel.OrderStatus == OrderStatusEnum.Cancel)
                {
                    return ApiResult.Failed("订单已取消，无法再试取消");
                }
            }
            else if (Type == 4)
            {
                if (omodel.Recycled == 1)
                {
                    return ApiResult.ParamIsNull("该订单已在回收站下");
                }
            }
            else if (Type == 5)
            {
                if (omodel.Recycled == 1)
                {
                    return ApiResult.ParamIsNull("回收站订单无法确认收货");
                }
                if (omodel.OrderStatus != OrderStatusEnum.WaitReceiving)
                {
                    return ApiResult.Failed("订单状态不对，无法确认收货");
                }
            }
            else if (Type == 6)
            {
                if (omodel.Recycled == 1)
                {
                    return ApiResult.ParamIsNull("回收站订单无法确认完成");
                }
                if (omodel.OrderStatus != OrderStatusEnum.Received)
                {
                    return ApiResult.Failed("订单状态不对，无法确认完成");
                }
            }
            else if (Type == 7)
            {
                if (omodel.Recycled != 1)
                {
                    return ApiResult.ParamIsNull("该订单不在回收站，无法恢复");
                }
            }
            else if (Type == 8)
            {
                if (omodel.Recycled != 1)
                {
                    return ApiResult.ParamIsNull("该订单不在回收站，无法删除");
                }
            }
            else
            {
                return ApiResult.ParamIsNull("参数有误");
            }

            bool flag = orderModule.SetOrderOperation(omodel, Type, Remark, Income, req.TenantId, req.MallBaseId, _accessor);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 后台订单强制取消
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetOrderForcedToCancel()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int OrderId = parms.GetInt("OrderId", 0);
            //string Remark = parms.GetStringValue("Remark");
            if (OrderId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            var omodel = orderModule.GetOrderInfo(OrderId);
            if (omodel == null)
            {
                return ApiResult.Failed("订单不存在");
            }
            if (omodel.Status == 1)
            {
                return ApiResult.Failed("订单已删除");
            }
            if (omodel.Recycled == 1)
            {
                return ApiResult.Failed("订单已进入回收站无法操作");
            }
            if (omodel.OrderStatus != OrderStatusEnum.NonPayment && omodel.OrderStatus != OrderStatusEnum.WaitSendGoods)
            {
                return ApiResult.Failed("该订单已无法取消");
            }
            int IsNormalServer = Convert.ToInt32(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("IsNormalServer").Value);
            if (IsNormalServer == 1 && omodel.OrderStatus == OrderStatusEnum.WaitSendGoods && omodel.OrderSource != UserSourceEnum.ERP && omodel.Income > 0)
            {
                //获取小程序信息
                var mallModel = orderModule.GetMiniProgramExtend(req.MallBaseId);
                int RefundNum = orderModule.GetOrderRefundOnlineTradeNum(OrderId, req.TenantId, req.MallBaseId);
                string RefundOrderNo = omodel.OrderNo + (RefundNum + 1);
                var pram = new Common.Pay.WeChatPat.PayParam()
                {
                    TotalFee = Convert.ToInt32((omodel.Income ?? 0) * 100),
                    RefundFee = Convert.ToInt32((omodel.Income ?? 0) * 100),
                    OrderNumber = omodel.MerchantsNo,
                    RefundNumber = RefundOrderNo
                };
                var Robj = new App_Code.PayUtil().Refund(pram, mallModel, _accessor);
                if (Robj.IsSuccess)
                {
                    //获取商品信息
                    var orderGoodsList = orderModule.GetOrderDetailList(new RB_Goods_OrderDetail_Extend { TenantId = omodel.TenantId, MallBaseId = omodel.MallBaseId, OrderId = omodel.OrderId });
                    //2020-11-10 Add By:W  start
                    if (omodel.OrderClassify == 0)
                    {
                        try
                        {
                            if (orderGoodsList != null && orderGoodsList.Any(x => x.IsNoTax == 1))//有不可以开发票的商品 新增记录更新缓存
                            {
                                if ((omodel.Income ?? 0) > 0)
                                {
                                    foreach (var item in orderGoodsList.Where(x => x.IsNoTax == 1))
                                    {
                                        orderModule.AddInvoiceRecordDetail(new Model.Entity.Product.RB_Invoice_RecordDetail
                                        {
                                            TenantId = item.TenantId,
                                            MallBaseId = item.MallBaseId,
                                            ID = 0,
                                            Type = 3,
                                            CreateDate = DateTime.Now,
                                            Name = item.GoodsName,
                                            OrderId = item.OrderId ?? 0,
                                            OrderDetailId = item.Id,
                                            GoodsPrice = omodel.Income ?? 0,
                                            Unit_Price = 0,
                                            Number = 1,
                                            FreightMoney = 0
                                        });
                                    }
                                    //获取缓存信息
                                    TransactionPriceInfo transactionPriceInfo = CacheManager.User.UserReidsCache.GetTransactionPriceInfo(omodel.MallBaseId);
                                    if (transactionPriceInfo == null)
                                    {
                                        transactionPriceInfo = new TransactionPriceInfo
                                        {
                                            TenantId = omodel.TenantId,
                                            MallBaseId = omodel.MallBaseId,
                                            TotalPrice = (omodel.Income ?? 0) * -1
                                        };
                                    }
                                    else
                                    {
                                        transactionPriceInfo.TotalPrice -= (omodel.Income ?? 0);
                                    }
                                    CacheManager.User.UserReidsCache.TransactionPriceSet(CacheKey.UserModuleCacheKeyConfig.Transaction_Price_ + omodel.MallBaseId, transactionPriceInfo, Config.JwtExpirTime);
                                };
                            }
                        }
                        catch (Exception ex)
                        {
                            LogHelper.WriteInfo("不开发票商品记录或者缓存失败:" + ex.ToString());
                        }
                    }
                    //2020-11-10 Add By:W End


                    string goodsName = orderGoodsList.FirstOrDefault().GoodsName;
                    if (orderGoodsList.Count > 1)
                    {
                        if (goodsName.Length > 12)
                        {
                            goodsName = goodsName.Substring(0, 11) + "..";
                        }
                        goodsName += "等" + orderGoodsList.Count + "件商品";
                    }
                    else
                    {
                        if (goodsName.Length > 18)
                        {
                            goodsName = goodsName.Substring(0, 18) + "..";
                        }
                    }

                    //退款成功发送退款成功的订阅消息
                    //根据订单下单人获取openid
                    var userModel = orderModule.GetMemberUserInfo(omodel.UserId.Value);
                    if (userModel != null)
                    {
                        miniProgramMsgModule.SendOrderRefundMsg(mallModel.TenantId.Value, mallModel.MallBaseId, userModel.OpenId, "已退款，请注意查收", omodel.OrderNo, (omodel.Income ?? 0).ToString(), goodsName);
                    }
                    var dic = ((Dictionary<string, string>)Robj.Data);
                    bool flag = orderModule.SetOrderForcedToCancel(omodel, RefundOrderNo, req.TenantId, req.MallBaseId, Common.Enum.Goods.OrderPayTypeEnum.WeChatPay, dic["dPrice"], dic["sOrderNo"], dic["sTradeNo"], dic["refundid"]);
                    if (flag)
                    {
                        return ApiResult.Success();
                    }
                    else
                    {
                        return ApiResult.Failed();
                    }
                }
                else
                {
                    LogHelper.Write(JsonConvert.SerializeObject(Robj));
                    return ApiResult.Failed();
                }
            }
            else
            {
                bool flag = orderModule.SetOrderForcedToCancel(omodel, "", req.TenantId, req.MallBaseId, Common.Enum.Goods.OrderPayTypeEnum.WeChatPay, "", "", "", "");
                if (flag)
                {
                    return ApiResult.Success();
                }
                else
                {
                    return ApiResult.Failed();
                }
            }
        }

        /// <summary>
        /// 修改订单明细价格
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetOrderDetialMoneyInfo()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int OrderDetailId = parms.GetInt("OrderDetailId", 0);
            decimal Income = parms.GetDecimal("Income");
            if (OrderDetailId <= 0)
            {
                return ApiResult.ParamIsNull("请传递订单明细id");
            }
            if (Income <= 0)
            {
                return ApiResult.ParamIsNull("请传递价格");
            }

            bool flag = orderModule.SetOrderDetialMoneyInfo(OrderDetailId, Income, req.TenantId, req.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 修改订单价格/运费
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetOrderMoneyOrFreightInfo()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int OrderId = parms.GetInt("OrderId", 0);
            decimal Income = parms.GetDecimal("Income");
            decimal FreightMoney = parms.GetDecimal("FreightMoney");
            if (OrderId <= 0)
            {
                return ApiResult.ParamIsNull("请传递订单明细id");
            }
            if (Income <= 0)
            {
                return ApiResult.ParamIsNull("请传递价格");
            }
            if (FreightMoney < 0)
            {
                return ApiResult.ParamIsNull("请传递运费");
            }

            bool flag = orderModule.SetOrderMoneyOrFreightInfo(OrderId, Income, FreightMoney, req.TenantId, req.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 设置订单收货地址
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetOrderShopingAddress()
        {
            var req = RequestParm;
            RB_Goods_Order_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Order_Extend>(req.msg.ToString());
            if (demodel.OrderId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            if (string.IsNullOrEmpty(demodel.Consignee))
            {
                return ApiResult.ParamIsNull("请输入收件人");
            }
            if (string.IsNullOrEmpty(demodel.Mobile))
            {
                return ApiResult.ParamIsNull("请输入手机号码");
            }
            if ((demodel.Province ?? 0) <= 0 || (demodel.City ?? 0) <= 0 || (demodel.District ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请选择区域");
            }
            if (string.IsNullOrEmpty(demodel.ShoppingAddress))
            {
                return ApiResult.ParamIsNull("请输入详细地址");
            }

            demodel.TenantId = req.TenantId;
            demodel.MallBaseId = req.MallBaseId;
            bool flag = orderModule.SetOrderShopingAddress(demodel);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 申请订单取消 审核
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetOrderApplyForCancelAudit()
        {
            var req = RequestParm;
            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");
            if (OrderId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            var omodel = orderModule.GetOrderInfo(OrderId);
            if (omodel == null)
            {
                return ApiResult.Failed("订单不存在");
            }
            if (omodel.Status == 1)
            {
                return ApiResult.Failed("订单已删除");
            }
            if (omodel.Recycled == 1)
            {
                return ApiResult.Failed("订单已进入回收站无法操作");
            }
            if (omodel.IsApplyForCancel != 1)
            {
                return ApiResult.Failed("该订单未申请取消该订单");
            }
            int IsNormalServer = Convert.ToInt32(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("IsNormalServer").Value);
            if (Type == 1 && IsNormalServer == 1 && omodel.OrderSource != UserSourceEnum.ERP)
            {
                //获取小程序信息
                var mallModel = orderModule.GetMiniProgramExtend(req.MallBaseId);
                int RefundNum = orderModule.GetOrderRefundOnlineTradeNum(OrderId, req.TenantId, req.MallBaseId);
                string RefundOrderNo = omodel.OrderNo + (RefundNum + 1);
                var pram = new Common.Pay.WeChatPat.PayParam()
                {
                    TotalFee = Convert.ToInt32((omodel.Income ?? 0) * 100),
                    RefundFee = Convert.ToInt32((omodel.Income ?? 0) * 100),
                    OrderNumber = omodel.MerchantsNo,
                    RefundNumber = RefundOrderNo
                };
                var Robj = new App_Code.PayUtil().Refund(pram, mallModel, _accessor);
                if (Robj.IsSuccess)
                {
                    //获取商品信息
                    var orderGoodsList = orderModule.GetOrderDetailList(new RB_Goods_OrderDetail_Extend { TenantId = omodel.TenantId, MallBaseId = omodel.MallBaseId, OrderId = omodel.OrderId });
                    //2020-11-10 Add By:W  start
                    if (omodel.OrderClassify == 0)
                    {
                        try
                        {
                            if (orderGoodsList != null && orderGoodsList.Any(x => x.IsNoTax == 1))//有不可以开发票的商品 新增记录更新缓存
                            {
                                if ((omodel.Income ?? 0) > 0)
                                {
                                    foreach (var item in orderGoodsList.Where(x => x.IsNoTax == 1))
                                    {
                                        orderModule.AddInvoiceRecordDetail(new Model.Entity.Product.RB_Invoice_RecordDetail
                                        {
                                            TenantId = item.TenantId,
                                            MallBaseId = item.MallBaseId,
                                            ID = 0,
                                            Type = 3,
                                            CreateDate = DateTime.Now,
                                            Name = item.GoodsName,
                                            OrderId = item.OrderId ?? 0,
                                            OrderDetailId = item.Id,
                                            GoodsPrice = omodel.Income ?? 0,
                                            Unit_Price = 0,
                                            Number = 1,
                                            FreightMoney = 0
                                        });
                                    }
                                    //获取缓存信息
                                    TransactionPriceInfo transactionPriceInfo = CacheManager.User.UserReidsCache.GetTransactionPriceInfo(omodel.MallBaseId);
                                    if (transactionPriceInfo == null)
                                    {
                                        transactionPriceInfo = new TransactionPriceInfo
                                        {
                                            TenantId = omodel.TenantId,
                                            MallBaseId = omodel.MallBaseId,
                                            TotalPrice = (omodel.Income ?? 0) * -1
                                        };
                                    }
                                    else
                                    {
                                        transactionPriceInfo.TotalPrice -= (omodel.Income ?? 0);
                                    }
                                    CacheManager.User.UserReidsCache.TransactionPriceSet(CacheKey.UserModuleCacheKeyConfig.Transaction_Price_ + omodel.MallBaseId, transactionPriceInfo, Config.JwtExpirTime);
                                };
                            }
                        }
                        catch (Exception ex)
                        {
                            LogHelper.WriteInfo("不开发票商品记录或者缓存失败:" + ex.ToString());
                        }
                    }
                    //2020-11-10 Add By:W End

                    string goodsName = orderGoodsList.FirstOrDefault().GoodsName;
                    if (orderGoodsList.Count > 1)
                    {
                        if (goodsName.Length > 12)
                        {
                            goodsName = goodsName.Substring(0, 11) + "..";
                        }
                        goodsName += "等" + orderGoodsList.Count + "件商品";
                    }
                    else
                    {
                        if (goodsName.Length > 18)
                        {
                            goodsName = goodsName.Substring(0, 18) + "..";
                        }
                    }

                    //退款成功发送退款成功的订阅消息
                    //根据订单下单人获取openid
                    var userModel = orderModule.GetMemberUserInfo(omodel.UserId.Value);
                    if (userModel != null)
                    {
                        miniProgramMsgModule.SendOrderRefundMsg(mallModel.TenantId.Value, mallModel.MallBaseId, userModel.OpenId, "已退款，请注意查收", omodel.OrderNo, (omodel.Income ?? 0).ToString(), goodsName);
                    }


                    var dic = ((Dictionary<string, string>)Robj.Data);
                    bool flag = orderModule.SetOrderApplyForCancelAudit(omodel, Type, Remark, RefundOrderNo, req.TenantId, req.MallBaseId, Common.Enum.Goods.OrderPayTypeEnum.WeChatPay, dic["dPrice"], dic["sOrderNo"], dic["sTradeNo"], dic["refundid"], req.EmpId);
                    if (flag)
                    {
                        return ApiResult.Success();
                    }
                    else
                    {
                        return ApiResult.Failed();
                    }
                }
                else
                {
                    LogHelper.Write(JsonConvert.SerializeObject(Robj));
                    return ApiResult.Failed();
                }
            }
            else
            {
                bool flag = orderModule.SetOrderApplyForCancelAudit(omodel, Type, Remark, "", req.TenantId, req.MallBaseId, Common.Enum.Goods.OrderPayTypeEnum.WeChatPay, "", "", "", "", req.EmpId);
                if (flag)
                {
                    return ApiResult.Success();
                }
                else
                {
                    return ApiResult.Failed();
                }
            }
        }

        /// <summary>
        /// 清空回收站
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetOrderEmptyRecycleBin()
        {
            var req = RequestParm;
            bool flag = orderModule.SetOrderEmptyRecycleBin(req.TenantId, req.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }



        /// <summary>
        /// 获取订单类型枚举下拉
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetOrderTypeEnumEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(OrderTypeEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }

        #region 司导订单管理
        /// <summary>
        /// 司导订单确认
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetSDOrderConfirm()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int OrderId = parms.GetInt("OrderId", 0);
            int Type = parms.GetInt("Type", 1);//类型  1确认  2出行  3完成
            if (OrderId <= 0)
            {
                return ApiResult.ParamIsNull("请传递订单id");
            }
            var omodel = orderModule.GetOrderInfo(OrderId);
            if (omodel == null)
            {
                return ApiResult.ParamIsNull("订单信息不存在");
            }
            if (omodel.OrderClassify != 1)
            {
                return ApiResult.ParamIsNull("该订单不是司导订单");
            }
            if (Type == 1)
            {
                if (omodel.OrderStatus != OrderStatusEnum.WaitSendGoods)
                {
                    return ApiResult.ParamIsNull("订单状态不正确，请核实后再试");
                }
            }
            else if (Type == 2)
            {
                if (omodel.OrderStatus != OrderStatusEnum.WaitReceiving)
                {
                    return ApiResult.ParamIsNull("订单状态不正确，请核实后再试");
                }
            }
            else if (Type == 3)
            {
                if (omodel.OrderStatus != OrderStatusEnum.Received)
                {
                    return ApiResult.ParamIsNull("订单状态不正确，请核实后再试");
                }
            }
            else
            {
                return ApiResult.Failed();
            }

            bool flag = orderModule.SetSDOrderConfirm(OrderId, Type, req.EmpId, _accessor);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 修改订单保险成本
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetOrderInsuranceCostMoney()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int OrderDetailId = parms.GetInt("OrderDetailId", 0);
            decimal InsuranceCostMoney = parms.GetDecimal("InsuranceCostMoney");
            if (OrderDetailId <= 0)
            {
                return ApiResult.ParamIsNull("请传递订单明细id");
            }

            if (InsuranceCostMoney < 0)
            {
                return ApiResult.ParamIsNull("请传递司导保险成本");
            }

            bool flag = orderModule.SetOrderInsuranceCostMoney(OrderDetailId, InsuranceCostMoney, req.TenantId, req.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        #endregion


        #region 教育订单
        /// <summary>
        /// 商品订单后台分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetEducationGoodsOrderPageList()
        {
            var parms = RequestParm;
            JObject newParms = JObject.Parse(RequestParm.msg.ToString());
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Goods_Order_Extend demodel = new RB_Goods_Order_Extend()
            {
                UserName = newParms.GetStringValue("UserName"),
                OrderSource = (UserSourceEnum)newParms.GetInt("OrderSource"),
                OrderType = newParms.GetInt("OrderType"),
                OrderId = newParms.GetInt("OrderId"),
                StartTime = newParms.GetStringValue("StartTime"),
                EndTime = newParms.GetStringValue("EndTime"),
                OrderStatus = (OrderStatusEnum)newParms.GetInt("OrderStatus"),
                OrderNo = newParms.GetStringValue("OrderNo"),
                MerchantsNo = newParms.GetStringValue("MerchantsNo"),
                UserId = newParms.GetInt("UserId"),
                GoodsName = newParms.GetStringValue("GoodsName"),
                Consignee = newParms.GetStringValue("Consignee"),
                Recycled = newParms.GetInt("Recycled"),
                AnchorName = newParms.GetStringValue("AnchorName"),
                IsSelectPayMoney = newParms.GetInt("IsSelectPayMoney", 0)
            };

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            demodel.OrderClassify = 2;
            var list = orderModule.GetEducationGoodsOrderPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.OrderId,
                x.OrderNo,
                x.MerchantsNo,
                x.OrderSource,
                OrderSourceName = x.OrderSource.GetEnumName(),
                x.UserId,
                x.UserName,
                x.DeliveryMethod,
                DeliveryMethodName = x.DeliveryMethod.GetEnumName(),
                x.Income,
                x.FreightMoney,
                x.PaymentWay,
                PaymentWayName = x.PaymentWay.GetEnumName(),
                CouponMoney = x.CouponMoney ?? 0,
                EducationMoney = x.EducationMoney ?? 0,
                IntegralMoney = (x.DetailList != null && x.DetailList.Any()) ? (x.DetailList.Sum(x => x.IntegralMoney ?? 0)) : 0,
                IntegralNumber = (x.DetailList != null && x.DetailList.Any()) ? (x.DetailList.Sum(x => x.IntegralNumber ?? 0)) : 0,
                MemberDiscountCouponList = x.MemberDiscountCouponList.Select(y => new
                {
                    y.Name,
                    y.MinConsumePrice,
                    y.MaxDiscountsPrice,
                    y.UseType,
                    y.CouponType,
                    y.DiscountsPrice
                }),
                DetailList = x.DetailList.Select(y => new
                {
                    y.SupplierId,
                    y.SupplierName,
                    y.FreightCostMoney,
                    y.FreightMoney,
                    y.CostMoney,
                    y.Id,
                    y.CoverImage,
                    y.CoverImagePath,
                    y.OrderType,
                    OrderTypeName = y.OrderType.GetEnumName(),
                    y.GoodsName,
                    SpecificationList = y.TeacherList.Select(x => x.Name),
                    y.ProductCode,
                    y.Final_Price,
                    y.Number,
                    y.IsBindExpress,
                    y.FreeShippingRemarks,
                    y.SmallShopsCostPrice,
                    y.YSMoney,
                    y.RealMoney,
                    y.YFMoney,
                    y.PayMoney,
                    CouponMoney = y.CouponMoney ?? 0,
                    InsuranceMoney = y.InsuranceMoney ?? 0,
                    InsuranceCostMoney = y.InsuranceCostMoney ?? 0,
                    IntegralMoney = y.IntegralMoney ?? 0,
                    IntegralNumber = y.IntegralNumber ?? 0,
                    MemberEducationCouponList = y.MemberEducationCouponList.Select(z => new
                    {
                        z.Name,
                    }),
                    SFinanceList = y.FinanceList.Where(z => z.Type == 1).Select(z => new
                    {
                        z.FrID,
                        z.Status,
                        z.Is_Cashier
                    }),
                    ZFinanceList = y.FinanceList.Where(z => z.Type == 2).Select(z => new
                    {
                        z.FrID,
                        z.Status,
                        z.Is_Cashier
                    })
                }),
                x.Consignee,
                x.Mobile,
                x.DistrictAddress,
                x.ShoppingAddress,
                x.BuyerMessage,
                x.Remark,
                x.OrderStatus,
                OrderStatusName = x.OrderStatus.GetEnumName(),
                PaymentTime = x.PaymentTime.HasValue ? x.PaymentTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                DeliveryTime = x.DeliveryTime.HasValue ? x.DeliveryTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                ReceivingTime = x.ReceivingTime.HasValue ? x.ReceivingTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                FinishTime = x.FinishTime.HasValue ? x.FinishTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                x.Country,
                x.Province,
                x.City,
                x.District,
                x.TenantId,
                x.MallBaseId,
                x.SmallShopsId,
                x.SmallShopsName,
                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 GetEducationGoodsOrderInfo()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int OrderId = parms.GetInt("OrderId", 0);
            if (OrderId <= 0)
            {
                return ApiResult.Failed();
            }

            return orderModule.GetEducationGoodsOrderInfo(OrderId, req.TenantId, req.MallBaseId);
        }



        /// <summary>
        /// 获取商品订单导出选项列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetEducationOrderListExportForEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(OrderListExportForEducationEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }

        /// <summary>
        /// 商品订单下载
        /// </summary>
        [HttpPost]
        public FileContentResult GetEduGoodsOrderListToExcel()
        {
            var parms = RequestParm;
            RB_Goods_Order_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Order_Extend>(parms.msg.ToString());
            string ExcelName = "教育订单列表" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            List<ExcelDataSource> slist = new List<ExcelDataSource>();
            if (demodel.ExcelEnumIds == null || !demodel.ExcelEnumIds.Any())
            {
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }
            var Enumlist = EnumHelper.GetEnumList(typeof(OrderListExportForEducationEnum));
            ExcelDataSource header = new ExcelDataSource()
            {
                ExcelRows = new List<ExcelColumn>(30) {
                    new ExcelColumn(value: "序号") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER }
                }
            };
            foreach (var item in demodel.ExcelEnumIds)
            {
                var Name = Enumlist.Where(x => x.Value == item.ToString()).FirstOrDefault().Key ?? "";
                header.ExcelRows.Add(new ExcelColumn(value: Name) { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER });
            }

            slist.Add(header);

            try
            {
                demodel.TenantId = Convert.ToInt32(parms.uid);
                demodel.MallBaseId = parms.MallBaseId;
                if (!(demodel.OrderStatus > 0))
                {
                    demodel.IsNotSelectCancel = 1;
                }
                var list = orderModule.GetEducationGoodsOrderPageList(1, 10000, out long count, demodel);
                #region 组装数据
                int Num = 0;
                foreach (var item in list)
                {
                    foreach (var item2 in item.DetailList)
                    {
                        Num++;
                        ExcelDataSource datarow = new ExcelDataSource()
                        {
                            ExcelRows = new List<ExcelColumn>(20) {
                                new ExcelColumn(value:Num.ToString()){ },
                            },
                            ColumnHight = 30
                        };
                        foreach (var qitem in demodel.ExcelEnumIds)
                        {
                            switch (qitem)
                            {
                                case 1:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderSource.GetEnumName()) { }); break;
                                case 2:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderNo) { }); break;
                                case 3:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.MerchantsNo) { }); break;
                                case 4:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.UserName) { }); break;
                                case 5:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item2.GoodsName) { }); break;
                                case 28:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item2.GoodsSubName) { }); break;
                                case 7:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: (item2.Number ?? 0).ToString()) { }); break;
                                case 9:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: (item2.CostMoney ?? 0).ToString()) { }); break;

                                case 10:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: (item2.Original_Price ?? 0).ToString()) { }); break;
                                case 11:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: (item2.Final_Price ?? 0).ToString()) { }); break;

                                case 12:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss")) { }); break;
                                case 13:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.PaymentWay.GetEnumName()) { }); break;
                                case 14:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderStatus.GetEnumName()) { }); break;
                                case 15:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderStatus > OrderStatusEnum.NonPayment ? "已付款" : "未付款") { }); break;
                                case 16:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.PaymentTime.HasValue ? item.PaymentTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "") { }); break;
                                case 17:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: (item2.TeacherList != null && item2.TeacherList.Any() ? (string.Join(",", item2.TeacherList.Select(x => x.Name))) : "")) { }); break;
                                case 18:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: "") { }); break;
                                case 19:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.Remark) { }); break;
                                case 20:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.BuyerMessage) { }); break;

                            }
                        }
                        slist.Add(datarow);
                    }
                }
                #endregion

                var byteData = ExcelTempLateHelper.ToExcelExtend(slist);

                return File(byteData, "application/octet-stream", ExcelName);
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, string.Format("GetFileFromWebApi_requestData: {0}", JsonHelper.Serialize(RequestParm)));
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }

        }




        /// <summary>
        /// 后台订单强制取消
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetEducationOrderForcedToCancel()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int OrderId = parms.GetInt("OrderId", 0);
            //string Remark = parms.GetStringValue("Remark");
            if (OrderId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            var omodel = orderModule.GetOrderInfo(OrderId);
            if (omodel == null)
            {
                return ApiResult.Failed("订单不存在");
            }
            if (omodel.Status == 1)
            {
                return ApiResult.Failed("订单已删除");
            }
            if (omodel.Recycled == 1)
            {
                return ApiResult.Failed("订单已进入回收站无法操作");
            }
            if (omodel.OrderStatus != OrderStatusEnum.NonPayment && omodel.OrderStatus != OrderStatusEnum.WaitSendGoods)
            {
                return ApiResult.Failed("该订单已无法取消");
            }
            int IsNormalServer = Convert.ToInt32(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("IsNormalServer").Value);
            if (IsNormalServer == 1 && omodel.OrderStatus == OrderStatusEnum.WaitSendGoods && omodel.OrderSource != UserSourceEnum.ERP)
            {
                //获取小程序信息
                var mallModel = orderModule.GetMiniProgramExtend(req.MallBaseId);
                int RefundNum = orderModule.GetOrderRefundOnlineTradeNum(OrderId, req.TenantId, req.MallBaseId);
                string RefundOrderNo = omodel.OrderNo + (RefundNum + 1);
                var pram = new Common.Pay.WeChatPat.PayParam()
                {
                    TotalFee = Convert.ToInt32((omodel.Income ?? 0) * 100),
                    RefundFee = Convert.ToInt32((omodel.Income ?? 0) * 100),
                    OrderNumber = omodel.MerchantsNo,
                    RefundNumber = RefundOrderNo
                };
                var Robj = new App_Code.PayUtil().Refund(pram, mallModel, _accessor);
                if (Robj.IsSuccess)
                {
                    //获取商品信息
                    var orderGoodsList = orderModule.GetOrderDetailList(new RB_Goods_OrderDetail_Extend { TenantId = omodel.TenantId, MallBaseId = omodel.MallBaseId, OrderId = omodel.OrderId });
                    string goodsName = orderGoodsList.FirstOrDefault().GoodsName;
                    if (orderGoodsList.Count > 1)
                    {
                        if (goodsName.Length > 12)
                        {
                            goodsName = goodsName.Substring(0, 11) + "..";
                        }
                        goodsName += "等" + orderGoodsList.Count + "件商品";
                    }
                    else
                    {
                        if (goodsName.Length > 18)
                        {
                            goodsName = goodsName.Substring(0, 18) + "..";
                        }
                    }

                    //退款成功发送退款成功的订阅消息
                    //根据订单下单人获取openid
                    var userModel = orderModule.GetMemberUserInfo(omodel.UserId.Value);
                    if (userModel != null)
                    {
                        miniProgramMsgModule.SendOrderRefundMsg(mallModel.TenantId.Value, mallModel.MallBaseId, userModel.OpenId, "已退款，请注意查收", omodel.OrderNo, (omodel.Income ?? 0).ToString(), goodsName);
                    }
                    var dic = ((Dictionary<string, string>)Robj.Data);
                    bool flag = orderModule.SetOrderForcedToCancel(omodel, RefundOrderNo, req.TenantId, req.MallBaseId, Common.Enum.Goods.OrderPayTypeEnum.WeChatPay, dic["dPrice"], dic["sOrderNo"], dic["sTradeNo"], dic["refundid"]);
                    if (flag)
                    {
                        return ApiResult.Success();
                    }
                    else
                    {
                        return ApiResult.Failed();
                    }
                }
                else
                {
                    LogHelper.Write(JsonConvert.SerializeObject(Robj));
                    return ApiResult.Failed();
                }
            }
            else
            {
                bool flag = orderModule.SetOrderForcedToCancel(omodel, "", req.TenantId, req.MallBaseId, Common.Enum.Goods.OrderPayTypeEnum.WeChatPay, "", "", "", "");
                if (flag)
                {
                    return ApiResult.Success();
                }
                else
                {
                    return ApiResult.Failed();
                }
            }
        }


        /// <summary>
        /// 获取订单状态枚举
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult EducationOrderStatusEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(Common.Enum.Goods.EducationOrderStatusEnum));
            return ApiResult.Success("", list.OrderBy(x => Convert.ToInt32(x.Value)).Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }


        #endregion

        #region 线下服务订单
        /// <summary>
        /// 商品订单后台分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetOfflineServiceOrderPage()
        {
            var parms = RequestParm;
            JObject newParms = JObject.Parse(RequestParm.msg.ToString());
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Goods_Order_Extend demodel = new RB_Goods_Order_Extend()
            {
                UserName = newParms.GetStringValue("UserName"),
                OrderSource = (UserSourceEnum)newParms.GetInt("OrderSource"),
                OrderType = newParms.GetInt("OrderType"),
                OrderId = newParms.GetInt("OrderId"),
                StartTime = newParms.GetStringValue("StartTime"),
                EndTime = newParms.GetStringValue("EndTime"),
                OrderStatus = (OrderStatusEnum)newParms.GetInt("OrderStatus"),
                OrderNo = newParms.GetStringValue("OrderNo"),
                MerchantsNo = newParms.GetStringValue("MerchantsNo"),
                UserId = newParms.GetInt("UserId"),
                GoodsName = newParms.GetStringValue("GoodsName"),
                Consignee = newParms.GetStringValue("Consignee"),
                Recycled = newParms.GetInt("Recycled"),
                AnchorName = newParms.GetStringValue("AnchorName"),
                IsSelectPayMoney = newParms.GetInt("IsSelectPayMoney", 0)
            };

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            demodel.OrderClassify = 3;
            var list = orderModule.GetOfflineServiceOrderPageListModule(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            var obj = list.Select(x => new
            {
                x.OrderId,
                x.OrderNo,
                x.MerchantsNo,
                x.OrderSource,
                OrderSourceName = x.OrderSource.GetEnumName(),
                x.UserId,
                x.UserName,
                x.DeliveryMethod,
                DeliveryMethodName = x.DeliveryMethod.GetEnumName(),
                x.Income,
                x.FreightMoney,
                x.PaymentWay,
                PaymentWayName = x.PaymentWay.GetEnumName(),
                CouponMoney = x.CouponMoney ?? 0,
                EducationMoney = x.EducationMoney ?? 0,
                IntegralMoney = (x.DetailList != null && x.DetailList.Any()) ? (x.DetailList.Sum(x => x.IntegralMoney ?? 0)) : 0,
                IntegralNumber = (x.DetailList != null && x.DetailList.Any()) ? (x.DetailList.Sum(x => x.IntegralNumber ?? 0)) : 0,
                MemberDiscountCouponList = x.MemberDiscountCouponList.Select(y => new
                {
                    y.Name,
                    y.MinConsumePrice,
                    y.MaxDiscountsPrice,
                    y.UseType,
                    y.CouponType,
                    y.DiscountsPrice
                }),
                DetailList = x.DetailList.Select(y => new
                {
                    y.FreightCostMoney,
                    y.FreightMoney,
                    y.CostMoney,
                    y.Id,
                    y.CoverImage,
                    y.CoverImagePath,
                    y.OrderType,
                    OrderTypeName = y.OrderType.GetEnumName(),
                    y.GoodsId,
                    y.GoodsName,
                    y.ProductCode,
                    y.Final_Price,
                    y.Number,
                    y.SmallShopsCostPrice,
                    y.YSMoney,
                    y.RealMoney,
                    y.YFMoney,
                    y.PayMoney,
                    CouponMoney = y.CouponMoney ?? 0,
                    InsuranceMoney = y.InsuranceMoney ?? 0,
                    InsuranceCostMoney = y.InsuranceCostMoney ?? 0,
                    MemberEducationCouponList = y.ReserveCouponList.Select(z => new
                    {
                        z.Name,
                    }),
                    SFinanceList = y.FinanceList.Where(z => z.Type == 1).Select(z => new
                    {
                        z.FrID,
                        z.Status,
                        z.Is_Cashier
                    }),
                    ZFinanceList = y.FinanceList.Where(z => z.Type == 2).Select(z => new
                    {
                        z.FrID,
                        z.Status,
                        z.Is_Cashier
                    }),
                    y.ServiceDate,
                    y.ServiceTime,
                    y.GoodServiceTime,
                    y.ServicepersonalName,
                    y.ServicepersonalId,
                }),
                x.Consignee,
                x.Mobile,
                x.DistrictAddress,
                x.ShoppingAddress,
                x.BuyerMessage,
                x.Remark,
                x.OrderStatus,
                OrderStatusName = x.OrderStatus.GetEnumName(),
                PaymentTime = x.PaymentTime.HasValue ? x.PaymentTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                DeliveryTime = x.DeliveryTime.HasValue ? x.DeliveryTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                ReceivingTime = x.ReceivingTime.HasValue ? x.ReceivingTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                FinishTime = x.FinishTime.HasValue ? x.FinishTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                x.Country,
                x.Province,
                x.City,
                x.District,
                x.TenantId,
                x.MallBaseId,
                x.SmallShopsId,
                x.SmallShopsName,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                x.StoresId,
                x.StoreName,
                x.StoresAddress,
            });
            pagelist.pageData = obj;
            return ApiResult.Success("", pagelist);
        }
        #endregion


        #region 修改运费成本以及商品成本、供应商
        /// <summary>
        /// 修改订单商品成本运费
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetOrderFreightCostMoney()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int OrderId = parms.GetInt("Id", 0);
            int EmpId = parms.GetInt("EmpId", 0);
            decimal FreightMoney = parms.GetDecimal("FreightCostMoney");
            if (OrderId <= 0)
            {
                return ApiResult.ParamIsNull("请传递订单明细id");
            }

            if (FreightMoney < 0)
            {
                return ApiResult.ParamIsNull("请传递运费成本");
            }

            bool flag = orderModule.SetOrderFreightCostMoney(OrderId, FreightMoney, EmpId, req.TenantId, req.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 修改商品成本
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetOrderCostMoney()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int OrderId = parms.GetInt("Id", 0);
            int EmpId = parms.GetInt("EmpId", 0);
            decimal costMoney = parms.GetDecimal("CostMoney");
            if (OrderId <= 0)
            {
                return ApiResult.ParamIsNull("请传递订单明细id");
            }
            if (costMoney < 0)
            {
                return ApiResult.ParamIsNull("请传递商品成本");
            }
            bool flag = orderModule.SetOrderCostMoney(OrderId, costMoney, EmpId, req.TenantId, req.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 修改订单供应商
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetOrderSupplierId()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int OrderId = parms.GetInt("Id", 0);
            int SupplierId = parms.GetInt("SupplierId", 0);
            if (OrderId <= 0)
            {
                return ApiResult.ParamIsNull("请传递订单明细id");
            }
            if (SupplierId < 0)
            {
                return ApiResult.ParamIsNull("请传递供应商信息");
            }
            bool flag = orderModule.SetOrderSupplierId(OrderId, SupplierId, req.TenantId, req.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }



        /// <summary>
        /// 修改订单商品的主播信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult UpdateOrderDetailLive()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            string OrderIds = parms.GetStringValue("Ids");
            int Type = parms.GetInt("Type", 0);//1-更新人数和金额，2-更新人数，3-更新金额
            int LivePeopleNum = parms.GetInt("LivePeopleNum", 0);
            decimal LiveCommission = parms.GetDecimal("LiveCommission");
            if (string.IsNullOrWhiteSpace(OrderIds))
            {
                return ApiResult.ParamIsNull("请传递订单明细id");
            }
            if (Type < 0)
            {
                return ApiResult.ParamIsNull("请传递需要操作的类型");
            }
            if (Type == 1 || Type == 2)
            {
                if (LivePeopleNum <= 0)
                {
                    return ApiResult.ParamIsNull("人数不能为0");
                }
            }
            if (Type == 1 || Type == 3)
            {
                if (LiveCommission < 0)
                {
                    return ApiResult.ParamIsNull("佣金不能小于0");
                }
            }

            //根据订单ids判断是否已经制单
            var orderDetailsList = orderModule.GetOrderDetailList(new RB_Goods_OrderDetail_Extend { OrderDetailIds = OrderIds, MallBaseId = req.MallBaseId, TenantId = req.TenantId });

            if (orderDetailsList != null && orderDetailsList.Any(x => !string.IsNullOrWhiteSpace(x.LiveFinanceIds)))
            {
                return ApiResult.ParamIsNull("部分订单已制单，不能修改");
            }

            bool flag = orderModule.UpdateOrderDetailLive(Type, LivePeopleNum, LiveCommission, orderDetailsList, req.TenantId, req.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }


        /// <summary>
        /// 设置订单为线下付款
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetOrderOfflinePayment()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int OrderId = parms.GetInt("OrderId", 0);
            if (OrderId <= 0)
            {
                return ApiResult.ParamIsNull("请传递订单明细id");
            }
            var orderModel = orderModule.GetOrderInfo(OrderId);
            if (orderModel == null)
            {
                return ApiResult.Failed("订单不存在");
            }
            if (orderModel.OrderStatus != OrderStatusEnum.Cancel && orderModel.OrderStatus != OrderStatusEnum.NonPayment && orderModel.PaymentTime.HasValue)
            {
                return ApiResult.Failed("订单状态不正确");
            }

            bool flag = orderModule.SetOrderOfflinePayment(orderModel, req.TenantId, req.MallBaseId, req.EmpId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        #endregion

        #endregion

        #region 主播返佣

        /// <summary>
        /// 直播订单后台分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetLiveGoodsOrderPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Goods_OrderDetail_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_OrderDetail_Extend>(parms.msg.ToString());

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            demodel.IsLiveOrder = 1;
            var list = orderModule.GetLiveGoodsOrderPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(y => new
            {
                y.OrderId,
                y.OrderNo,
                OrderDetailId = y.Id,
                y.CoverImage,
                y.GoodsName,
                SpecificationList = JsonConvert.DeserializeObject<List<string>>(y.Specification),
                y.Final_Price,
                y.Number,
                y.Unit_Price,
                y.LiveCommission,
                y.LivePeopleNum,
                y.LiveFinanceIds
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 直播订单创建财务单据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetLiveGoodsOrderFinance()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int IsPublic = parms.GetInt("IsPublic", 0);//账户类型
            int ErpEmpId = parms.GetInt("ErpEmpId", 0);
            string LiveTime = parms.GetStringValue("LiveTime");//直播时间
            if (ErpEmpId <= 0)
            {
                ErpEmpId = req.ERPEmpId;
            }
            string AccountIds = parms.GetStringValue("AccountIds");//账户ids
            string OrderDetailIds = parms.GetStringValue("OrderDetailIds");//订单明细ids
            if (string.IsNullOrEmpty(AccountIds))
            {
                return ApiResult.ParamIsNull("账户不存在");
            }
            if (string.IsNullOrEmpty(OrderDetailIds))
            {
                return ApiResult.ParamIsNull("订单明细不存在");
            }
            List<int> AccountIdList;
            try
            {
                AccountIdList = JsonConvert.DeserializeObject<List<int>>(AccountIds);
            }
            catch (Exception)
            {
                return ApiResult.ParamIsNull("账户格式有误");
            }

            List<int> OrderdetailIdList;
            try
            {
                OrderdetailIdList = JsonConvert.DeserializeObject<List<int>>(OrderDetailIds);
            }
            catch (Exception)
            {
                return ApiResult.ParamIsNull("订单明细格式有误");
            }
            if (!AccountIdList.Any())
            {
                return ApiResult.ParamIsNull("请选择账户");
            }
            if (!OrderdetailIdList.Any())
            {
                return ApiResult.ParamIsNull("请选择订单列表");
            }

            string msg = orderModule.SetLiveGoodsOrderFinance(IsPublic, AccountIdList, OrderdetailIdList, LiveTime, req.TenantId, req.MallBaseId, ErpEmpId);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        #endregion

        #region 会员购买

        /// <summary>
        /// 会员购买后台分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMembersToBuyPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Goods_Order_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Order_Extend>(parms.msg.ToString());

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = orderModule.GetMembersToBuyPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.OrderId,
                x.OrderNo,
                x.OrderSource,
                OrderSourceName = x.OrderSource.GetEnumName(),
                x.UserId,
                x.UserName,
                x.Income,
                x.PaymentWay,
                PaymentWayName = x.PaymentWay.GetEnumName(),
                x.OrderStatus,
                OrderStatusName = x.OrderStatus.GetEnumName(),
                PaymentTime = x.PaymentTime.HasValue ? x.PaymentTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                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 GetMembersToBuyExportEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(MembersToBuyExportEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }

        /// <summary>
        /// 会员购买Excel下载
        /// </summary>
        [HttpPost]
        public FileContentResult GetMembersToBuyToExcel()
        {
            var parms = RequestParm;
            RB_Goods_Order_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Order_Extend>(parms.msg.ToString());
            string ExcelName = "会员购买" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            List<ExcelDataSource> slist = new List<ExcelDataSource>();
            if (demodel.ExcelEnumIds == null || !demodel.ExcelEnumIds.Any())
            {
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }
            var Enumlist = EnumHelper.GetEnumList(typeof(MembersToBuyExportEnum));
            ExcelDataSource header = new ExcelDataSource()
            {
                ExcelRows = new List<ExcelColumn>(30) {
                    new ExcelColumn(value: "序号") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER }
                }
            };
            foreach (var item in demodel.ExcelEnumIds)
            {
                var Name = Enumlist.Where(x => x.Value == item.ToString()).FirstOrDefault().Key ?? "";
                header.ExcelRows.Add(new ExcelColumn(value: Name) { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER });
            }

            slist.Add(header);

            try
            {
                demodel.TenantId = Convert.ToInt32(parms.uid);
                demodel.MallBaseId = parms.MallBaseId;
                var list = orderModule.GetMembersToBuyPageList(1, 10000, out long count, demodel);
                #region 组装数据
                int Num = 0;
                foreach (var item in list)
                {
                    foreach (var item2 in item.DetailList)
                    {
                        Num++;
                        ExcelDataSource datarow = new ExcelDataSource()
                        {
                            ExcelRows = new List<ExcelColumn>(30) {
                            new ExcelColumn(value:Num.ToString()){ },
                        }
                        };
                        foreach (var qitem in demodel.ExcelEnumIds)
                        {
                            switch (qitem)
                            {
                                case 1:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderSource.GetEnumName()) { }); break;
                                case 2:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderNo) { }); break;
                                case 3:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.UserName) { }); break;
                                case 4:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: (item.Income ?? 0).ToString()) { }); break;
                                case 5:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.PaymentTime.Value.ToString("yyyy-MM-dd HH:mm:ss")) { }); break;
                                case 6:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderStatus.GetEnumName()) { }); break;
                            }
                        }
                        slist.Add(datarow);
                    }
                }
                #endregion

                var byteData = ExcelTempLateHelper.ToExcelExtend(slist);

                return File(byteData, "application/octet-stream", ExcelName);
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, string.Format("GetFileFromWebApi_requestData: {0}", JsonHelper.Serialize(RequestParm)));
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }

        }

        #endregion

        #region 分销订单

        /// <summary>
        /// 分销订单后台分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDistributionOrdersPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            JObject parameters = JObject.Parse(parms.msg.ToString());
            RB_Goods_Order_Extend demodel = new RB_Goods_Order_Extend()
            {
                OrderSource = (UserSourceEnum)parameters.GetInt("OrderSource"),
                OrderType = parameters.GetInt("OrderType"),
                DeliveryMethod = (OrderDeliveryMethodEnum)parameters.GetInt("DeliveryMethod"),
                OrderId = parameters.GetInt("OrderId"),
                StartTime = parameters.GetStringValue("StartTime"),
                EndTime = parameters.GetStringValue("EndTime"),
                OrderStatus = (OrderStatusEnum)parameters.GetInt("OrderStatus"),
                OrderNo = parameters.GetStringValue("OrderNo"),
                UserName = parameters.GetStringValue("UserName"),
                UserId = parameters.GetInt("UserId"),
                GoodsName = parameters.GetStringValue("GoodsName"),
                DistributionUserId = parameters.GetInt("DistributionUserId")
            };
            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            demodel.Recycled = 2;
            var list = orderModule.GetDistributionOrdersPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.OrderId,
                x.OrderNo,
                x.MerchantsNo,
                x.OrderSource,
                OrderSourceName = x.OrderSource.GetEnumName(),
                x.UserId,
                x.UserName,
                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.CoverImage,
                    y.CoverImagePath,
                    y.OrderType,
                    OrderTypeName = y.OrderType.GetEnumName(),
                    y.GoodsName,
                    SpecificationList = !string.IsNullOrEmpty(y.Specification) ? JsonConvert.DeserializeObject<List<string>>(y.Specification) : new List<string>(),
                    y.ProductCode,
                    y.Final_Price,
                    y.Number
                }),
                x.Consignee,
                x.Mobile,
                x.ShoppingAddress,
                x.BuyerMessage,
                x.Remark,
                x.OrderStatus,
                OrderStatusName = x.OrderStatus.GetEnumName(),
                PaymentTime = x.PaymentTime.HasValue ? x.PaymentTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                DeliveryTime = x.DeliveryTime.HasValue ? x.DeliveryTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                ReceivingTime = x.ReceivingTime.HasValue ? x.ReceivingTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                x.IsOrderCommission,
                OrderCommissionList = x.OrderCommissionList.Select(z => new
                {
                    z.Id,
                    z.Grade,
                    z.GradeDescription,
                    z.UserId,
                    z.UserName,
                    z.Mobile,
                    z.Name,
                    z.Commission,
                    z.CommissionState,
                    DeductionCommission = z.DeductionCommission ?? 0
                }),
                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 GetDistributionOrdersExportEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(DistributionOrdersExportEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }

        /// <summary>
        /// 分销订单Excel下载
        /// </summary>
        [HttpPost]
        public FileContentResult GetDistributionOrdersToExcel()
        {
            var parms = RequestParm;
            RB_Goods_Order_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Order_Extend>(parms.msg.ToString());
            string ExcelName = "分销订单" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            List<ExcelDataSource> slist = new List<ExcelDataSource>();
            if (demodel.ExcelEnumIds == null || !demodel.ExcelEnumIds.Any())
            {
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }
            var Enumlist = EnumHelper.GetEnumList(typeof(DistributionOrdersExportEnum));
            ExcelDataSource header = new ExcelDataSource()
            {
                ExcelRows = new List<ExcelColumn>(30) {
                    new ExcelColumn(value: "序号") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER }
                }
            };
            foreach (var item in demodel.ExcelEnumIds)
            {
                var Name = Enumlist.Where(x => x.Value == item.ToString()).FirstOrDefault().Key ?? "";
                header.ExcelRows.Add(new ExcelColumn(value: Name) { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER });
            }

            slist.Add(header);

            try
            {
                demodel.TenantId = Convert.ToInt32(parms.uid);
                demodel.MallBaseId = parms.MallBaseId;
                var list = orderModule.GetDistributionOrdersPageListToExcel(1, 10000, out long count, demodel);
                #region 组装数据
                int Num = 0;
                foreach (var item in list)
                {
                    foreach (var item2 in item.DetailList)
                    {
                        //获取返佣
                        string ZGFY = "", YJFX = "", EJFX = "", SJFX = "", YJYJ = "", EJYJ = "", SJYJ = "";
                        var ocList = item.OrderCommissionList.Where(x => x.OrderDetailId == item2.Id).ToList();
                        if (ocList.Any())
                        {
                            foreach (var ocitem in ocList)
                            {
                                switch (ocitem.Grade)
                                {
                                    case 0:
                                        ZGFY = (ocitem.Commission ?? 0).ToString(); break;
                                    case 1:
                                        YJFX = $"昵称：{ocitem.UserName}，姓名：{ocitem.Name}，手机号：{ocitem.Mobile}";
                                        YJYJ = (ocitem.Commission ?? 0).ToString(); break;
                                    case 2:
                                        EJFX = $"昵称：{ocitem.UserName}，姓名：{ocitem.Name}，手机号：{ocitem.Mobile}";
                                        EJYJ = (ocitem.Commission ?? 0).ToString(); break;
                                    case 3:
                                        SJFX = $"昵称：{ocitem.UserName}，姓名：{ocitem.Name}，手机号：{ocitem.Mobile}";
                                        SJYJ = (ocitem.Commission ?? 0).ToString(); break;
                                }
                            }
                        }
                        Num++;
                        ExcelDataSource datarow = new ExcelDataSource()
                        {
                            ExcelRows = new List<ExcelColumn>(30) {
                            new ExcelColumn(value:Num.ToString()){ },
                        },
                            ColumnHight = 30
                        };
                        foreach (var qitem in demodel.ExcelEnumIds)
                        {
                            switch (qitem)
                            {
                                case 1:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderSource.GetEnumName()) { }); break;
                                case 2:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderNo) { }); break;
                                case 3:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.MerchantsNo) { }); break;
                                case 4:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.UserName) { }); break;
                                case 5:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item2.GoodsName) { }); break;
                                case 6:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item2.Specification) { }); break;
                                case 7:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: (item2.Number ?? 0).ToString()) { }); break;
                                case 8:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item2.ProductCode) { }); break;
                                case 10:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.Consignee) { }); break;
                                case 11:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.Mobile) { }); break;
                                case 12:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.ShoppingAddress) { }); break;
                                case 13:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: (item2.Original_Price ?? 0).ToString()) { }); break;
                                case 14:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: (item2.Final_Price ?? 0).ToString()) { }); break;
                                case 16:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss")) { }); break;
                                case 17:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderStatus.GetEnumName()) { }); break;
                                case 18:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.PaymentWay.GetEnumName()) { }); break;
                                case 19:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderStatus > OrderStatusEnum.NonPayment ? "已付款" : "未付款") { }); break;
                                case 20:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.PaymentTime.HasValue ? item.PaymentTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "") { }); break;
                                case 21:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.Remark) { }); break;
                                case 22:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.BuyerMessage) { }); break;
                                case 23:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: ZGFY) { }); break;
                                case 24:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: YJFX) { }); break;
                                case 25:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: EJFX) { }); break;
                                case 26:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: SJFX) { }); break;
                                case 27:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: YJYJ) { }); break;
                                case 28:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: EJYJ) { }); break;
                                case 29:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: SJYJ) { }); break;

                            }
                        }
                        slist.Add(datarow);
                    }
                }
                #endregion

                var byteData = ExcelTempLateHelper.ToExcelExtend(slist);

                return File(byteData, "application/octet-stream", ExcelName);
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, string.Format("GetFileFromWebApi_requestData: {0}", JsonHelper.Serialize(RequestParm)));
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }

        }


        /// <summary>
        /// 获取分销订单导出选项列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDistributionOrdersExportEnumListForFX()
        {
            var list = EnumHelper.GetEnumList(typeof(DistributionOrdersExportForFXEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }

        /// <summary>
        /// 分销订单Excel下载
        /// </summary>
        [HttpPost]
        public FileContentResult GetDistributionOrdersToExcelForFX()
        {
            var parms = RequestParm;
            RB_Goods_Order_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Order_Extend>(parms.msg.ToString());
            string ExcelName = "分销订单" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            List<ExcelDataSource> slist = new List<ExcelDataSource>();
            if (demodel.ExcelEnumIds == null || !demodel.ExcelEnumIds.Any())
            {
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }
            var Enumlist = EnumHelper.GetEnumList(typeof(DistributionOrdersExportForFXEnum));
            ExcelDataSource header = new ExcelDataSource()
            {
                ExcelRows = new List<ExcelColumn>(30) {
                    new ExcelColumn(value: "序号") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER }
                }
            };
            foreach (var item in demodel.ExcelEnumIds)
            {
                var Name = Enumlist.Where(x => x.Value == item.ToString()).FirstOrDefault().Key ?? "";
                header.ExcelRows.Add(new ExcelColumn(value: Name) { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER });
            }

            slist.Add(header);

            try
            {
                demodel.TenantId = Convert.ToInt32(parms.uid);
                demodel.MallBaseId = parms.MallBaseId;
                var list = orderModule.GetDistributionOrdersPageListToExcel(1, 10000, out long count, demodel);
                #region 组装数据
                int Num = 0;
                foreach (var item in list)
                {
                    foreach (var item2 in item.DetailList)
                    {
                        Num++;
                        var ocList = item.OrderCommissionList.Where(x => x.OrderDetailId == item2.Id).ToList();
                        int OCCount = ocList.Count();
                        OCCount = OCCount == 0 ? 1 : OCCount;
                        ExcelDataSource datarow = new ExcelDataSource()
                        {
                            ExcelRows = new List<ExcelColumn>(30) {
                                new ExcelColumn(value:Num.ToString()){ Rowspan = OCCount},
                            },
                            ColumnHight = 30
                        };
                        int QNum = 0;
                        foreach (var qitem in demodel.ExcelEnumIds)
                        {
                            switch (qitem)
                            {
                                case 1:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderSource.GetEnumName()) { Rowspan = OCCount }); QNum++; break;
                                case 2:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderNo) { Rowspan = OCCount }); QNum++; break;
                                case 3:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.MerchantsNo) { Rowspan = OCCount }); QNum++; break;
                                case 4:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.UserName) { Rowspan = OCCount }); QNum++; break;
                                case 5:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item2.GoodsName) { Rowspan = OCCount }); QNum++; break;
                                case 6:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item2.Specification) { Rowspan = OCCount }); QNum++; break;
                                case 7:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: (item2.Number ?? 0).ToString()) { Rowspan = OCCount }); QNum++; break;
                                case 8:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item2.ProductCode) { Rowspan = OCCount }); QNum++; break;
                                case 10:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.Consignee) { Rowspan = OCCount }); QNum++; break;
                                case 11:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.Mobile) { Rowspan = OCCount }); QNum++; break;
                                case 12:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.ShoppingAddress) { Rowspan = OCCount }); QNum++; break;
                                case 13:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: (item2.Original_Price ?? 0).ToString()) { Rowspan = OCCount }); QNum++; break;
                                case 14:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: (item2.Final_Price ?? 0).ToString()) { Rowspan = OCCount }); QNum++; break;
                                case 16:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss")) { Rowspan = OCCount }); QNum++; break;
                                case 17:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderStatus.GetEnumName()) { Rowspan = OCCount }); QNum++; break;
                                case 18:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.PaymentWay.GetEnumName()) { Rowspan = OCCount }); QNum++; break;
                                case 19:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderStatus > OrderStatusEnum.NonPayment ? "已付款" : "未付款") { Rowspan = OCCount }); QNum++; break;
                                case 20:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.PaymentTime.HasValue ? item.PaymentTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "") { Rowspan = OCCount }); QNum++; break;
                                case 21:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.Remark) { Rowspan = OCCount }); QNum++; break;
                                case 22:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.BuyerMessage) { Rowspan = OCCount }); QNum++; break;
                            }
                        }
                        bool IsOCFirst = true;
                        if (ocList.Any())
                        {
                            ocList = ocList.OrderBy(x => x.Grade).ToList();
                            foreach (var ocitem in ocList)
                            {
                                if (!IsOCFirst)
                                {
                                    datarow = new ExcelDataSource()
                                    {
                                        ExcelRows = new List<ExcelColumn>(30) {
                                            new ExcelColumn(value:Num.ToString()){ },
                                        },
                                        ColumnHight = 30
                                    };
                                    for (var i = 0; i < QNum; i++)
                                    {
                                        datarow.ExcelRows.Add(new ExcelColumn(value: "") { });
                                    }
                                }

                                string UserName = $"昵称：{ocitem.UserName}，姓名：{ocitem.Name}，手机号：{ocitem.Mobile}";
                                datarow.ExcelRows.Add(new ExcelColumn(value: ocitem.GradeDescription) { });
                                datarow.ExcelRows.Add(new ExcelColumn(value: UserName) { });
                                datarow.ExcelRows.Add(new ExcelColumn(value: (ocitem.Commission ?? 0).ToString()) { });
                                slist.Add(datarow);
                                IsOCFirst = false;
                            }
                        }
                        else
                        {
                            datarow.ExcelRows.Add(new ExcelColumn(value: "") { });
                            datarow.ExcelRows.Add(new ExcelColumn(value: "") { });
                            datarow.ExcelRows.Add(new ExcelColumn(value: "") { });
                            slist.Add(datarow);
                        }
                    }
                }
                #endregion

                var byteData = ExcelTempLateHelper.ToExcelExtend(slist);

                return File(byteData, "application/octet-stream", ExcelName);
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, string.Format("GetFileFromWebApi_requestData: {0}", JsonHelper.Serialize(RequestParm)));
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }

        }


        /// <summary>
        /// 推荐分销订单后台分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDistributionOrdersPageListForRecommend()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Goods_Order_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Order_Extend>(parms.msg.ToString());

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            demodel.Recycled = 2;
            var list = orderModule.GetDistributionOrdersPageListForRecommend(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.OrderId,
                x.OrderNo,
                x.MerchantsNo,
                x.OrderSource,
                OrderSourceName = x.OrderSource.GetEnumName(),
                x.UserId,
                x.UserName,
                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.CoverImage,
                    y.CoverImagePath,
                    y.OrderType,
                    OrderTypeName = y.OrderType.GetEnumName(),
                    y.GoodsName,
                    SpecificationList = JsonConvert.DeserializeObject<List<string>>(y.Specification),
                    y.ProductCode,
                    y.Final_Price,
                    y.Number,
                    OrderIntroduction = new
                    {
                        Id = y.OrderIntroduction?.Id ?? 0,
                        UserName = y.OrderIntroduction?.UserName ?? "",
                        Name = y.OrderIntroduction?.Name ?? "",
                        Commission = y.OrderIntroduction?.Commission ?? 0,
                        CommissionState = y.OrderIntroduction?.CommissionState ?? 1,
                        y.OrderIntroduction?.Remark,
                    }
                }),
                x.Consignee,
                x.Mobile,
                x.ShoppingAddress,
                x.BuyerMessage,
                x.Remark,
                x.OrderStatus,
                OrderStatusName = x.OrderStatus.GetEnumName(),
                PaymentTime = x.PaymentTime.HasValue ? x.PaymentTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                DeliveryTime = x.DeliveryTime.HasValue ? x.DeliveryTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                ReceivingTime = x.ReceivingTime.HasValue ? x.ReceivingTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                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 GetDistributionOrdersExportEnumListForRecommend()
        {
            var list = EnumHelper.GetEnumList(typeof(DistributionOrdersExportForRecommendEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }

        /// <summary>
        /// 推荐分销订单Excel下载
        /// </summary>
        [HttpPost]
        public FileContentResult GetDistributionOrdersToExcelForRecommend()
        {
            var parms = RequestParm;
            RB_Goods_Order_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Order_Extend>(parms.msg.ToString());
            string ExcelName = "推荐返利订单" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            List<ExcelDataSource> slist = new List<ExcelDataSource>();
            if (demodel.ExcelEnumIds == null || !demodel.ExcelEnumIds.Any())
            {
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }
            var Enumlist = EnumHelper.GetEnumList(typeof(DistributionOrdersExportForRecommendEnum));
            ExcelDataSource header = new ExcelDataSource()
            {
                ExcelRows = new List<ExcelColumn>(30) {
                    new ExcelColumn(value: "序号") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER }
                }
            };
            foreach (var item in demodel.ExcelEnumIds)
            {
                var Name = Enumlist.Where(x => x.Value == item.ToString()).FirstOrDefault().Key ?? "";
                header.ExcelRows.Add(new ExcelColumn(value: Name) { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER });
            }

            slist.Add(header);

            try
            {
                demodel.TenantId = Convert.ToInt32(parms.uid);
                demodel.MallBaseId = parms.MallBaseId;
                var list = orderModule.GetDistributionOrdersPageListForRecommend(1, 10000, out long count, demodel);
                #region 组装数据
                int Num = 0;
                foreach (var item in list)
                {
                    foreach (var item2 in item.DetailList)
                    {
                        Num++;
                        ExcelDataSource datarow = new ExcelDataSource()
                        {
                            ExcelRows = new List<ExcelColumn>(30) {
                                new ExcelColumn(value:Num.ToString()){ },
                            },
                            ColumnHight = 30
                        };
                        foreach (var qitem in demodel.ExcelEnumIds)
                        {
                            switch (qitem)
                            {
                                case 1:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderSource.GetEnumName()) { }); break;
                                case 2:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderNo) { }); break;
                                case 3:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.MerchantsNo) { }); break;
                                case 4:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.UserName) { }); break;
                                case 5:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item2.GoodsName) { }); break;
                                case 6:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item2.Specification) { }); break;
                                case 7:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: (item2.Number ?? 0).ToString()) { }); break;
                                case 8:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item2.ProductCode) { }); break;
                                case 10:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.Consignee) { }); break;
                                case 11:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.Mobile) { }); break;
                                case 12:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.ShoppingAddress) { }); break;
                                case 13:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: (item2.Original_Price ?? 0).ToString()) { }); break;
                                case 14:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: (item2.Final_Price ?? 0).ToString()) { }); break;
                                case 16:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss")) { }); break;
                                case 17:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderStatus.GetEnumName()) { }); break;
                                case 18:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.PaymentWay.GetEnumName()) { }); break;
                                case 19:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderStatus > OrderStatusEnum.NonPayment ? "已付款" : "未付款") { }); break;
                                case 20:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.PaymentTime.HasValue ? item.PaymentTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "") { }); break;
                                case 21:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.Remark) { }); break;
                                case 22:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.BuyerMessage) { }); break;
                            }
                        }
                        if (item2.OrderIntroduction != null)
                        {
                            string UserName = $"昵称：{item2.OrderIntroduction.UserName}，姓名：{item2.OrderIntroduction.Name}，手机号：{item2.OrderIntroduction.Mobile}";
                            datarow.ExcelRows.Add(new ExcelColumn(value: UserName) { });
                            datarow.ExcelRows.Add(new ExcelColumn(value: (item2.OrderIntroduction.Commission ?? 0).ToString()) { });
                            slist.Add(datarow);
                        }
                        else
                        {
                            datarow.ExcelRows.Add(new ExcelColumn(value: "") { });
                            datarow.ExcelRows.Add(new ExcelColumn(value: "") { });
                            slist.Add(datarow);
                        }
                    }
                }
                #endregion

                var byteData = ExcelTempLateHelper.ToExcelExtend(slist);

                return File(byteData, "application/octet-stream", ExcelName);
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, string.Format("GetFileFromWebApi_requestData: {0}", JsonHelper.Serialize(RequestParm)));
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }

        }

        /// <summary>
        /// 设置推荐分销
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetRecommendOrdersCommission()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int OrderDetailId = parms.GetInt("OrderDetailId", 0);
            decimal Commission = parms.GetDecimal("Commission");
            if (OrderDetailId <= 0)
            {
                return ApiResult.ParamIsNull("请传递订单明细id");
            }

            bool flag = orderModule.SetRecommendOrdersCommission(OrderDetailId, Commission, req.TenantId, req.MallBaseId, req.EmpId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }


        /// <summary>
        /// 微店订单后台分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSmallShopsOrdersPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Goods_Order_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Order_Extend>(parms.msg.ToString());

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            demodel.Recycled = 2;
            var list = orderModule.GetSmallShopsOrdersPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.OrderId,
                x.OrderNo,
                x.MerchantsNo,
                x.OrderSource,
                OrderSourceName = x.OrderSource.GetEnumName(),
                x.UserId,
                x.UserName,
                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.CoverImage,
                    y.CoverImagePath,
                    y.OrderType,
                    OrderTypeName = y.OrderType.GetEnumName(),
                    y.GoodsName,
                    SpecificationList = JsonConvert.DeserializeObject<List<string>>(y.Specification),
                    y.ProductCode,
                    y.Final_Price,
                    y.Number,
                    SmallShopsCommission = new
                    {
                        Id = y.SmallShopsCommission?.Id ?? 0,
                        UserName = y.SmallShopsCommission?.UserName ?? "",
                        Name = y.SmallShopsCommission?.Name ?? "",
                        Commission = y.SmallShopsCommission?.Commission ?? 0,
                        CommissionState = y.SmallShopsCommission?.CommissionState ?? 1,
                        y.SmallShopsCommission?.Remark,
                    }
                }),
                x.Consignee,
                x.Mobile,
                x.ShoppingAddress,
                x.BuyerMessage,
                x.Remark,
                x.OrderStatus,
                OrderStatusName = x.OrderStatus.GetEnumName(),
                PaymentTime = x.PaymentTime.HasValue ? x.PaymentTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                DeliveryTime = x.DeliveryTime.HasValue ? x.DeliveryTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                ReceivingTime = x.ReceivingTime.HasValue ? x.ReceivingTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                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 GetSmallShopsOrdersExportEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(SmallShopsOrdersExportEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }

        /// <summary>
        /// 微店订单Excel下载
        /// </summary>
        [HttpPost]
        public FileContentResult GetSmallShopsOrdersToExcel()
        {
            var parms = RequestParm;
            RB_Goods_Order_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Order_Extend>(parms.msg.ToString());
            string ExcelName = "微店返利订单" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            List<ExcelDataSource> slist = new List<ExcelDataSource>();
            if (demodel.ExcelEnumIds == null || !demodel.ExcelEnumIds.Any())
            {
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }
            var Enumlist = EnumHelper.GetEnumList(typeof(SmallShopsOrdersExportEnum));
            ExcelDataSource header = new ExcelDataSource()
            {
                ExcelRows = new List<ExcelColumn>(30) {
                    new ExcelColumn(value: "序号") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER }
                }
            };
            foreach (var item in demodel.ExcelEnumIds)
            {
                var Name = Enumlist.Where(x => x.Value == item.ToString()).FirstOrDefault().Key ?? "";
                header.ExcelRows.Add(new ExcelColumn(value: Name) { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER });
            }

            slist.Add(header);

            try
            {
                demodel.TenantId = Convert.ToInt32(parms.uid);
                demodel.MallBaseId = parms.MallBaseId;
                var list = orderModule.GetSmallShopsOrdersPageList(1, 10000, out long count, demodel);
                #region 组装数据
                int Num = 0;
                foreach (var item in list)
                {
                    foreach (var item2 in item.DetailList)
                    {
                        Num++;
                        ExcelDataSource datarow = new ExcelDataSource()
                        {
                            ExcelRows = new List<ExcelColumn>(30) {
                                new ExcelColumn(value:Num.ToString()){ },
                            },
                            ColumnHight = 30
                        };
                        foreach (var qitem in demodel.ExcelEnumIds)
                        {
                            switch (qitem)
                            {
                                case 1:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderSource.GetEnumName()) { }); break;
                                case 2:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderNo) { }); break;
                                case 3:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.MerchantsNo) { }); break;
                                case 4:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.UserName) { }); break;
                                case 5:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item2.GoodsName) { }); break;
                                case 6:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item2.Specification) { }); break;
                                case 7:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: (item2.Number ?? 0).ToString()) { }); break;
                                case 8:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item2.ProductCode) { }); break;
                                case 10:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.Consignee) { }); break;
                                case 11:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.Mobile) { }); break;
                                case 12:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.ShoppingAddress) { }); break;
                                case 13:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: (item2.Original_Price ?? 0).ToString()) { }); break;
                                case 14:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: (item2.Final_Price ?? 0).ToString()) { }); break;
                                case 16:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss")) { }); break;
                                case 17:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderStatus.GetEnumName()) { }); break;
                                case 18:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.PaymentWay.GetEnumName()) { }); break;
                                case 19:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderStatus > OrderStatusEnum.NonPayment ? "已付款" : "未付款") { }); break;
                                case 20:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.PaymentTime.HasValue ? item.PaymentTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "") { }); break;
                                case 21:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.Remark) { }); break;
                                case 22:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: item.BuyerMessage) { }); break;
                            }
                        }
                        if (item2.SmallShopsCommission != null)
                        {
                            datarow.ExcelRows.Add(new ExcelColumn(value: item2.SmallShopsCommission.Name) { });
                            datarow.ExcelRows.Add(new ExcelColumn(value: item2.SmallShopsCommission.UserName) { });
                            datarow.ExcelRows.Add(new ExcelColumn(value: (item2.SmallShopsCommission.Commission ?? 0).ToString()) { });
                            slist.Add(datarow);
                        }
                        else
                        {
                            datarow.ExcelRows.Add(new ExcelColumn(value: "") { });
                            datarow.ExcelRows.Add(new ExcelColumn(value: "") { });
                            datarow.ExcelRows.Add(new ExcelColumn(value: "") { });
                            slist.Add(datarow);
                        }
                    }
                }
                #endregion

                var byteData = ExcelTempLateHelper.ToExcelExtend(slist);

                return File(byteData, "application/octet-stream", ExcelName);
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, string.Format("GetFileFromWebApi_requestData: {0}", JsonHelper.Serialize(RequestParm)));
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }

        }

        /// <summary>
        /// 设置微店返佣金额
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetSmallShopsOrdersCommission()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int OrderDetailId = parms.GetInt("OrderDetailId", 0);
            decimal Commission = parms.GetDecimal("Commission");
            if (OrderDetailId <= 0)
            {
                return ApiResult.ParamIsNull("请传递订单明细id");
            }

            bool flag = orderModule.SetSmallShopsOrdersCommission(OrderDetailId, Commission, req.TenantId, req.MallBaseId, req.EmpId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        #endregion

        #region 推荐供应商

        /// <summary>
        /// 推荐分销订单佣金分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetRecommendOrdersCommissionPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Goods_OrderIntroduction_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_OrderIntroduction_Extend>(parms.msg.ToString());

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            if ((demodel.UserId ?? 0) <= 0)
            {
                return ApiResult.Failed("请选择用户id");
            }
            var list = orderModule.GetRecommendOrdersCommissionPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(y => new
            {
                y.OrderId,
                y.OrderNo,
                y.Id,
                y.CoverImage,
                y.GoodsName,
                SpecificationList = JsonConvert.DeserializeObject<List<string>>(y.Specification),
                y.ProductCode,
                y.Final_Price,
                y.Number,
                OrderIntroduction = new
                {
                    IntroductionId = y.OrderIntroduction?.Id ?? 0,
                    UserName = y.OrderIntroduction?.UserName ?? "",
                    Name = y.OrderIntroduction?.Name ?? "",
                    Commission = y.OrderIntroduction?.Commission ?? 0,
                    CommissionState = y.OrderIntroduction?.CommissionState ?? 1,
                }
            });
            return ApiResult.Success("", pagelist);
        }

        #endregion

        #region 售后订单

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

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = orderModule.GetGoodsOrderAfterPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.ReOrderId,
                x.ReOrderNo,
                x.UserId,
                x.UserName,
                OrderModel = new
                {
                    x.OrderModel.OrderId,
                    x.OrderModel.OrderNo,
                    x.OrderModel.OrderSource,
                    OrderSourceName = x.OrderModel.OrderSource.GetEnumName(),
                    x.OrderModel.Consignee,
                    x.OrderModel.Mobile,
                    x.OrderModel.Province,
                    x.OrderModel.City,
                    x.OrderModel.District,
                    x.OrderModel.DistrictAddress,
                    x.OrderModel.ShoppingAddress
                },
                OrderDetailModel = new
                {
                    x.OrderDetailModel.Id,
                    x.OrderDetailModel.GoodsName,
                    x.OrderDetailModel.GoodsId,
                    x.OrderDetailModel.CoverImagePath,
                    x.OrderDetailModel.ProductCode,
                    SpecificationList = JsonConvert.DeserializeObject<List<string>>(x.OrderDetailModel.Specification),
                },
                x.Type,
                x.ReNumber,
                x.Remark,
                x.Income,
                x.Refund,
                x.RefundActual,
                VoucherList = string.IsNullOrEmpty(x.Voucher) ? new List<string>() : JsonConvert.DeserializeObject<List<string>>(x.Voucher),
                x.ReOrderStatus,
                ReOrderStatusName = x.ReOrderStatus.GetEnumName(),
                x.ReRemark,
                x.FinanceId,
                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 GetOrderAfterSaleExportEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(OrderAfterSaleExportEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }

        /// <summary>
        /// 订单售后下载
        /// </summary>
        [HttpPost]
        public FileContentResult GetGoodsOrderAfterListToExcel()
        {
            var parms = RequestParm;
            RB_Goods_OrderAfterSale_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_OrderAfterSale_Extend>(parms.msg.ToString());
            string ExcelName = "订单售后" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            List<ExcelDataSource> slist = new List<ExcelDataSource>();
            if (demodel.ExcelEnumIds == null || !demodel.ExcelEnumIds.Any())
            {
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }
            var Enumlist = EnumHelper.GetEnumList(typeof(OrderListExportEnum));
            ExcelDataSource header = new ExcelDataSource()
            {
                ExcelRows = new List<ExcelColumn>(30) {
                    new ExcelColumn(value: "序号") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER }
                }
            };
            foreach (var item in demodel.ExcelEnumIds)
            {
                var Name = Enumlist.Where(x => x.Value == item.ToString()).FirstOrDefault().Key ?? "";
                header.ExcelRows.Add(new ExcelColumn(value: Name) { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER });
            }

            slist.Add(header);

            try
            {
                demodel.TenantId = Convert.ToInt32(parms.uid);
                demodel.MallBaseId = parms.MallBaseId;
                var list = orderModule.GetGoodsOrderAfterPageList(1, 10000, out long count, demodel);
                #region 组装数据
                int Num = 0;
                foreach (var item in list)
                {
                    Num++;
                    ExcelDataSource datarow = new ExcelDataSource()
                    {
                        ExcelRows = new List<ExcelColumn>(30) {
                            new ExcelColumn(value:Num.ToString()){ },
                        }
                    };
                    List<string> arr = JsonConvert.DeserializeObject<List<string>>(item.OrderDetailModel.Specification);
                    string Specification = string.Join("，", arr);
                    foreach (var qitem in demodel.ExcelEnumIds)
                    {
                        switch (qitem)
                        {
                            case 1:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderModel.OrderSource.GetEnumName()) { }); break;
                            case 2:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.ReOrderNo) { }); break;
                            case 4:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.UserName) { }); break;
                            case 5:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderDetailModel.GoodsName) { }); break;
                            case 6:
                                datarow.ExcelRows.Add(new ExcelColumn(value: Specification) { }); break;
                            case 7:
                                datarow.ExcelRows.Add(new ExcelColumn(value: (item.ReNumber ?? 0).ToString()) { }); break;
                            case 8:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderDetailModel.ProductCode) { }); break;
                            case 10:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderModel.Consignee) { }); break;
                            case 11:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderModel.Mobile) { }); break;
                            case 12:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderModel.DistrictAddress + " " + item.OrderModel.ShoppingAddress) { }); break;
                            case 13:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.ReRemark ?? "") { }); break;
                            case 14:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.Type == 1 ? "退货退款" : "换货") { }); break;
                            case 15:
                                datarow.ExcelRows.Add(new ExcelColumn(value: (item.Refund ?? 0).ToString()) { }); break;
                            case 16:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.Remark) { }); break;
                            case 17:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss")) { }); break;
                            case 18:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.ReOrderStatus.GetEnumName()) { }); break;
                            case 19:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.ReExpressName) { }); break;
                            case 20:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.ReExpressNumber) { }); break;

                        }
                    }
                    slist.Add(datarow);
                }
                #endregion

                var byteData = ExcelTempLateHelper.ToExcelExtend(slist);

                return File(byteData, "application/octet-stream", ExcelName);
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, string.Format("GetFileFromWebApi_requestData: {0}", JsonHelper.Serialize(RequestParm)));
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }

        }

        /// <summary>
        /// 获取订单售后查询枚举
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAfterSaleSelectStatusEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(AfterSaleSelectStatusEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }

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

            return orderModule.GetOrderAfterSaleInfo(ReOrderId, req.TenantId, req.MallBaseId);
        }

        /// <summary>
        /// 订单售后审核
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetOrderAfterSaleAudit()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int ReOrderId = parms.GetInt("ReOrderId", 0);
            int Type = parms.GetInt("Type", 1);//1 审核通过  2拒绝

            int DeliveryId = parms.GetInt("DeliveryId", 0);
            if (ReOrderId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            if (Type == 1)
            {
                if (DeliveryId <= 0)
                {
                    return ApiResult.ParamIsNull("请选择退货地址");
                }
            }

            return orderModule.SetOrderAfterSaleAudit(ReOrderId, Type, DeliveryId, req.TenantId, req.MallBaseId);
        }

        /// <summary>
        /// 订单售后收货(退货退款)
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetOrderReceivingForReturnsAndRefunds()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int ReOrderId = parms.GetInt("ReOrderId", 0);
            if (ReOrderId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            return orderModule.SetOrderReceivingForReturnsAndRefunds(ReOrderId, req.TenantId, req.MallBaseId);
        }

        /// <summary>
        /// 订单售后退款
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetOrderAfterSaleForRefunds()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int ReOrderId = parms.GetInt("ReOrderId", 0);
            decimal Refund = parms.GetDecimal("Refund");
            if (ReOrderId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            if (Refund < 0)
            {
                return ApiResult.ParamIsNull("请传递金额");
            }
            var ReModel = orderModule.GetOrderAfterSaleEntity(ReOrderId);
            if (ReModel == null)
            {
                return ApiResult.Failed("未查询到售后订单信息");
            }
            if (ReModel == null)
            {
                return ApiResult.Failed("售后订单不存在");
            }
            if (ReModel.ReOrderStatus != OrderAfterSaleStatusEnum.RefundedBySeller)
            {
                return ApiResult.Failed("状态不正确");
            }
            if (ReModel.Refund < Refund)
            {
                return ApiResult.Failed("退款金额不能大于" + ReModel.Refund);
            }
            var orderModel = orderModule.GetOrderInfo(ReModel.OrderId ?? 0);
            if (orderModel == null)
            {
                return ApiResult.Failed("未查询到订单信息");
            }

            var omodel = orderModule.GetOrderInfo(ReModel.OrderId ?? 0);
            int IsNormalServer = Convert.ToInt32(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("IsNormalServer").Value);
            if (IsNormalServer == 1 && omodel.OrderSource != UserSourceEnum.ERP && Refund > 0)
            {
                //获取小程序信息
                var mallModel = orderModule.GetMiniProgramExtend(req.MallBaseId);
                int RefundNum = orderModule.GetOrderRefundOnlineTradeNum(ReModel.OrderId ?? 0, req.TenantId, req.MallBaseId);
                string RefundOrderNo = orderModel.OrderNo + (RefundNum + 1);
                var pram = new Common.Pay.WeChatPat.PayParam()
                {
                    TotalFee = Convert.ToInt32((orderModel.Income ?? 0) * 100),
                    RefundFee = Convert.ToInt32(Refund * 100),
                    OrderNumber = orderModel.MerchantsNo,
                    RefundNumber = RefundOrderNo
                };
                LogHelper.Write(JsonConvert.SerializeObject(pram));
                var Robj = new App_Code.PayUtil().Refund(pram, mallModel, _accessor);
                if (Robj.IsSuccess)
                {
                    var dic = ((Dictionary<string, string>)Robj.Data);
                    bool flag = orderModule.SetOrderAfterSaleForRefunds(omodel, ReOrderId, Refund, RefundOrderNo, req.TenantId, req.MallBaseId, Common.Enum.Goods.OrderPayTypeEnum.WeChatPay, dic["dPrice"], dic["sOrderNo"], dic["sTradeNo"], dic["refundid"]);
                    if (flag == false)
                    {
                        //日志记录
                        LogHelper.Write("售后订单：" + ReOrderId + ",金额：" + Refund + " 退款记录失败");
                    }

                    var detailModel = orderModule.GetOrderDetailInfo(ReModel.OrderDetialId ?? 0);


                    //2020-11-10 Add By:W  start
                    try
                    {
                        if (detailModel != null && detailModel.IsNoTax == 1)//有不可以开发票的商品 新增记录更新缓存
                        {
                            if (Refund > 0)
                            {
                                orderModule.AddInvoiceRecordDetail(new Model.Entity.Product.RB_Invoice_RecordDetail
                                {
                                    TenantId = detailModel.TenantId,
                                    MallBaseId = detailModel.MallBaseId,
                                    ID = 0,
                                    Type = 3,
                                    CreateDate = DateTime.Now,
                                    Name = detailModel.GoodsName,
                                    OrderId = detailModel.OrderId ?? 0,
                                    OrderDetailId = detailModel.Id,
                                    GoodsPrice = Refund,
                                    Unit_Price = 0,
                                    Number = 1,
                                    FreightMoney = 0
                                });
                                //获取缓存信息
                                TransactionPriceInfo transactionPriceInfo = CacheManager.User.UserReidsCache.GetTransactionPriceInfo(detailModel.MallBaseId);
                                if (transactionPriceInfo == null)
                                {
                                    transactionPriceInfo = new TransactionPriceInfo
                                    {
                                        TenantId = orderModel.TenantId,
                                        MallBaseId = orderModel.MallBaseId,
                                        TotalPrice = Refund * -1
                                    };
                                }
                                else
                                {
                                    transactionPriceInfo.TotalPrice -= Refund;
                                }
                                CacheManager.User.UserReidsCache.TransactionPriceSet(CacheKey.UserModuleCacheKeyConfig.Transaction_Price_ + detailModel.MallBaseId, transactionPriceInfo, Config.JwtExpirTime);
                            };
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.WriteInfo("不开发票商品记录或者缓存失败:" + ex.ToString());
                    }
                    //2020-11-10 Add By:W End




                    string goodsName = detailModel?.GoodsName ?? "";
                    if (goodsName.Length > 10)
                    {
                        goodsName = goodsName.Substring(0, 10);
                    }
                    var umodel = orderModule.GetMemberUserInfo(orderModel.UserId ?? 0);
                    if (goodsName != "" && umodel != null)
                    {
                        new MiniProgramMsgModule().SendOrderRefundMsg(orderModel.TenantId, orderModel.MallBaseId, umodel.OpenId, "已退款，请注意查收", orderModel.OrderNo, (Refund).ToString(), goodsName);
                    }
                    return ApiResult.Success("");
                }
                else
                {
                    LogHelper.Write(JsonConvert.SerializeObject(Robj));
                    return ApiResult.Failed();
                }
            }
            else if (IsNormalServer == 1 && omodel.OrderSource == UserSourceEnum.ERP)
            {
                bool refundflag = orderModule.SetMallOrderSalesTheWayRefund(omodel.OrderId, ReModel.FinanceId);
                if (refundflag)
                {
                    bool flag = orderModule.SetOrderAfterSaleForRefunds(omodel, ReOrderId, Refund, "", req.TenantId, req.MallBaseId, Common.Enum.Goods.OrderPayTypeEnum.WeChatPay, "", "", "", "");
                    if (flag)
                    {
                        return ApiResult.Success("");
                    }
                    else
                    {
                        return ApiResult.Failed();
                    }
                }
                else
                {
                    LogHelper.Write("调用erp退款接口失败");
                    return ApiResult.Failed();
                }
            }
            else
            {
                bool flag = orderModule.SetOrderAfterSaleForRefunds(omodel, ReOrderId, Refund, "", req.TenantId, req.MallBaseId, Common.Enum.Goods.OrderPayTypeEnum.WeChatPay, "", "", "", "");
                if (flag)
                {
                    return ApiResult.Success("");
                }
                else
                {
                    return ApiResult.Failed();
                }
            }
        }


        /// <summary>
        /// 后台处理用户发货
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetUserOrderAfterSaleSendGoods()
        {
            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();
            }

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


        /// <summary>
        /// 根据财务单据退款
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetOrderAfterSaleByFinance()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int ReOrderId = parms.GetInt("ReOrderId", 0);
            decimal Refund = parms.GetDecimal("Refund");
            if (ReOrderId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            if (Refund <= 0)
            {
                return ApiResult.ParamIsNull("请传递金额");
            }
            var ReModel = orderModule.GetOrderAfterSaleEntity(ReOrderId);
            if (ReModel == null)
            {
                return ApiResult.Failed("未查询到售后订单信息");
            }
            if (ReModel == null)
            {
                return ApiResult.Failed("售后订单不存在");
            }
            if (ReModel.ReOrderStatus != OrderAfterSaleStatusEnum.RefundedBySeller)
            {
                return ApiResult.Failed("状态不正确");
            }
            if (ReModel.Refund < Refund)
            {
                return ApiResult.Failed("退款金额不能大于" + ReModel.Refund);
            }
            var orderModel = orderModule.GetOrderInfo(ReModel.OrderId ?? 0);
            if (orderModel == null)
            {
                return ApiResult.Failed("未查询到订单信息");
            }
            int IsNormalServer = Convert.ToInt32(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("IsNormalServer").Value);
            if (IsNormalServer == 1)
            {
                //获取小程序信息
                var mallModel = orderModule.GetMiniProgramExtend(req.MallBaseId);
                int RefundNum = orderModule.GetOrderRefundOnlineTradeNum(ReModel.OrderId ?? 0, req.TenantId, req.MallBaseId);
                string RefundOrderNo = orderModel.OrderNo + (RefundNum + 1);
                var pram = new Common.Pay.WeChatPat.PayParam()
                {
                    TotalFee = Convert.ToInt32((orderModel.Income ?? 0) * 100),
                    RefundFee = Convert.ToInt32(Refund * 100),
                    OrderNumber = orderModel.MerchantsNo,
                    RefundNumber = RefundOrderNo
                };
                var Robj = new App_Code.PayUtil().Refund(pram, mallModel, _accessor);
                if (Robj.IsSuccess)
                {
                    //获取商品信息
                    var orderGoodsList = orderModule.GetOrderDetailList(new RB_Goods_OrderDetail_Extend { TenantId = orderModel.TenantId, MallBaseId = orderModel.MallBaseId, OrderId = orderModel.OrderId });
                    //2020-11-10 Add By:W  start
                    if (orderModel.OrderClassify == 0)
                    {
                        try
                        {
                            if (orderGoodsList != null && orderGoodsList.Any(x => x.IsNoTax == 1))//有不可以开发票的商品 新增记录更新缓存
                            {
                                if (Refund > 0)
                                {
                                    foreach (var item in orderGoodsList.Where(x => x.IsNoTax == 1))
                                    {
                                        orderModule.AddInvoiceRecordDetail(new Model.Entity.Product.RB_Invoice_RecordDetail
                                        {
                                            TenantId = item.TenantId,
                                            MallBaseId = item.MallBaseId,
                                            ID = 0,
                                            Type = 3,
                                            CreateDate = DateTime.Now,
                                            Name = item.GoodsName,
                                            OrderId = item.OrderId ?? 0,
                                            OrderDetailId = item.Id,
                                            GoodsPrice = Refund,
                                            Unit_Price = 0,
                                            Number = 1,
                                            FreightMoney = 0
                                        });
                                    }
                                    //获取缓存信息
                                    TransactionPriceInfo transactionPriceInfo = CacheManager.User.UserReidsCache.GetTransactionPriceInfo(orderModel.MallBaseId);
                                    if (transactionPriceInfo == null)
                                    {
                                        transactionPriceInfo = new TransactionPriceInfo
                                        {
                                            TenantId = orderModel.TenantId,
                                            MallBaseId = orderModel.MallBaseId,
                                            TotalPrice = Refund * -1
                                        };
                                    }
                                    else
                                    {
                                        transactionPriceInfo.TotalPrice -= Refund;
                                    }
                                    CacheManager.User.UserReidsCache.TransactionPriceSet(CacheKey.UserModuleCacheKeyConfig.Transaction_Price_ + orderModel.MallBaseId, transactionPriceInfo, Config.JwtExpirTime);
                                };
                            }
                        }
                        catch (Exception ex)
                        {
                            LogHelper.WriteInfo("不开发票商品记录或者缓存失败:" + ex.ToString());
                        }
                    }
                    //2020-11-10 Add By:W End

                    string goodsName = orderGoodsList.FirstOrDefault().GoodsName;
                    if (orderGoodsList.Count > 1)
                    {
                        if (goodsName.Length > 12)
                        {
                            goodsName = goodsName.Substring(0, 11) + "..";
                        }
                        goodsName += "等" + orderGoodsList.Count + "件商品";
                    }
                    else
                    {
                        if (goodsName.Length > 18)
                        {
                            goodsName = goodsName.Substring(0, 18) + "..";
                        }
                    }

                    //退款成功发送退款成功的订阅消息
                    //根据订单下单人获取openid
                    var userModel = orderModule.GetMemberUserInfo(orderModel.UserId.Value);
                    if (userModel != null)
                    {
                        miniProgramMsgModule.SendOrderRefundMsg(mallModel.TenantId.Value, mallModel.MallBaseId, userModel.OpenId, "已退款，请注意查收", orderModel.OrderNo, (orderModel.Income ?? 0).ToString(), goodsName);
                    }
                    var dic = ((Dictionary<string, string>)Robj.Data);
                    bool flag = orderModule.SetOrderAfterSaleForRefunds(orderModel, ReOrderId, Refund, RefundOrderNo, req.TenantId, req.MallBaseId, Common.Enum.Goods.OrderPayTypeEnum.WeChatPay, dic["dPrice"], dic["sOrderNo"], dic["sTradeNo"], dic["refundid"]);
                    if (flag == false)
                    {
                        //日志记录
                        LogHelper.Write("售后订单：" + ReOrderId + ",金额：" + Refund + " 退款记录失败");
                    }
                    return ApiResult.Success("");
                }
                return ApiResult.Failed();
            }
            else
            {
                bool flag = orderModule.SetOrderAfterSaleForRefunds(orderModel, ReOrderId, Refund, "", req.TenantId, req.MallBaseId, Common.Enum.Goods.OrderPayTypeEnum.WeChatPay, "", "", "", "");
                if (flag == false)
                {
                    //日志记录
                    return ApiResult.Failed();
                }
                return ApiResult.Success("");
            }
        }




        /// <summary>
        /// 售后订单发货
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetOrderAfterSaleSendGoods()
        {
            var req = RequestParm;
            RB_Goods_OrderExpress_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_OrderExpress_Extend>(req.msg.ToString());
            if ((demodel.AfterSaleOrderId ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请传递订单id");
            }
            if (demodel.Type == 1)
            {
                if (!demodel.ExpressId.HasValue || demodel.ExpressId <= 0)
                {
                    return ApiResult.ParamIsNull("请选择快递公司");
                }
                if (string.IsNullOrEmpty(demodel.ExpressNumber))
                {
                    return ApiResult.ParamIsNull("请输入快递单号");
                }
            }
            else
            {
                if (string.IsNullOrEmpty(demodel.Remark))
                {
                    return ApiResult.ParamIsNull("请输入物流内容");
                }
            }

            demodel.TenantId = req.TenantId;
            demodel.MallBaseId = req.MallBaseId;
            demodel.CreateDate = DateTime.Now;
            demodel.UpdateDate = DateTime.Now;

            return orderModule.SetOrderAfterSaleSendGoods(demodel);
        }


        #endregion

        #region 订单评论

        /// <summary>
        /// 获取评论模板分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetGoodsCommentTemplatePageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Goods_CommentTemplate_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_CommentTemplate_Extend>(parms.msg.ToString());

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = orderModule.GetGoodsCommentTemplatePageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.Name,
                x.Content,
                x.CommentGrade,
                CommentGradeName = x.CommentGrade.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 SetGoodsCommentTemplateInfo()
        {
            var req = RequestParm;
            RB_Goods_CommentTemplate_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_CommentTemplate_Extend>(req.msg.ToString());
            if (string.IsNullOrEmpty(demodel.Name))
            {
                return ApiResult.ParamIsNull("请输入模板名称");
            }
            if (string.IsNullOrEmpty(demodel.Content))
            {
                return ApiResult.ParamIsNull("请输入模板内容");
            }
            if (!demodel.CommentGrade.HasValue)
            {
                return ApiResult.ParamIsNull("请选择模板类型");
            }

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

        /// <summary>
        /// 删除评论模板
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelGoodsCommentTemplateInfo()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int TemplateId = parms.GetInt("TemplateId", 0);
            if (TemplateId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            bool flag = orderModule.DelGoodsCommentTemplateInfo(TemplateId, req.TenantId, req.MallBaseId);
            if (flag) { return ApiResult.Success(); } else { return ApiResult.Failed(); }
        }

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

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = orderModule.GetGoodsCommentPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.UserId,
                x.UserName,
                x.GoodsId,
                x.GoodsName,
                x.CoverImage,
                x.CommentScore,
                x.CommentGrade,
                CommentGradeName = x.CommentGrade.GetEnumName(),
                x.CommentImgList,
                x.Content,
                x.Reply,
                x.Is_Top,
                x.Is_Show,
                x.Is_Anonymity,
                x.PlatformSource,
                x.TenantId,
                x.MallBaseId,
                x.OrderDetailId,
                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 SetGoodsCommentInfo()
        {
            var req = RequestParm;
            RB_Goods_Comment_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Comment_Extend>(req.msg.ToString());
            if (string.IsNullOrEmpty(demodel.UserName))
            {
                return ApiResult.ParamIsNull("请输入用户名称");
            }
            if (!demodel.CreateDate.HasValue)
            {
                return ApiResult.ParamIsNull("请输入评论时间");
            }
            if ((demodel.GoodsId ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请选择商品");
            }
            if (string.IsNullOrEmpty(demodel.Content))
            {
                return ApiResult.ParamIsNull("请输入评价内容");
            }
            if (!demodel.CommentGrade.HasValue)
            {
                return ApiResult.ParamIsNull("请选择评分");
            }
            demodel.CommentScore ??= 5;
            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 ??= 1;
            demodel.Is_Anonymity ??= 2;
            demodel.UserId ??= 0;
            demodel.Reply ??= "";

            demodel.TenantId = req.TenantId;
            demodel.MallBaseId = req.MallBaseId;
            demodel.Status = 0;
            demodel.UpdateDate = DateTime.Now;

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

        /// <summary>
        /// 批量操作
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetGoodsCommentBatch()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            string CommentIds = parms.GetStringValue("CommentIds");
            int Type = parms.GetInt("Type", 1);//1批量回复   2批量隐藏  3批量显示  4批量置顶  5取消置顶  6批量删除
            string Content = parms.GetStringValue("Content");
            if (string.IsNullOrEmpty(CommentIds))
            {
                return ApiResult.ParamIsNull();
            }
            if (Type == 1)
            {
                if (string.IsNullOrEmpty(Content))
                {
                    return ApiResult.ParamIsNull("回复内容不能为空");
                }
            }

            bool flag = orderModule.SetGoodsCommentBatch(CommentIds, Type, Content, req.TenantId, req.MallBaseId);
            if (flag) { return ApiResult.Success(); } else { return ApiResult.Failed(); }
        }


        /// <summary>
        /// 批量操作
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetCommentBatchByOrderDetailId()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            string orderDetailIds = parms.GetStringValue("OrderDetailIds");
            int Type = parms.GetInt("Type", 1);//1批量回复   2批量隐藏  3批量显示  4批量置顶  5取消置顶  6批量删除
            string Content = parms.GetStringValue("Content");
            if (string.IsNullOrEmpty(orderDetailIds))
            {
                return ApiResult.ParamIsNull();
            }
            if (Type == 1)
            {
                if (string.IsNullOrEmpty(Content))
                {
                    return ApiResult.ParamIsNull("回复内容不能为空");
                }
            }

            bool flag = orderModule.SetCommentBatchByOrderDetailId(orderDetailIds, Type, Content, req.TenantId, req.MallBaseId);
            if (flag) { return ApiResult.Success(); } else { return ApiResult.Failed(); }
        }

        /// <summary>
        /// 获取商品评价类型枚举
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetGoodsCommentTypeEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(GoodsCommentTypeEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }
        #endregion

        #region 订单批量发货

        /// <summary>
        /// 批量发货
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetOrderBatchSendGoods()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            string FilePath = parms.GetStringValue("FilePath");
            int ExpressId = parms.GetInt("ExpressId", 0);

            if (string.IsNullOrEmpty(FilePath))
            {
                return ApiResult.ParamIsNull("文件路径不存在");
            }
            if (ExpressId <= 0)
            {
                return ApiResult.ParamIsNull("请选择快递id");
            }

            string msg = orderModule.SetOrderBatchSendGoods(FilePath, ExpressId, req.TenantId, req.MallBaseId);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        #endregion

        #region 赞羊订单导入

        /// <summary>
        /// 赞羊订单导入
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetGoodsOrderBatchImport()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            string FilePath = parms.GetStringValue("FilePath");

            if (string.IsNullOrEmpty(FilePath))
            {
                return ApiResult.ParamIsNull("文件路径不存在");
            }

            string msg = orderModule.SetGoodsOrderBatchImport(FilePath, req.TenantId, req.MallBaseId);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        #endregion

        #region 微店

        /// <summary>
        /// 分销订单后台分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetOldSmallShopOrdersPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            JObject parameters = JObject.Parse(parms.msg.ToString());
            RB_Goods_Order_Extend demodel = new RB_Goods_Order_Extend()
            {
                OrderSource = (UserSourceEnum)parameters.GetInt("OrderSource"),
                OrderType = parameters.GetInt("OrderType"),
                DeliveryMethod = (OrderDeliveryMethodEnum)parameters.GetInt("DeliveryMethod"),
                OrderId = parameters.GetInt("OrderId"),
                StartTime = parameters.GetStringValue("StartTime"),
                EndTime = parameters.GetStringValue("EndTime"),
                OrderStatus = (OrderStatusEnum)parameters.GetInt("OrderStatus"),
                OrderNo = parameters.GetStringValue("OrderNo"),
                UserName = parameters.GetStringValue("UserName"),
                UserId = parameters.GetInt("UserId"),
                GoodsName = parameters.GetStringValue("GoodsName"),
                DistributionUserId = parameters.GetInt("DistributionUserId")
            };
            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            demodel.Recycled = 2;
            var list = orderModule.GetSmallShopOrdersPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.OrderId,
                x.OrderNo,
                x.MerchantsNo,
                x.OrderSource,
                OrderSourceName = x.OrderSource.GetEnumName(),
                x.UserId,
                x.UserName,
                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.CoverImage,
                    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.Consignee,
                x.Mobile,
                x.ShoppingAddress,
                x.BuyerMessage,
                x.Remark,
                x.OrderStatus,
                OrderStatusName = x.OrderStatus.GetEnumName(),
                PaymentTime = x.PaymentTime.HasValue ? x.PaymentTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                DeliveryTime = x.DeliveryTime.HasValue ? x.DeliveryTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                ReceivingTime = x.ReceivingTime.HasValue ? x.ReceivingTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                x.IsOrderCommission,
                OrderCommissionList = x.SmallShopsCommissionOrderList.Select(z => new
                {
                    z.Id,
                    z.UserId,
                    z.UserName,
                    z.Mobile,
                    z.Name,
                    z.Commission,
                    z.CommissionState
                }),
                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 GetInvoiceOnlineTradePageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            RB_Invoice_Online_Trade_Extend demodel = JsonConvert.DeserializeObject<RB_Invoice_Online_Trade_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = orderModule.GetInvoiceOnlineTradePageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.Out_Trade_No,
                x.CreateByName,
                x.FinanceId,
                x.Money,
                Pay_DateStr = x.Pay_Date.HasValue ? x.Pay_Date.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                x.UserName,
                x.Transaction_Id,
                x.Pay_Result
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 获取提现信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetInvoiceOnlineTradeInfo()
        {
            var parms = RequestParm;

            TransactionPriceInfo demodel = JsonConvert.DeserializeObject<TransactionPriceInfo>(RequestParm.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            TransactionPriceInfo transactionPriceInfo = CacheManager.User.UserReidsCache.GetTransactionPriceInfo(demodel.MallBaseId);
            if (transactionPriceInfo == null)
            {
                transactionPriceInfo = new TransactionPriceInfo();
            }
            return ApiResult.Success("", transactionPriceInfo);
        }



        /// <summary>
        /// 获取提现信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetInvoiceOnlineTrade()
        {
            var parms = RequestParm;
            RB_Invoice_Online_Trade_Extend demodel = JsonConvert.DeserializeObject<RB_Invoice_Online_Trade_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            // demodel.CreateBy = UserInfo.EmpId;
            if (demodel.CreateBy == 0)
            {
                return ApiResult.Failed("操作人不能是管理员，请登录员工账号");
            }
            if (demodel.User_Id == 0)
            {
                return ApiResult.Failed("提现人id不能等于零");
            }
            //查找提现人的信息是否满足当前情况
            var member = orderModule.GetMemberUserInfo(demodel.User_Id);
            if (member == null)
            {
                return ApiResult.Failed("提现人不存在");
            }
            if (member.IsSettlement != 1)
            {
                return ApiResult.Failed("提现人不是结算人");
            }
            if (!demodel.Money.HasValue)
            {
                return ApiResult.Failed("请输入提现金额");
            }
            if (demodel.Money.HasValue && demodel.Money.Value <= 0)
            {
                return ApiResult.Failed("提现金额必须大于0");
            }
            if (demodel.Money.HasValue && demodel.Money.Value > 5000)
            {
                return ApiResult.Failed("提现金额必须小于等于五千");
            }
            //查询提现人今日提现金额
            var oldList = orderModule.GetToDayInvoiceOnlineTradeList(new RB_Invoice_Online_Trade_Extend { TenantId = UserInfo.TenantId, MallBaseId = parms.MallBaseId, User_Id = demodel.User_Id, Pay_Date = System.DateTime.Now });

            if (oldList != null && oldList.Any())
            {
                decimal allPrice = oldList.Sum(x => (x.Money ?? 0));
                if ((allPrice + (demodel.Money ?? 0)) > 5000)
                {
                    return ApiResult.Failed("今日最多只能提现" + (50000 - allPrice).ToString());
                }
            }
            //获取缓存信息
            TransactionPriceInfo transactionPriceInfo = CacheManager.User.UserReidsCache.GetTransactionPriceInfo(demodel.MallBaseId);
            if (transactionPriceInfo == null)
            {
                return ApiResult.Failed("暂无可提现金额");
            }
            if (transactionPriceInfo.TotalPrice < (demodel.Money ?? 0))
            {
                return ApiResult.Failed("提现金额不能大于总金额：" + transactionPriceInfo.TotalPrice.ToString());
            }
            Random R = new Random();
            int Rstr = R.Next(111, 999);
            demodel.Out_Trade_No = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Rstr;
            demodel.PayType = "JSAPI";
            demodel.PayWay = OrderPayTypeEnum.WeChatPay;
            demodel.CreateDate = System.DateTime.Now;
            demodel.Pay_Result = -1;
            //新增提现记录
            int id = orderModule.AddInvoiceOnlineTrade(demodel);
            var mallModel = orderModule.GetMiniProgramExtend(demodel.MallBaseId);
            var Robj = App_Code.PayUtil.GetTransfersOrder_V2(demodel.Out_Trade_No, demodel.Money ?? 0, demodel.User_Id.ToString(), member.OpenId, mallModel, _accessor);
            if (Robj.IsSuccess)
            {
                //获取缓存信息
                transactionPriceInfo = CacheManager.User.UserReidsCache.GetTransactionPriceInfo(demodel.MallBaseId);
                transactionPriceInfo.TotalPrice -= (demodel.Money ?? 0);
                CacheManager.User.UserReidsCache.TransactionPriceSet(CacheKey.UserModuleCacheKeyConfig.Transaction_Price_ + demodel.MallBaseId, transactionPriceInfo, Config.JwtExpirTime);
                var dic = ((Dictionary<string, string>)Robj.Data);
                string Transaction_Id = dic["payment_no"];
                DateTime PayDate = DateTime.ParseExact(dic["payment_time"], "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.CurrentCulture);//转换时间// Convert.ToDateTime(dic["PayDate"]);
                orderModule.UpdateInvoiceOnlineTrade(new RB_Invoice_Online_Trade_Extend { Id = id, Pay_Date = PayDate, Pay_Result = 0, Transaction_Id = Transaction_Id });
            }
            else
            {
                return ApiResult.Failed(Robj.Message);
            }
            return ApiResult.Success("");
        }



        #endregion


        #region 订单商品成本修改记录
        /// <summary>
        /// 获取提现信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetOrderGoodsLogPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            RB_OrderGoods_Log_Extend demodel = JsonConvert.DeserializeObject<RB_OrderGoods_Log_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = orderModule.GetOrderGoodsLogPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.NewCostPrice,
                x.OldCostPrice,
                EmpName = x.EmpName ??= "",
                x.OrderNo,
                GoodsName = x.GoodsName ??= "",
                x.Type,
                CreateDateStr = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
            });
            return ApiResult.Success("", pagelist);
        }
        #endregion 
    }
}