using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
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 Newtonsoft.Json;

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]
        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.GetLiveHousePageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            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);
        }



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

            foreach (var item in list)
            {
                item.ALLCommission = item.CostMoney + item.GoodsFreight + item.FXCommission + item.LiveCommission + item.CouponMoney + item.RefundActual + item.YFMoney;
                item.NoPaid = item.ALLCommission;
                item.RemitFXCommission = item.RemitFXCommission + (!string.IsNullOrWhiteSpace(item.LiveFinanceIds) ? item.LiveCommission : 0);
                item.Paid = item.ServiceCharge + 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);
                }
               
                // 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 - item.RefundActual) == 0 ? 0 : Math.Round((item.GrossProfit / ((item.AllPrice + item.RealMoney - item.RefundActual) == 0 ? 1 : (item.AllPrice + item.RealMoney - item.RefundActual))), 2, MidpointRounding.AwayFromZero);

            }
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list;
            return ApiResult.Success("", pagelist);
        }



        /// <summary>
        /// 导出订单损益核算
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        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]
        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 }
                },
            };
            slist.Add(header);

            try
            {
                demodel.TenantId = requestParm.TenantId;
                demodel.MallBaseId = requestParm.MallBaseId;
                List<OrderStatistics_Query> list = new List<OrderStatistics_Query>();
                if (demodel.IsFxCommission == 1)
                {
                    demodel.IsSelectOrderCommission = 1;
                    list = statisticsModule.GetFXAllOrderProfitLossList(demodel);
                }
                foreach (var item in list)
                {
                   
                    item.ALLCommission = item.CostMoney + item.GoodsFreight + item.FXCommission + item.LiveCommission + item.CouponMoney + item.RefundActual + item.YFMoney;
                    item.NoPaid = item.ALLCommission;
                    item.RemitFXCommission = item.RemitFXCommission + (!string.IsNullOrWhiteSpace(item.LiveFinanceIds) ? item.LiveCommission : 0);
                    item.Paid = item.ServiceCharge + 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);
                    }

                    //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 - item.RefundActual) == 0 ? 0 : Math.Round((item.GrossProfit / ((item.AllPrice + item.RealMoney - item.RefundActual) == 0 ? 1 : (item.AllPrice + item.RealMoney - item.RefundActual))), 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.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.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.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.FXCommission.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.RemitFXCommission.ToString("#0.00")) { });
                    string commissionInfo = "";
                    if (item.OrderCommissionList != null && item.OrderCommissionList.Any())
                    {
                        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.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);
                    }

                    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.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).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.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.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]
        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]
        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>();
            if (demodel.IsFxCommission == 1)
            {
                list = statisticsModule.GetFXAllOrderProfitLossList(demodel);
            }
            else if (demodel.IsFxCommission == 0)
            {
                demodel.IsSelectOrderCommission = 1;
                list = statisticsModule.GetAllOrderProfitLossList(demodel);
            }
            foreach (var item in list)
            {
               
               
                item.ALLCommission =  item.CostMoney + item.GoodsFreight + item.FXCommission + item.LiveCommission + item.CouponMoney + item.RefundActual + item.YFMoney;
                item.NoPaid = item.ALLCommission;
                item.RemitFXCommission = item.RemitFXCommission + (!string.IsNullOrWhiteSpace(item.LiveFinanceIds) ? item.LiveCommission : 0);
                item.Paid = item.ServiceCharge + 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);
            }
            var retult = new
            {

                OrderNo = "",
                GoodsName = "",
                Unit_Price = list.Sum(x => x.Unit_Price),//单价
                Number = list.Sum(x => x.Number),//数量
                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),
                CostMoney = list.Sum(x => x.CostMoney),
                PackingMoney = list.Sum(x => x.PackingMoney),
                GoodsFreight = list.Sum(x => x.GoodsFreight),
                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),
                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 = list.Sum(x => x.GrossProfit),
                CompanyName = "",
                GrossProfitRate,//毛利率的平均值
            };


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




        /// <summary>
        /// 获取分销商
        /// </summary>
        /// <param name="requestMsg"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        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.ALLCommission = item.CostFreight + item.CostMoney + item.PackingMoney + item.GoodsFreight + item.OneCommission + item.TwoCommission + 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),//优惠金额
                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]
        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
    }
}