using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Dnc.Api.Throttle;
using Google.Protobuf.WellKnownTypes;
using Mall.Common;
using Mall.Common.API;
using Mall.Common.Plugin;
using Mall.Model.Extend.AppletWeChat;
using Mall.Model.Extend.Product;
using Mall.Model.Extend.User;
using Mall.Model.Query;
using Mall.Module.MarketingCenter;
using Mall.Module.Product;
using Mall.Module.User;
using Mall.WebApi.Filter;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Mall.WebApi.Controllers.AppletWeChat
{

    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class LiveHouseController : ControllerBase
    {
        public readonly StatisticsModule statisticsModule = new StatisticsModule();
        private readonly MiniProgramModule appletWeChatModule = new MiniProgramModule();

        private readonly SupplierModule supplierModule = new SupplierModule();

        private readonly ProductModule productModule = new ProductModule();


        #region 直播房间信息
        [HttpPost]
        [AllowAnonymous] 
        [RateValve(Policy = Policy.Ip, Limit = 20, Duration = 60)]
        public ApiResult GetLiveHouseList(object requestMsg)
        {
            var requestParm = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(requestParm.msg.ToString());
            RB_Live_HouseExtension_Extend demodel = JsonConvert.DeserializeObject<RB_Live_HouseExtension_Extend>(requestParm.msg.ToString());
            demodel.TenantId = requestParm.TenantId;
            demodel.MallBaseId = requestParm.MallBaseId;
            var list = appletWeChatModule.GetLiveHouseExtensionPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.ID,
                x.roomid,
                x.name,
                x.anchor_img,
                x.anchor_name,
                x.cover_img,
                x.live_status,
                x.HouseImgID,
                x.ExtensionImg,
                x.LiveQrCodePaddingLeft,
                x.LiveQrCodePaddingTop,
                x.LiveQrCodeSize,
                x.LiveQrCodeType,
                start_time = GetTime(x.start_time),
                end_time = GetTime(x.end_time),
            });
            return ApiResult.Success("", pagelist);
        }

        [HttpPost]
        [Obsolete]
        [AllowAnonymous] 
        [RateValve(Policy = Policy.Ip, Limit = 20, Duration = 60)]
        public ApiResult GetLiveListByLiveStatus(object requestMsg)
        {
            var requestParm = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            Model.Extend.AppletWeChat.RB_Live_HouseExtension_Extend demodel = JsonConvert.DeserializeObject<Model.Extend.AppletWeChat.RB_Live_HouseExtension_Extend>(requestParm.msg.ToString());
            demodel.TenantId = requestParm.TenantId;
            demodel.MallBaseId = requestParm.MallBaseId;
            demodel.live_status = "102";
            var list = appletWeChatModule.GetLiveHousePageList(demodel);
            var retult = list.Select(x => new
            {
                x.ID,
                x.roomid,
                x.name,
                x.anchor_img,
                x.anchor_name,
                x.cover_img,
                x.live_status,
                x.ExtensionImg,
                x.HouseImgID,
                x.LiveQrCodePaddingLeft,
                x.LiveQrCodePaddingTop,
                x.LiveQrCodeSize,
                x.LiveQrCodeType,
                start_time = GetTime(x.start_time),
                end_time = GetTime(x.end_time),
            });
            return ApiResult.Success("", retult);
        }


        /// <summary>
        /// 时间戳转为C#格式时间
        /// </summary>
        /// <param name="timeStamp">Unix时间戳格式</param>
        /// <returns>C#格式时间</returns>
        public static string GetTime(string timeStamp)
        {
            try
            {
                var start = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                var longTimeSpan = long.Parse(timeStamp + "0000000");
                return start.AddMilliseconds(longTimeSpan).AddHours(8).ToString("yyyy-MM-dd HH:mm:ss");
            }
            catch (Exception)
            {
                return "";
            }
        }


        /// <summary>  
        /// 将c# DateTime时间格式转换为Unix时间戳格式  
        /// </summary>  
        /// <param name="time">时间</param>  
        /// <returns>long</returns>  
        public static long ConvertDateTimeToInt(System.DateTime time)
        {
            System.DateTime startTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            long t = (time.Ticks - startTime.Ticks) / 10000;   //除10000调整为13位      
            return t;
        }
        #endregion




        #region 损益核算表

        /// <summary>
        /// 获取供应商下拉列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous] 
        [RateValve(Policy = Policy.Ip, Limit = 20, Duration = 60)]
        public ApiResult GetSupplierAllList(object requestMsg)
        {
            var requestParm = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            var query = JsonConvert.DeserializeObject<RB_Supplier_Extend>(requestParm.msg.ToString());
            query.TenantId = requestParm.TenantId;
            query.MallBaseId = requestParm.MallBaseId;
            var oldLogisticsList = supplierModule.GetList(query);
            return ApiResult.Success("", oldLogisticsList);
        }





        [HttpPost]
        [AllowAnonymous] 
        [RateValve(Policy = Policy.Ip, Limit = 20, Duration = 60)]
        public ApiResult GetOrderProfitLossList(object requestMsg)
        {
            var requestParm = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(requestParm.msg.ToString());
            OrderStatistics_Query demodel = JsonConvert.DeserializeObject<OrderStatistics_Query>(requestParm.msg.ToString());
            demodel.TenantId = requestParm.TenantId;
            demodel.MallBaseId = requestParm.MallBaseId;
            List<OrderStatistics_Query> list = new List<OrderStatistics_Query>();
            List<OrderStatistics_Query> listCancel = new List<OrderStatistics_Query>();
            List<OrderStatistics_Query> listAftersale = new List<OrderStatistics_Query>();
            long count = 0;
            if (demodel.IsFxCommission == 0)
            {
                list = statisticsModule.GetOrderProfitLossList(pagelist.pageIndex, pagelist.pageSize, out count, demodel);

            }
            else
            {
                list = statisticsModule.GetFXOrderProfitLossList(pagelist.pageIndex, pagelist.pageSize, out count, demodel);
                if (list != null && list.Any())
                {
                    string ids = string.Join(",", list.Select(x => x.Id));
                    demodel.Ids = ids;
                    listCancel = statisticsModule.GetFXAllCancelOrderProfitLossList(demodel);
                    listAftersale = statisticsModule.GetFXAllAftersaleOrderProfitLossList(demodel);
                }

            }

            foreach (var item in list)
            {

                if (item.OrderStatus == 7)
                {
                    item.FXCommission = 0;
                    item.LiveCommission = 0;
                    item.RemitFXCommission = 0;
                    item.RefundActual = item.RefundActual > 0 ? item.RefundActual : item.AllPrice;
                }

                if (item.OrderSource == Common.Enum.User.UserSourceEnum.ERP)
                {
                    item.ReturnServiceCharge = 0;
                    item.ServiceCharge = 0;
                }
                else
                {
                    if (item.RefundActual > 0 && (item.OrderSource.HasValue && item.OrderSource != Common.Enum.User.UserSourceEnum.ERP))
                    {
                        if (listCancel != null && listCancel.Any(x => x.Id == item.Id))//存在取消中
                        {
                            item.ReturnServiceCharge = item.ServiceCharge;
                        }
                        else if (listAftersale != null && listAftersale.Any(x => x.Id == item.Id))//存在取消中
                        {
                            item.ReturnServiceCharge = Math.Round((item.RefundActual * (Convert.ToDecimal(Config.SettlementRate) / 100)), 2, MidpointRounding.AwayFromZero);
                        }
                    }
                }


                item.CostMoney = ((item.OrderClassify == 1 && item.CarType != 5) ? item.CostMoney : (item.CostMoney * item.Number));
                item.ALLCommission = item.CostMoney + item.GoodsFreight + item.InsuranceCostMoney + item.FXCommission + item.LiveCommission + item.RefundActual + item.YFMoney;
                item.NoPaid = item.ALLCommission;
                item.RemitFXCommission = item.RemitFXCommission + (!string.IsNullOrWhiteSpace(item.LiveFinanceIds) ? item.LiveCommission : 0);
                item.Paid = item.RefundActual + item.RemitFXCommission + item.CostMoney + item.GoodsFreight + item.PayMoney;
                item.GrossProfit = item.AllPrice + item.YSMoney - item.ALLCommission;

                if (item.AllPrice == 0)
                {
                    item.GrossProfitRate = 0;
                }
                else
                {
                    item.GrossProfitRate = ((item.AllPrice + item.YSMoney) == 0 ? 0 : Math.Round((item.GrossProfit / (item.AllPrice + item.YSMoney)), 4, MidpointRounding.AwayFromZero) * 100);
                }
            }
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list;
            return ApiResult.Success("", pagelist);
        }



        /// <summary>
        /// 导出订单损益核算
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous] 
        [RateValve(Policy = Policy.Ip, Limit = 20, Duration = 60)]
        public FileContentResult GetOrderProfitLossExcel(object requestMsg)
        {
            var requestParm = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            OrderStatistics_Query demodel = JsonConvert.DeserializeObject<OrderStatistics_Query>(requestParm.msg.ToString());

            string ExcelName = "订单损益核算" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            List<ExcelDataSource> slist = new List<ExcelDataSource>();
            ExcelDataSource header = new ExcelDataSource()
            {
                ExcelRows = new List<ExcelColumn>(31) {
                    new ExcelColumn(value: "序号") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "订单号") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                     new ExcelColumn(value: "数量") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "规格") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "数量") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "供应商") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "结算款") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "运费") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "已收") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "未收款") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "合计数") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "采购成本") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "包装费摊销") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "快递费") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "商品运费摊销") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "公司返佣") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "公司") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "总代理返佣") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "总代理") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "特一级返佣") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "特一级") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "一级返佣") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "一级返佣人") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "二级返佣") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "二级返佣人") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "其他") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "合计数") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "已付") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "应付") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "毛利") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "毛利率") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER }
                },
            };
            slist.Add(header);

            try
            {
                demodel.TenantId = requestParm.TenantId;
                demodel.MallBaseId = requestParm.MallBaseId;
                List<OrderStatistics_Query> list = new List<OrderStatistics_Query>();
                if (demodel.IsFxCommission == 0)
                {
                    list = statisticsModule.GetAllOrderProfitLossList(demodel);
                }
                foreach (var item in list)
                {
                    item.ALLCommission = item.CostFreight + item.CostMoney + item.PackingMoney + item.GoodsFreight + item.OneCommission + item.TwoCommission + item.OtherPrice;
                    // item.ALLCommission = item.CostFreight + item.CostMoney + item.PackingMoney + item.GoodsFreight + item.FXCommission + item.OtherPrice;
                    item.NoPaid = item.ALLCommission - item.Paid;
                    item.GrossProfit = item.AllPrice - item.ALLCommission;
                    item.GrossProfitRate = item.AllPrice == 0 ? 0 : Math.Round((item.GrossProfit / item.AllPrice), 2, MidpointRounding.AwayFromZero);
                }
                #region 组装数据
                int Num = 0;
                foreach (var item in list)
                {
                    Num++;
                    ExcelDataSource datarow = new ExcelDataSource()
                    {
                        ExcelRows = new List<ExcelColumn>(30) {
                            new ExcelColumn(value:Num.ToString()){ },
                        }
                    };
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderNo) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.GoodsName + item.Specification) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.Unit_Price.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.Number.ToString()) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.SupplierName) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.Final_Price.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.FreightMoney) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.AllPrice.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: "0") { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.AllPrice.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.CostMoney.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.PackingMoney.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.CostFreight.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.GoodsFreight.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.BranchCommission.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.BranchName) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.GeneralAgentCommission.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.GeneralAgentName) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.SpecialCommission.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.SpecialName) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OneCommission.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OneUserName) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.TwoCommission.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.TwoUserName) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OtherPrice.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.ALLCommission.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.Paid.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.NoPaid.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.GrossProfit.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.GrossProfitRate.ToString("#0.00")) { });
                    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(requestMsg.ToString())));
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }

        }


        /// <summary>
        /// 导出订单损益核算
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        [RateValve(Policy = Policy.Ip, Limit = 20, Duration = 60)]
        public FileContentResult GetFXOrderProfitLossExcel(object requestMsg)
        {
            var requestParm = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            OrderStatistics_Query demodel = JsonConvert.DeserializeObject<OrderStatistics_Query>(requestParm.msg.ToString());

            string ExcelName = "订单损益核算" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            List<ExcelDataSource> slist = new List<ExcelDataSource>();
            ExcelDataSource header = new ExcelDataSource()
            {
                ExcelRows = new List<ExcelColumn>(23) {
                    new ExcelColumn(value: "序号") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "订单号") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                      new ExcelColumn(value: "订单状态") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                     new ExcelColumn(value: "商品名称") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "单价") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "数量") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "供应商") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "结算款") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "运费收入") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                      new ExcelColumn(value: "保险收入") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "实收") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                      new ExcelColumn(value: "其他收入") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "合计收入") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                     new ExcelColumn(value: "手续费") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "采购成本") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "运费支出") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                     new ExcelColumn(value: "保险支出") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "总返佣金额") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                  new ExcelColumn(value: "已返佣金额") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "返佣信息") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "优惠金额") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                      new ExcelColumn(value: "储值卡抵扣金额") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                     new ExcelColumn(value: "退款金额") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "其他支出") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "应付") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "已付") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "毛利") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                     new ExcelColumn(value: "分公司名称") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "毛利率") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER }
                },
            };
            slist.Add(header);

            try
            {
                demodel.TenantId = requestParm.TenantId;
                demodel.MallBaseId = requestParm.MallBaseId;
                List<OrderStatistics_Query> list = new List<OrderStatistics_Query>();
                List<OrderStatistics_Query> listCancel = new List<OrderStatistics_Query>();
                List<OrderStatistics_Query> listAftersale = new List<OrderStatistics_Query>();
                if (demodel.IsFxCommission == 1)
                {
                    demodel.IsSelectOrderCommission = 1;
                    list = statisticsModule.GetFXAllOrderProfitLossList(demodel);
                    listCancel = statisticsModule.GetFXAllCancelOrderProfitLossList(demodel);
                    listAftersale = statisticsModule.GetFXAllAftersaleOrderProfitLossList(demodel);
                }
                foreach (var item in list)
                {
                    if (item.OrderStatus == 7)
                    {
                        item.FXCommission = 0;
                        item.LiveCommission = 0;
                        item.RemitFXCommission = 0;
                        item.RefundActual = item.RefundActual > 0 ? item.RefundActual : item.AllPrice;
                    }
                    if (item.OrderSource == Common.Enum.User.UserSourceEnum.ERP)
                    {
                        item.ReturnServiceCharge = 0;
                        item.ServiceCharge = 0;
                    }
                    else
                    {
                        if (item.RefundActual > 0 && (item.OrderSource.HasValue && item.OrderSource != Common.Enum.User.UserSourceEnum.ERP))//判断当前的订单是否存在在售后获取取消中
                        {
                            if (listCancel != null && listCancel.Any(x => x.Id == item.Id))//存在取消中
                            {
                                item.ReturnServiceCharge = item.ServiceCharge;
                            }
                            else if (listAftersale != null && listAftersale.Any(x => x.Id == item.Id))//存在取消中
                            {
                                item.ReturnServiceCharge = Math.Round((item.RefundActual * (Convert.ToDecimal(Config.SettlementRate) / 100)), 2, MidpointRounding.AwayFromZero);
                            }
                        }
                    }

                    item.CostMoney = ((item.OrderClassify == 1 && item.CarType != 5) ? item.CostMoney : (item.CostMoney * item.Number));
                    item.ALLCommission = item.CostMoney + item.GoodsFreight + item.InsuranceCostMoney + item.FXCommission + item.LiveCommission + item.RefundActual + item.YFMoney;
                    // item.ALLCommission = item.CostMoney + item.GoodsFreight + item.FXCommission + item.LiveCommission +  item.RefundActual + item.YFMoney;
                    item.NoPaid = item.ALLCommission;
                    item.RemitFXCommission = item.RemitFXCommission + (!string.IsNullOrWhiteSpace(item.LiveFinanceIds) ? item.LiveCommission : 0);
                    item.Paid = item.RefundActual + item.RemitFXCommission + item.CostMoney + item.GoodsFreight + item.PayMoney;
                    item.GrossProfit = item.AllPrice + item.YSMoney - item.ALLCommission;

                    if (item.AllPrice == 0)
                    {
                        item.GrossProfitRate = 0;
                    }
                    else
                    {
                        item.GrossProfitRate = ((item.AllPrice + item.YSMoney) == 0 ? 0 : Math.Round((item.GrossProfit / (item.AllPrice + item.YSMoney)), 4, MidpointRounding.AwayFromZero) * 100);
                    }
                }
                #region 组装数据
                int Num = 0;
                foreach (var item in list)
                {
                    Num++;
                    ExcelDataSource datarow = new ExcelDataSource()
                    {
                        ExcelRows = new List<ExcelColumn>(30) {
                            new ExcelColumn(value:Num.ToString()){ },
                        }
                    };
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderNo) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: (item.OrderStatus == 7 ? "已取消" : "正常")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.GoodsName + item.Specification) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.Unit_Price.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.Number.ToString()) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.SupplierName) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.Final_Price.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.FreightMoney) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.InsuranceMoney.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.AllPrice.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.YSMoney.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: (item.AllPrice + item.YSMoney).ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: (item.ServiceCharge - item.ReturnServiceCharge).ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.CostMoney.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.GoodsFreight.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.InsuranceCostMoney.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.FXCommission.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.RemitFXCommission.ToString("#0.00")) { });
                    string commissionInfo = "";
                    if (item.OrderCommissionList != null && item.OrderCommissionList.Any() && item.OrderStatus != 7)
                    {
                        foreach (var itemCommi in item.OrderCommissionList)
                        {
                            if (!string.IsNullOrWhiteSpace(commissionInfo))
                            {
                                commissionInfo += (",[" + itemCommi.GradeDescription + ":" + itemCommi.Commission + itemCommi.UserName + "]");
                            }
                            else
                            {
                                commissionInfo += ("[" + itemCommi.GradeDescription + ":" + itemCommi.Commission + itemCommi.UserName + "]");
                            }
                        }

                        if (item.LiveCommission > 0)
                        {
                            commissionInfo += (",[" + item.LivePeopleNum + "位主播佣金:" + item.LiveCommission + "]");
                        }
                        //  commissionInfo = string.Join(",", item.OrderCommissionList.Select(x=>"["+ x.GradeDescription+x.UserName+x.Commission+x.CommissionState==1?"待返":"已返"));
                    }
                    datarow.ExcelRows.Add(new ExcelColumn(value: commissionInfo) { });//返佣信息
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.CouponMoney.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.TotalDepositMoney.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.RefundActual.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.YFMoney.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.NoPaid.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.Paid.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.GrossProfit.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.CompanyName) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.GrossProfitRate.ToString("#0.00")) { });
                    slist.Add(datarow);
                }

                if (list != null && list.Any())
                {
                    decimal GrossProfitRate = 0;
                    if (list.Count() > 0 && (list.Sum(x => x.AllPrice + x.YSMoney)) > 0)
                    {
                        GrossProfitRate = (Math.Round((list.Sum(x => x.GrossProfit) / list.Sum(x => x.AllPrice + x.YSMoney)), 4, MidpointRounding.AwayFromZero) * 100);
                    }
                    decimal totalReturn = 0;

                    if (listCancel != null && listCancel.Any())
                    {
                        totalReturn += listCancel.Where(x => x.OrderSource != Common.Enum.User.UserSourceEnum.ERP).Sum(x => x.AllPrice);
                    }
                    if (listAftersale != null && listAftersale.Any())
                    {
                        totalReturn += listAftersale.Where(x => x.OrderSource != Common.Enum.User.UserSourceEnum.ERP).Sum(x => x.RefundActual);
                    }
                    if (totalReturn > 0)
                    {
                        totalReturn = Math.Round((totalReturn * (Convert.ToDecimal(Config.SettlementRate) / 100)), 2, MidpointRounding.AwayFromZero);
                    }
                    ExcelDataSource datarow = new ExcelDataSource()
                    {
                        ExcelRows = new List<ExcelColumn>(30) {
                            new ExcelColumn(value:"小计"){ },
                        }
                    };
                    datarow.ExcelRows.Add(new ExcelColumn(value: "") { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: "") { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: "") { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: list.Sum(x => x.Unit_Price).ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: list.Sum(x => x.Number).ToString()) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: "") { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: list.Sum(x => x.Final_Price).ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: (list.Sum(x => !string.IsNullOrWhiteSpace(x.FreightMoney) ? Convert.ToDecimal(x.FreightMoney) : 0)).ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: list.Sum(x => x.InsuranceMoney).ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: list.Sum(x => x.AllPrice).ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: list.Sum(x => x.YSMoney).ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: list.Sum(x => x.AllPrice + x.YSMoney).ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: (list.Sum(x => x.ServiceCharge) - totalReturn).ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: list.Sum(x => x.CostMoney).ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: list.Sum(x => x.GoodsFreight).ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: list.Sum(x => x.InsuranceCostMoney).ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: list.Sum(x => x.FXCommission).ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: list.Sum(x => x.RemitFXCommission).ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: "") { });//返佣信息
                    datarow.ExcelRows.Add(new ExcelColumn(value: list.Sum(x => x.CouponMoney).ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: list.Sum(x => x.TotalDepositMoney).ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: list.Sum(x => x.RefundActual).ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: list.Sum(x => x.YFMoney).ToString("#0.00")) { });
                    // datarow.ExcelRows.Add(new ExcelColumn(value: item.ALLCommission.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: list.Sum(x => x.NoPaid).ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: list.Sum(x => x.Paid).ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: list.Sum(x => x.GrossProfit).ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: "") { });
                    //datarow.ExcelRows.Add(new ExcelColumn(value: Math.Round((item.GrossProfit * (item.CompanyProfitRate / 100)), 2, MidpointRounding.AwayFromZero).ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: GrossProfitRate.ToString("#0.00")) { });
                    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(requestMsg.ToString())));
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }

        }


        /// <summary>
        /// 获取商品
        /// </summary>
        /// <param name="requestMsg"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous] 
        [RateValve(Policy = Policy.Ip, Limit = 20, Duration = 60)]
        public ApiResult GetGoodsList(object requestMsg)
        {
            var requestParm = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            var query = JsonConvert.DeserializeObject<RB_Goods_Extend>(requestParm.msg.ToString());
            query.TenantId = requestParm.TenantId;
            query.MallBaseId = requestParm.MallBaseId;
            var oldLogisticsList = productModule.GetGoodsList(query).Take(15);
            return ApiResult.Success("", oldLogisticsList);
        }


        /// <summary>
        /// 获取分销商
        /// </summary>
        /// <param name="requestMsg"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous] 
        [RateValve(Policy = Policy.Ip, Limit = 20, Duration = 60)]
        public ApiResult GetDistributorInfoList(object requestMsg)
        {
            var requestParm = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            var query = JsonConvert.DeserializeObject<RB_Distributor_Info_Extend>(requestParm.msg.ToString());
            query.TenantId = requestParm.TenantId;
            query.MallBaseId = requestParm.MallBaseId;
            var oldLogisticsList = productModule.GetDistributorInfoList(query).Take(15);
            return ApiResult.Success("", oldLogisticsList);
        }


        /// <summary>
        /// 获取分销商
        /// </summary>
        /// <param name="requestMsg"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ApiResult GetTotalOrderProfitLoss_V2(object requestMsg)
        {
            var requestParm = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            OrderStatistics_Query demodel = JsonConvert.DeserializeObject<OrderStatistics_Query>(requestParm.msg.ToString());
            demodel.TenantId = requestParm.TenantId;
            demodel.MallBaseId = requestParm.MallBaseId;
            List<OrderStatistics_Query> list = new List<OrderStatistics_Query>();
            List<OrderStatistics_Query> listCancel = new List<OrderStatistics_Query>();
            List<OrderStatistics_Query> listAftersale = new List<OrderStatistics_Query>();
            if (demodel.IsFxCommission == 1)
            {
                list = statisticsModule.GetFXAllOrderProfitLossList(demodel);
                listCancel = statisticsModule.GetFXAllCancelOrderProfitLossList(demodel);
                listAftersale = statisticsModule.GetFXAllAftersaleOrderProfitLossList(demodel);
            }
            else if (demodel.IsFxCommission == 0)
            {
                demodel.IsSelectOrderCommission = 1;
                list = statisticsModule.GetAllOrderProfitLossList(demodel);
            }
            foreach (var item in list)
            {
                if (item.OrderStatus == 7)
                {
                    item.FXCommission = 0;
                    item.LiveCommission = 0;
                    item.RemitFXCommission = 0;
                    item.RefundActual = item.RefundActual > 0 ? item.RefundActual : item.AllPrice;
                }

                if (item.OrderSource == Common.Enum.User.UserSourceEnum.ERP)
                {
                    item.ReturnServiceCharge = 0;
                    item.ServiceCharge = 0;
                }
                else
                {

                    if (item.RefundActual > 0 && (item.OrderSource.HasValue && item.OrderSource != Common.Enum.User.UserSourceEnum.ERP))//判断当前的订单是否存在在售后获取取消中
                    {
                        if (listCancel != null && listCancel.Any(x => x.Id == item.Id))//存在取消中
                        {
                            item.ReturnServiceCharge = item.ServiceCharge;
                        }
                        else if (listAftersale != null && listAftersale.Any(x => x.Id == item.Id))//存在取消中
                        {
                            item.ReturnServiceCharge = Math.Round((item.RefundActual * (Convert.ToDecimal(Config.SettlementRate) / 100)), 2, MidpointRounding.AwayFromZero);
                        }
                    }
                }
                item.CostMoney = ((item.OrderClassify == 1 && item.CarType != 5) ? item.CostMoney : (item.CostMoney * item.Number));
                item.ALLCommission = item.CostMoney + item.GoodsFreight + item.InsuranceCostMoney + item.FXCommission + item.LiveCommission + item.RefundActual + item.YFMoney;
                item.NoPaid = item.ALLCommission;
                item.RemitFXCommission = item.RemitFXCommission + (!string.IsNullOrWhiteSpace(item.LiveFinanceIds) ? item.LiveCommission : 0);
                item.Paid = item.RefundActual + item.RemitFXCommission + item.CostMoney + item.GoodsFreight + item.PayMoney;
                item.GrossProfit = item.AllPrice + item.YSMoney - item.ALLCommission;

                if (item.AllPrice == 0)
                {
                    item.GrossProfitRate = 0;
                }
                else
                {
                    item.GrossProfitRate = ((item.AllPrice + item.YSMoney) == 0 ? 0 : Math.Round((item.GrossProfit / (item.AllPrice + item.YSMoney)), 4, MidpointRounding.AwayFromZero) * 100);
                }
            }


            decimal GrossProfitRate = 0;
            if (list.Count() > 0 && (list.Sum(x => x.AllPrice + x.YSMoney)) > 0)
            {
                GrossProfitRate = (Math.Round((list.Sum(x => x.GrossProfit) / list.Sum(x => x.AllPrice + x.YSMoney)), 4, MidpointRounding.AwayFromZero) * 100);
            }

            decimal totalReturn = 0;

            if (listCancel != null && listCancel.Any())
            {
                totalReturn += listCancel.Where(x => x.OrderSource != Common.Enum.User.UserSourceEnum.ERP).Sum(x => x.AllPrice);
            }
            if (listAftersale != null && listAftersale.Any())
            {
                totalReturn += listAftersale.Where(x => x.OrderSource != Common.Enum.User.UserSourceEnum.ERP).Sum(x => x.RefundActual);
            }
            if (totalReturn > 0)
            {
                totalReturn = list.Sum(x => x.ReturnServiceCharge);  //Math.Round((totalReturn * (Convert.ToDecimal(Config.SettlementRate) / 100)), 2, MidpointRounding.AwayFromZero);
            }
            decimal AvgGrossProfit = 0;
            int GoodsNum = 0;
            decimal totalGrossProfit = 0;
            if (list != null && list.Any())
            {
                totalGrossProfit = list.Sum(x => x.GrossProfit);
                GoodsNum = list.Sum(x => x.Number);
                if (GoodsNum > 0)
                {
                    AvgGrossProfit = (Math.Round((totalGrossProfit / Convert.ToDecimal(GoodsNum)), 2, MidpointRounding.AwayFromZero));
                }
            }
            var retult = new
            {
                OrderNo = "",
                GoodsName = "",
                Unit_Price = list.Sum(x => x.Unit_Price),//单价
                Number = GoodsNum, //数量
                SupplierName = "",
                Final_Price = list.Sum(x => x.Final_Price),//数量
                FreightMoney = list.Sum(x => !string.IsNullOrWhiteSpace(x.FreightMoney) ? Convert.ToDecimal(x.FreightMoney) : 0),
                AllPrice = list.Sum(x => x.AllPrice),
                ServiceCharge = list.Sum(x => x.ServiceCharge),
                ReturnServiceCharge = totalReturn,
                CostMoney = list.Sum(x => x.CostMoney),
                PackingMoney = list.Sum(x => x.PackingMoney),
                GoodsFreight = list.Sum(x => x.GoodsFreight),
                InsuranceCostMoney = list.Sum(x => x.InsuranceCostMoney),
                InsuranceMoney = list.Sum(x => x.InsuranceMoney),
                PaidCostMoney = list.Sum(x => x.PaidCostMoney),
                CostFreight = list.Sum(x => x.CostFreight),
                FXCommission = list.Sum(x => x.FXCommission),
                RemitFXCommission = list.Sum(x => x.RemitFXCommission),
                ALLCommission = list.Sum(x => x.ALLCommission),
                OtherPrice = list.Sum(x => x.OtherPrice),
                Paid = list.Sum(x => x.Paid),
                NoPaid = list.Sum(x => x.NoPaid),
                CouponMoney = list.Sum(x => x.CouponMoney),
                TotalDepositMoney = list.Sum(x => x.TotalDepositMoney),
                RefundActual = list.Sum(x => x.RefundActual),
                YSMoney = list.Sum(x => x.YSMoney),
                RealMoney = list.Sum(x => x.RealMoney),
                YFMoney = list.Sum(x => x.YFMoney),
                PayMoney = list.Sum(x => x.PayMoney),
                GrossProfit = totalGrossProfit,
                CompanyName = "",
                AvgGrossProfit,//平均毛利率
                GrossProfitRate,//毛利率的平均值
            };


            return ApiResult.Success("", retult);
        }




        /// <summary>
        /// 获取分销商
        /// </summary>
        /// <param name="requestMsg"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous] 
        [RateValve(Policy = Policy.Ip, Limit = 20, Duration = 60)]
        public ApiResult GetTotalOrderProfitLoss(object requestMsg)
        {
            var requestParm = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            OrderStatistics_Query demodel = JsonConvert.DeserializeObject<OrderStatistics_Query>(requestParm.msg.ToString());
            demodel.TenantId = requestParm.TenantId;
            demodel.MallBaseId = requestParm.MallBaseId;
            List<OrderStatistics_Query> list = new List<OrderStatistics_Query>();
            if (demodel.IsFxCommission == 1)
            {
                list = statisticsModule.GetFXAllOrderProfitLossList(demodel);
            }
            else if (demodel.IsFxCommission == 0)
            {
                list = statisticsModule.GetAllOrderProfitLossList(demodel);
            }
            foreach (var item in list)
            {
                item.ALLCommission = item.CostFreight + item.CostMoney + item.PackingMoney + item.GoodsFreight + item.FXCommission + item.LiveCommission + item.OtherPrice;
                item.NoPaid = item.ALLCommission;
                item.RemitFXCommission = item.RemitFXCommission + (!string.IsNullOrWhiteSpace(item.LiveFinanceIds) ? item.LiveCommission : 0);
                item.Paid = item.PaidCostMoney + item.RemitFXCommission;
                item.GrossProfit = (item.AllPrice + item.RealMoney) - item.CouponMoney - item.RefundActual - item.ALLCommission - item.PayMoney;
                item.GrossProfitRate = (item.AllPrice + item.RealMoney) == 0 ? 0 : Math.Round((item.GrossProfit / ((item.AllPrice + item.RealMoney - item.RefundActual) == 0 ? 1 : (item.AllPrice + item.RealMoney - item.RefundActual))), 2, MidpointRounding.AwayFromZero);
                //item.GrossProfit = item.AllPrice - item.ALLCommission;
                //item.GrossProfitRate = item.AllPrice == 0 ? 0 : Math.Round((item.GrossProfit / item.AllPrice), 2, MidpointRounding.AwayFromZero);
            }

            var retult = new
            {
                TotalFinal_Price = list.Sum(x => x.Final_Price),//结算款小计
                TotalFreightMoney = list.Sum(x => string.IsNullOrWhiteSpace(x.FreightMoney) ? 0 : Convert.ToDecimal(x.FreightMoney)),//运费小计
                TotalAllPrice = list.Sum(x => x.AllPrice),//已收小计
                TotalNoAllPrice = list.Sum(x => 0),//未收小计
                TotalPay = list.Sum(x => x.AllPrice),//合计小计
                TotalCostMoney = list.Sum(x => x.CostMoney),//采购成本小计
                TotalPackingMoney = list.Sum(x => x.PackingMoney),//包装费摊销小计
                TotalCostFreight = list.Sum(x => x.CostFreight),//快递成本小计
                TotalGoodsFreight = list.Sum(x => x.GoodsFreight),//商品运费小计
                TotalBranchCommission = list.Sum(x => x.BranchCommission),//分公司小计
                TotalGeneralAgentCommission = list.Sum(x => x.GeneralAgentCommission),//总代理小计
                TotalSpecialCommission = list.Sum(x => x.SpecialCommission),//特一级小计
                TotalOneCommission = list.Sum(x => x.OneCommission),//一级返佣小计
                TotalOneTwoCommission = list.Sum(x => x.TwoCommission),//二级返佣小计
                TotalFXCommission = list.Sum(x => x.FXCommission),//粉象总返佣
                TotalPaidCostMoney = list.Sum(x => x.PaidCostMoney),//商品已付总成本
                TotalRemitFXCommission = list.Sum(x => x.RemitFXCommission),//已提现总返佣
                TotalOneOtherPrice = list.Sum(x => x.OtherPrice),//其他费用小计
                TotalALLCommission = list.Sum(x => x.ALLCommission),//营业合计小计
                TotalPaid = list.Sum(x => x.Paid),//已付小计
                TotalNoPaid = list.Sum(x => x.NoPaid),//未付小计
                TotalGrossProfit = list.Sum(x => x.GrossProfit),//毛利小计
                TotalRealMoney = list.Sum(x => x.RealMoney),//其他实收
                TotalPayMoney = list.Sum(x => x.PayMoney),//其他实付
                TotalCouponMoney = list.Sum(x => x.CouponMoney),//优惠金额
                TotalDepositMoney = list.Sum(x => x.TotalDepositMoney),//储值卡抵扣金额
                TotalCompanyProfit = list.Sum(x => Math.Round((x.GrossProfit * (x.CompanyProfitRate / 100)), 2, MidpointRounding.AwayFromZero)),//公司结算金额
            };


            return ApiResult.Success("", retult);
        }

        /// <summary>
        /// 根据商品订单详情获取返佣信息
        /// </summary>
        /// <param name="requestMsg"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous] 
        [RateValve(Policy = Policy.Ip, Limit = 20, Duration = 60)]
        public ApiResult GetOrderCommissionList(object requestMsg)
        {
            var requestParm = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            RB_Goods_OrderCommission_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_OrderCommission_Extend>(requestParm.msg.ToString());
            demodel.TenantId = requestParm.TenantId;
            demodel.MallBaseId = requestParm.MallBaseId;

            var list = statisticsModule.GetByOrderDetailId(demodel);

            return ApiResult.Success("", list);
        }



        /// <summary>
        /// 获取用户下拉列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetCompanyUserList(object requestMsg)
        {
            var requestParm = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            RB_Member_User_Extend demodel = JsonConvert.DeserializeObject<RB_Member_User_Extend>(requestParm.msg.ToString());
            demodel.TenantId = requestParm.TenantId;
            demodel.MallBaseId = requestParm.MallBaseId;
            var list = productModule.GetCompanyUserList(demodel);
            var result = list.Select(x => new
            {
                x.Id,
                x.Name,
                x.Moblie,
                x.Photo
            });
            return ApiResult.Success("", result);
        }



        #endregion


        #region erp低利润商品查询


        /// <summary>
        /// 商品后台分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetProductGoodsPageList(object requestMsg)
        {
            var parms = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            JObject parameters = JObject.Parse(parms.msg.ToString());
            RB_Goods_Extend demodel = new RB_Goods_Extend()
            {
                Name = parameters.GetStringValue("Name"),
                GoodsStatus = parameters.GetInt("GoodsStatus"),
                IsSelectSellOut = parameters.GetInt("IsSelectSellOut"),
                CategoryIds = parameters.GetStringValue("CategoryIds"),
                Id = parameters.GetInt("Id"),
                StartTime = parameters.GetStringValue("StartTime"),
                EndTime = parameters.GetStringValue("EndTime"),
                OrderBy = parameters.GetInt("OrderBy")
            };

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            decimal MinProfitRate = 0;
            if (demodel.TenantId == 1)
            {
                //MinProfitRate = Convert.ToDecimal(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("MinProfitRate")["TenantId1"]);
            }
            if (demodel.IsSelectLowProfit == 1)
            {
                demodel.MinProfitRate = MinProfitRate;
            }
            var list = productModule.GetProductGoodsPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.Name,
                x.Sort,
                x.CoverImage,
                CategoryList = x.CategoryList.Select(y => new { y.Id, y.CategoryName }),
                x.SellingPrice,
                x.InventoryNum,
                x.SalesNum,
                x.GoodsBuyNum,
                x.IsQuickBuy,
                x.IsProxy,
                x.IsProcurement,
                x.ProcurementStatus,
                x.GoodsStatus,
                x.TenantId,
                x.MallBaseId,
                x.SendArea,
                x.Remark,
                GoodsPageTypeStr = x.GoodsPageType.GetEnumName(),
                CarouselImageList = x.CarouselImageList.Select(qitem => qitem.Path).ToList(),
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                x.IsNoTax,
                IsLowProfit = MinProfitRate > 0 ? x.MinProfitRate < MinProfitRate ? 1 : 2 : 2
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 商品信息下载
        /// </summary>
        [HttpPost]
        public FileContentResult GetProductGoodsListToExcel(object requestMsg)
        {
            var parms = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            RB_Goods_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Extend>(parms.msg.ToString());
            string ExcelName = "商品列表" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            List<ExcelDataSource> slist = new List<ExcelDataSource>();
            ExcelDataSource header = new ExcelDataSource()
            {
                ExcelRows = new List<ExcelColumn>(30) {
                    new ExcelColumn(value: "序号") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "商品名称") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "原价") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "成本价") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "商品详情") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "商品缩略图") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "商品轮播图") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "商品视频") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "单位") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "售价") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "是否使用规格") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "规格组") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "商品库存") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "虚拟销量") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "购物数量限制") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "单品满件包邮") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "单品满额包邮") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "赠送积分") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "赠送积分类型") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "可抵扣积分") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "可抵扣积分类型") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "允许多件累计折扣") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "自定义分享图片") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "自定义分享标题") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "排序") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "限购订单") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "是否单独区域购买") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "区域限购详情") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "规格详情") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "是否快速购买") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "是否热销") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "是否面议") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER }
                }
            };

            slist.Add(header);

            try
            {
                demodel.TenantId = parms.TenantId;
                demodel.MallBaseId = parms.MallBaseId;
                decimal MinProfitRate = 0;
                if (demodel.TenantId == 1)
                {
                    //MinProfitRate = Convert.ToDecimal(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("MinProfitRate")["TenantId1"]);
                }
                if (demodel.IsSelectLowProfit == 1)
                {
                    demodel.MinProfitRate = MinProfitRate;
                }
                var list = productModule.GetProductGoodsListForExcel(demodel);
                #region 组装数据
                int Num = 0;
                foreach (var item in list)
                {
                    Num++;
                    string GGZ = "";
                    string GGMX = "";
                    if (item.IsCustomSpecification == 1)
                    {
                        var obj = item.SpecificationList.Select(x => new
                        {
                            x.Id,
                            x.GoodsId,
                            x.Name,
                            x.Sort,
                            x.EnabledImage,
                            SpecificationValueList = x.SpecificationValueList.Select(z => new
                            {
                                z.Id,
                                z.GoodsId,
                                z.SpecificationId,
                                z.Name,
                                z.Image,
                                z.Sort
                            })
                        });
                        GGZ = JsonConvert.SerializeObject(obj);//序列化

                        GGMX = JsonConvert.SerializeObject(item.SpecificationPriceList.Select(x => new
                        {
                            x.Id,
                            x.GoodsId,
                            x.SpecificationSort,
                            x.SellingPrice,
                            x.InventoryNum,
                            x.GoodsWeight,
                            x.GoodsNumbers
                        }));
                    }
                    else
                    {
                        List<object> objList = new List<object>();
                        List<object> SpecificationValueList = new List<object>();
                        SpecificationValueList.Add(new
                        {
                            Id = 0,
                            GoodsId = item.Id,
                            SpecificationId = 0,
                            Name = item.DefaultSpecificationName,
                            Image = "",
                            Sort = 0
                        });
                        objList.Add(new
                        {
                            Id = 0,
                            GoodsId = item.Id,
                            Name = "规格",
                            Sort = 0,
                            EnabledImage = 2,
                            SpecificationValueList
                        });
                        GGZ = JsonConvert.SerializeObject(objList);//序列化
                        List<object> SpecificationPriceList = new List<object>();
                        SpecificationPriceList.Add(new
                        {
                            Id = 0,
                            GoodsId = item.Id,
                            SpecificationSort = "",
                            item.SellingPrice,
                            item.InventoryNum,
                            item.GoodsWeight,
                            item.GoodsNumbers
                        });
                        GGMX = JsonConvert.SerializeObject(SpecificationPriceList);//序列化
                    }
                    string AreaList = "";
                    if (item.IsAreaBuy == 1)
                    {
                        AreaList = JsonConvert.SerializeObject(item.AreaList.Select(x => new
                        {
                            x.Id,
                            x.GoodsId,
                            x.AreaId,
                            x.AreaName,
                            x.AreaType
                        }));
                    }

                    ExcelDataSource datarow = new ExcelDataSource()
                    {
                        ExcelRows = new List<ExcelColumn>(30) {
                            new ExcelColumn(value:Num.ToString()){ },
                            new ExcelColumn(value:item.Name){ },
                            new ExcelColumn(value:(item.OriginalPrice??0).ToString()){ },
                            new ExcelColumn(value:(item.CostPrice??0).ToString()){ },
                            new ExcelColumn(value:item.GoodsDetails){ },
                            new ExcelColumn(value:item.CoverImage){ },
                            new ExcelColumn(value:item.CarouselImage){ },
                            new ExcelColumn(value:item.VideoAddress){ },
                            new ExcelColumn(value:item.Unit){ },
                            new ExcelColumn(value:(item.SellingPrice??0).ToString()){ },

                            new ExcelColumn(value:(item.IsCustomSpecification??2).ToString()){ },
                            new ExcelColumn(value:GGZ.ToString()){ },

                            new ExcelColumn(value:(item.InventoryNum??0).ToString()){ },
                            new ExcelColumn(value:(item.SalesNum??0).ToString()){ },
                            new ExcelColumn(value:(item.LimitBuyGoodsNum??0).ToString()){ },
                            new ExcelColumn(value:(item.FullNumPinkage??0).ToString()){ },
                            new ExcelColumn(value:(item.FullMoneyPinkage??0).ToString()){ },
                            new ExcelColumn(value:(item.IntegralPresent??0).ToString()){ },
                            new ExcelColumn(value:(item.IntegralPresentType??0).ToString()){ },
                            new ExcelColumn(value:(item.PointsDeduction??0).ToString()){ },
                            new ExcelColumn(value:(item.PointsDeductionType??0).ToString()){ },
                            new ExcelColumn(value:(item.IsMultipleDeduction??0).ToString()){ },
                            new ExcelColumn(value:item.CustomShareImage ??""){ },
                            new ExcelColumn(value:item.CustomShareTitles ??""){ },
                            new ExcelColumn(value:(item.Sort??0).ToString()){ },
                            new ExcelColumn(value:(item.LimitBuyOrderNum??0).ToString()){ },

                            new ExcelColumn(value:(item.IsAreaBuy??0).ToString()){ },
                            new ExcelColumn(value:AreaList.ToString()){ },
                            new ExcelColumn(value:GGMX.ToString()){ },

                            new ExcelColumn(value:(item.IsQuickBuy??0).ToString()){ },
                            new ExcelColumn(value:(item.IsSellWell??0).ToString()){ },
                            new ExcelColumn(value:(item.IsGoodsNegotiable??0).ToString()){ },
                        }
                        ,
                        ColumnHight = 30
                    };
                    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(parms)));
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }

        }

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

            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            var list = productModule.GetProductCategoryTreeList(demodel);
            return ApiResult.Success("", list);
        }

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

            var model = productModule.GetProductGoodsInfo(GoodsId, parms.TenantId, parms.MallBaseId);
            var tempLogo = new MarketingLogoItem();
            if (!string.IsNullOrEmpty(model?.MarketingLogo))
            {
                try
                {
                    tempLogo = Common.Plugin.JsonHelper.DeserializeObject<MarketingLogoItem>(model?.MarketingLogo);
                }
                catch
                {
                    tempLogo = new MarketingLogoItem();
                }
            }
            object obj = new object();
            if (model != null)
            {
                obj = new
                {
                    model?.Id,
                    model?.Name,
                    model?.CarouselImage,
                    model?.VideoAddress,
                    model?.CustomShareTitles,
                    model?.CustomShareImage,
                    model?.CustomShareImagePath,
                    model?.GoodsStatus,
                    model?.InventoryNum,
                    model?.DefaultSpecificationName,
                    model?.IsCustomSpecification,
                    model?.Sort,
                    model?.SellingPrice,
                    model?.OriginalPrice,
                    model?.Unit,
                    model?.CostPrice,
                    model?.IsGoodsNegotiable,
                    model?.SalesNum,
                    model?.GoodsNumbers,
                    model?.GoodsWeight,
                    model?.IsDefaultService,
                    model?.GoodsService,
                    model?.FreightId,
                    model?.FreightName,
                    model?.FormsId,
                    model?.FormsName,
                    model?.LimitBuyGoodsNum,
                    model?.LimitBuyOrderNum,
                    model?.FullNumPinkage,
                    model?.FullMoneyPinkage,
                    model?.IsAreaBuy,
                    model?.IntegralPresent,
                    model?.IntegralPresentType,
                    model?.PointsDeduction,
                    model?.PointsDeductionType,
                    model?.IsMultipleDeduction,
                    model?.GoodsDetails,
                    model?.SeparateDistribution,
                    model?.SeparateDistributionType,
                    model?.SeparateDistributionMoneyType,
                    model?.EnjoyMember,
                    model?.SeparateSetMember,
                    model?.IsQuickBuy,
                    model?.SupplierId,
                    model?.IsProxy,
                    model?.ProxyType,
                    model?.ProxyRises,
                    model?.ProxyMoney,
                    model?.IsProcurement,
                    model?.Commission,
                    model?.IsLiveGoods,
                    model?.SendArea,
                    model?.Remark,
                    model?.GoodsPageType,
                    model?.IsNoTax,
                    CategoryList = model?.CategoryList.Select(x => new
                    {
                        x.Id,
                        x.CategoryId,
                        x.CategoryName
                    }),
                    SpecificationList = model?.SpecificationList.Select(x => new
                    {
                        x.Id,
                        x.EnabledImage,
                        x.Name,
                        x.Sort,
                        SpecificationValueList = x.SpecificationValueList.Select(y => new
                        {
                            y.Id,
                            y.Image,
                            y.ImagePath,
                            y.Name,
                            y.Sort
                        })
                    }),
                    SpecificationPriceList = model?.SpecificationPriceList.Select(x => new
                    {
                        x.Id,
                        x.GoodsNumbers,
                        x.GoodsWeight,
                        x.InventoryNum,
                        x.SellingPrice,
                        x.SpecificationSort,
                        x.AttrList,
                        x.Commission,
                        x.CostMoney
                    }),
                    AreaList = model?.AreaList.Select(x => new
                    {
                        x.Id,
                        x.AreaId,
                        x.AreaName,
                        x.AreaType
                    }),
                    DistributionCommissionList = model?.DistributionCommissionList.Select(x => new
                    {
                        x.Id,
                        x.DistributorGrade,
                        x.OneCommission,
                        x.SpecificationSort,
                        x.ThreeCommission,
                        x.TwoCommission
                    }),
                    DistributionCommissionTreeList = model?.DistributionCommissionTreeList.Select(x => new
                    {
                        x.Id,
                        x.SpecificationSort,
                        x.AttrList,
                        GradeCommissionList = x.GradeCommissionList.Select(y => new
                        {
                            y.DistributorGrade,
                            y.OneCommission,
                            y.ThreeCommission,
                            y.TwoCommission
                        })
                    }),
                    MemberPriceList = model?.MemberPriceList.Select(x => new
                    {
                        x.Id,
                        x.MemberGrade,
                        x.MemberPrice,
                        x.SpecificationSort
                    }),
                    MemberPriceTreeList = model?.MemberPriceTreeList.Select(x => new
                    {
                        x.Id,
                        x.SpecificationSort,
                        x.AttrList,
                        GradePriceList = x.GradePriceList.Select(y => new
                        {
                            y.MemberGrade,
                            y.MemberPrice
                        })
                    }),
                    model?.CarouselImageList,
                    model?.ServiceList,
                    model?.PresentFXGrade,
                    model?.PresentFXMonth,
                    model?.Advertising,
                    model?.SubName,
                    MarketingLogo = tempLogo,
                    model?.ShelvesDate,
                    model?.DownDate,
                    model?.VideoType,
                    model?.IntegralComment,
                    model?.IntegralCommentType,
                };
            }
            return ApiResult.Success("", obj);
        }

        #endregion


        #region 电商统计

        /// <summary>
        /// 电商月度统计
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous] 
        [RateValve(Policy = Policy.Ip, Limit = 20, Duration = 60)]
        public ApiResult GetDSMonthStatistics(object requestMsg)
        {
            var requestParm = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            JObject parms = JObject.Parse(requestParm.msg.ToString());
            string Month = parms.GetStringValue("Month");//月份
            if (string.IsNullOrEmpty(Month))
            {
                return ApiResult.ParamIsNull();
            }
            try
            {
                Month = Convert.ToDateTime(Month).ToString("yyyy-MM");
            }
            catch (Exception)
            {
                return ApiResult.Failed("月份格式有误");
            }

            var Robj = statisticsModule.GetDSMonthStatistics(Month, requestParm.TenantId, requestParm.MallBaseId);
            return ApiResult.Success("", Robj);
        }

        /// <summary>
        /// 导出电商月度统计
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous] 
        [RateValve(Policy = Policy.Ip, Limit = 20, Duration = 60)]
        public FileContentResult GetDSMonthStatisticsToExcel(object requestMsg)
        {
            var requestParm = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            JObject parms = JObject.Parse(requestParm.msg.ToString());
            string Month = parms.GetStringValue("Month");//月份
            string ExcelName = "电商月度统计" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            List<ExcelDataSource> slist = new List<ExcelDataSource>();
            if (string.IsNullOrEmpty(Month))
            {
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }
            try
            {
                Month = Convert.ToDateTime(Month).ToString("yyyy-MM");
            }
            catch (Exception)
            {
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }

            ExcelDataSource header = new ExcelDataSource()
            {
                ExcelRows = new List<ExcelColumn>(23) {
                    new ExcelColumn(value: "") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "平均付款人數") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "平均付款單數") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "平均付款金額") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "平均付款件數") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "平均取消單數") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "平均每人購買單數") { CellWidth = 20, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "平均每人購買件數") { CellWidth = 20, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "平均每單單價") { CellWidth = 20, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "平均每人購買單價") { CellWidth = 20, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "平均會員累計數") { CellWidth = 20, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "平均付款累計人數") { CellWidth = 20, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "平均會員下單轉換率") { CellWidth = 20, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "平均復夠人數") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "平均復夠率") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "平均新人下單") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "平均普象") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "平均VIP") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "平均銀象") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "平均金象") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER }
                },
                ColumnHight = 30
            };
            slist.Add(header);

            try
            {
                List<ExcelDataSource> Rlist = statisticsModule.GetDSMonthStatisticsToExcel(Month, requestParm.TenantId, requestParm.MallBaseId);
                slist.AddRange(Rlist);
                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(requestMsg.ToString())));
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }

        }

        /// <summary>
        /// 每月统计
        /// </summary>
        /// <param name="requestMsg"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous] [RateValve(Policy = Policy.Ip, Limit = 20, Duration = 60)]
        public ApiResult GetDSMoreMonthStatistics(object requestMsg)
        {
            var requestParm = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            JObject parms = JObject.Parse(requestParm.msg.ToString());
            string StartTime = parms.GetStringValue("StartTime");//开始时间  月
            string EndTime = parms.GetStringValue("EndTime");//结束时间  月
            if (string.IsNullOrEmpty(StartTime))
            {
                return ApiResult.ParamIsNull();
            }
            if (string.IsNullOrEmpty(EndTime))
            {
                return ApiResult.ParamIsNull();
            }
            try
            {
                StartTime = Convert.ToDateTime(StartTime).ToString("yyyy-MM");
                EndTime = Convert.ToDateTime(EndTime).ToString("yyyy-MM");
            }
            catch (Exception)
            {
                return ApiResult.Failed("月份格式有误");
            }
            if (Convert.ToDateTime(StartTime) > Convert.ToDateTime(EndTime))
            {
                return ApiResult.Failed("起始月份不能大于结束月份");
            }

            var Robj = statisticsModule.GetDSMoreMonthStatistics(StartTime, EndTime, requestParm.TenantId, requestParm.MallBaseId);
            return ApiResult.Success("", Robj);
        }

        /// <summary>
        /// 每月统计导出excel
        /// </summary>
        /// <param name="requestMsg"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous] 
        [RateValve(Policy = Policy.Ip, Limit = 20, Duration = 60)]
        public FileContentResult GetDSMoreMonthStatisticsToExcel(object requestMsg)
        {
            var requestParm = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            JObject parms = JObject.Parse(requestParm.msg.ToString());
            string StartTime = parms.GetStringValue("StartTime");//开始时间  月
            string EndTime = parms.GetStringValue("EndTime");//结束时间  月
            string ExcelName = "电商多月统计" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            List<ExcelDataSource> slist = new List<ExcelDataSource>();
            if (string.IsNullOrEmpty(StartTime))
            {
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }
            if (string.IsNullOrEmpty(EndTime))
            {
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }
            try
            {
                StartTime = Convert.ToDateTime(StartTime).ToString("yyyy-MM");
                EndTime = Convert.ToDateTime(EndTime).ToString("yyyy-MM");
            }
            catch (Exception)
            {
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }
            if (Convert.ToDateTime(StartTime) > Convert.ToDateTime(EndTime))
            {
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }

            ExcelDataSource header = new ExcelDataSource()
            {
                ExcelRows = new List<ExcelColumn>(23) {
                    new ExcelColumn(value: "月份") { CellWidth = 25, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "平均付款人數") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "平均付款單數") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "平均付款金額") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "平均付款件數") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "平均每人購買單數") { CellWidth = 20, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "平均每人購買件數") { CellWidth = 20, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "平均每單單價") { CellWidth = 20, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "平均每人購買單價") { CellWidth = 20, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "平均會員累計數") { CellWidth = 20, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "平均付款累計人數") { CellWidth = 20, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "平均會員下單轉換率") { CellWidth = 20, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "平均復夠人數") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "平均復夠率") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "平均新人下單") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "毛利率") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER }
                },
                ColumnHight = 30
            };
            slist.Add(header);

            try
            {
                List<ExcelDataSource> Rlist = statisticsModule.GetDSMoreMonthStatisticsToExcel(StartTime, EndTime, requestParm.TenantId, requestParm.MallBaseId);
                slist.AddRange(Rlist);
                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(requestMsg.ToString())));
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }

        }

        /// <summary>
        /// 年度统计
        /// </summary>
        /// <param name="requestMsg"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous] 
        [RateValve(Policy = Policy.Ip, Limit = 20, Duration = 60)]
        public ApiResult GetDSYearStartistics(object requestMsg)
        {
            var requestParm = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            JObject parms = JObject.Parse(requestParm.msg.ToString());
            int StartYear = parms.GetInt("StartYear", 0);//开始时间  年
            int EndYear = parms.GetInt("EndYear", 0);//结束时间  年
            if (StartYear <= 0 || EndYear <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            if (StartYear < 2019 || StartYear > EndYear)
            {
                return ApiResult.ParamIsNull("参数有误");
            }

            var Robj = statisticsModule.GetDSYearStartistics(StartYear, EndYear, requestParm.TenantId, requestParm.MallBaseId);
            return ApiResult.Success("", Robj);
        }

        /// <summary>
        /// 年度导出
        /// </summary>
        /// <param name="requestMsg"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous] 
        [RateValve(Policy = Policy.Ip, Limit = 20, Duration = 60)]
        public FileContentResult GetDSYearStartisticsToExcel(object requestMsg)
        {
            var requestParm = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            JObject parms = JObject.Parse(requestParm.msg.ToString());
            int StartYear = parms.GetInt("StartYear", 0);//开始时间  年
            int EndYear = parms.GetInt("EndYear", 0);//结束时间  年
            string ExcelName = "电商年度统计" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            List<ExcelDataSource> slist = new List<ExcelDataSource>();
            if (StartYear <= 0 || EndYear <= 0)
            {
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }
            if (StartYear < 2019 || StartYear > EndYear)
            {
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }

            try
            {
                List<ExcelDataSource> Rlist = statisticsModule.GetDSYearStartisticsToExcel(StartYear, EndYear, requestParm.TenantId, requestParm.MallBaseId);
                slist.AddRange(Rlist);
                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(requestMsg.ToString())));
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }
        }

        #endregion
    }
}