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;

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 = new OrderModule();
        private readonly MiniProgramMsgModule miniProgramMsgModule = new MiniProgramMsgModule();

        #region 订单列表

        /// <summary>
        /// 商品订单后台分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetGoodsOrderPageList()
        {
            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.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.CouponMoney,
                x.PaymentWay,
                PaymentWayName = x.PaymentWay.GetEnumName(),
                DetailList = x.DetailList.Select(y => new
                {
                    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
                }),
                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,
                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;
                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()){ },
                        }
                        };
                        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 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: (item.PreferPrice ?? 0).ToString()) { }); break;
                                case 14:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: (item.Income ?? 0).ToString()) { }); break;
                                case 15:
                                    datarow.ExcelRows.Add(new ExcelColumn(value: (item.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);
            }

        }

        /// <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;

            string msg = orderModule.SetOrderSendGoods(demodel);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return 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");
            string Address = parms.GetStringValue("Address");
            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, Address, req.TenantId, req.MallBaseId);
            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)
            {
                //获取小程序信息
                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);
                    }

                    bool flag = orderModule.SetOrderForcedToCancel(omodel, RefundOrderNo, req.TenantId, req.MallBaseId);
                    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);
                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)
            {
                //获取小程序信息
                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);
                    }
                    bool flag = orderModule.SetOrderApplyForCancelAudit(omodel, Type, Remark, RefundOrderNo, req.TenantId, req.MallBaseId);
                    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);
                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 SetOrderFreightCostMoney()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int OrderId = parms.GetInt("Id", 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, 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);
            decimal costMoney = parms.GetDecimal("CostMoney");
            if (OrderId <= 0)
            {
                return ApiResult.ParamIsNull("请传递订单明细id");
            }
            if (costMoney < 0)
            {
                return ApiResult.ParamIsNull("请传递商品成本");
            }
            bool flag = orderModule.SetOrderCostMoney(OrderId, costMoney, req.TenantId, req.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }


        #endregion

        #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());
            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.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.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.OrderCommissionList.Select(z => new
                {
                    z.Id,
                    z.Grade,
                    z.GradeDescription,
                    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);
        }

        /// <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()){ },
                        }
                        };
                        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);
            }

        }

        #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.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("未查询到订单信息");
            }
            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(Refund * 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)
                {
                    bool flag = orderModule.SetOrderAfterSaleForRefunds(ReOrderId, Refund, RefundOrderNo, req.TenantId, req.MallBaseId);
                    if (flag == false)
                    {
                        //日志记录
                        LogHelper.Write("售后订单：" + ReOrderId + ",金额：" + Refund + " 退款记录失败");
                    }

                    var detailModel = orderModule.GetOrderDetailInfo(ReModel.OrderDetialId ?? 0);
                    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
            {
                bool flag = orderModule.SetOrderAfterSaleForRefunds(ReOrderId, Refund, "", req.TenantId, req.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(Refund * 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 });
                    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);
                    }
                    bool flag = orderModule.SetOrderAfterSaleForRefunds(ReOrderId, Refund, RefundOrderNo, req.TenantId, req.MallBaseId);
                    if (flag == false)
                    {
                        //日志记录
                        LogHelper.Write("售后订单：" + ReOrderId + ",金额：" + Refund + " 退款记录失败");
                    }
                    return ApiResult.Success("");
                }
                return ApiResult.Failed();
            }
            else
            {
                bool flag = orderModule.SetOrderAfterSaleForRefunds(ReOrderId, Refund, "", req.TenantId, req.MallBaseId);
                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.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,
                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.CommentImage = "";
            if (demodel.CommentImgList != null && demodel.CommentImgList.Any())
            {
                demodel.CommentImage = JsonConvert.SerializeObject(demodel.CommentImgList);
            }
            demodel.UserPhoto ??= 0;
            demodel.Is_Top ??= 2;
            demodel.Is_Show ??= 2;
            demodel.Is_Anonymity ??= 2;
            demodel.UserId ??= 0;
            demodel.Reply ??= "";

            demodel.TenantId = 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 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
    }
}