using System.Linq;
using Mall.Common.API;
using Microsoft.AspNetCore.Mvc;
using Mall.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Mall.Module.MarketingCenter;
using Newtonsoft.Json;
using Mall.Model.Query;
using System;
using Mall.Common.Plugin;
using System.Collections.Generic;
using Mall.Module.User;
using Microsoft.AspNetCore.Authorization;

namespace Mall.WebApi.Controllers.MarketingCenter
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class StatisticsController : BaseController
    {
        public StatisticsModule statisticsModule = new StatisticsModule();
        #region  数据统计
        /// <summary>
        /// 数据概况
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetOrdertSatistics()
        {

            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<DataStatistics_Query>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            var model = statisticsModule.GetOrdertSatistics(query).FirstOrDefault();
            if (model == null)
            {
                return ApiResult.Failed("获取数据失败");
            }
            return ApiResult.Success("获取成功", model);
        }

        /// <summary>
        /// 销售情况
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetWeeklyOrder()
        {

            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<DataStatistics_Query>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            var model = statisticsModule.GetWeeklyOrder(query);
            if (model == null)
            {
                return ApiResult.Failed("获取数据失败");
            }
            return ApiResult.Success("获取成功", model);
        }


        /// <summary>
        /// 商品购买力TOP排行
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetGoosTop()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<DataStatistics_Query>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            var List = statisticsModule.GetGoosTop(query).Take(10);
            return ApiResult.Success("获取成功", List);
        }


        /// <summary>
        /// 商品购买力TOP排行导出
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public FileContentResult GetGoosTopToExcel()
        {
            var parms = RequestParm;
            DataStatistics_Query demodel = JsonConvert.DeserializeObject<DataStatistics_Query>(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 }
                },
            };
            slist.Add(header);

            try
            {
                demodel.TenantId = UserInfo.TenantId;
                demodel.MallBaseId = parms.MallBaseId;
                var list = statisticsModule.GetGoosTop(demodel);
                #region 组装数据
                int Num = 0;
                foreach (var item in list)
                {
                    Num++;
                    ExcelDataSource datarow = new ExcelDataSource()
                    {
                        ExcelRows = new List<ExcelColumn>(30) {
                            new ExcelColumn(value:Num.ToString()){ },
                        }
                    };
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.Name) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.PayMoney.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.BuyNum.ToString()) { });
                    slist.Add(datarow);
                }
                #endregion

                var byteData = ExcelTempLateHelper.ToExcelExtend(slist);

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

        }

        /// <summary>
        /// 用户购买力TOP排行
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMemberTop()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<DataStatistics_Query>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            var List = statisticsModule.GetMemberTop(query).Take(10);
            return ApiResult.Success("获取成功", List);
        }


        /// <summary>
        /// 用户购买力TOP排行导出
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public FileContentResult GetMemberTopToExcel()
        {
            var parms = RequestParm;
            DataStatistics_Query demodel = JsonConvert.DeserializeObject<DataStatistics_Query>(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 }
                },
            };
            slist.Add(header);

            try
            {
                demodel.TenantId = UserInfo.TenantId;
                demodel.MallBaseId = parms.MallBaseId;
                var list = statisticsModule.GetMemberTop(demodel);
                #region 组装数据
                int Num = 0;
                foreach (var item in list)
                {
                    Num++;
                    ExcelDataSource datarow = new ExcelDataSource()
                    {
                        ExcelRows = new List<ExcelColumn>(30) {
                            new ExcelColumn(value:Num.ToString()){ },
                        }
                    };
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.Name) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.PayMoney.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.BuyNum.ToString()) { });
                    slist.Add(datarow);
                }
                #endregion

                var byteData = ExcelTempLateHelper.ToExcelExtend(slist);

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

        }

        #endregion

        #region 销售统计
        /// <summary>
        ///销售统计列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSellPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            DataStatistics_Query demodel = JsonConvert.DeserializeObject<DataStatistics_Query>(RequestParm.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = statisticsModule.GetSellPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.CreateDate,
                x.GoodsNum,
                x.OrderNum,
                x.PayMoney,
                x.PayMemerNum
            });
            return ApiResult.Success("", pagelist);
        }

        [HttpPost]
        public ApiResult GetSellOrder()
        {

            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<DataStatistics_Query>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            var model = statisticsModule.GetSellOrder(query);
            if (model == null)
            {
                return ApiResult.Failed("获取数据失败");
            }
            return ApiResult.Success("获取成功", model);
        }



        /// <summary>
        /// 用户购买力TOP排行导出
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public FileContentResult GetSellExcel()
        {
            var parms = RequestParm;
            DataStatistics_Query demodel = JsonConvert.DeserializeObject<DataStatistics_Query>(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 }
                },
            };
            slist.Add(header);

            try
            {
                demodel.TenantId = UserInfo.TenantId;
                demodel.MallBaseId = parms.MallBaseId;
                var list = statisticsModule.GetSellExcel(demodel);
                #region 组装数据
                int Num = 0;
                foreach (var item in list)
                {
                    Num++;
                    ExcelDataSource datarow = new ExcelDataSource()
                    {
                        ExcelRows = new List<ExcelColumn>(30) {
                            new ExcelColumn(value:Num.ToString()){ },
                        }
                    };
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.CreateDate) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.GoodsNum.ToString()) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderNum.ToString()) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.PayMoney.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.PayMemerNum.ToString()) { });
                    slist.Add(datarow);
                }
                #endregion

                var byteData = ExcelTempLateHelper.ToExcelExtend(slist);

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

        }
        #endregion

        #region 损益核算表
        [HttpPost]
        [AllowAnonymous]
        public ApiResult GetOrderProfitLossList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            OrderStatistics_Query demodel = JsonConvert.DeserializeObject<OrderStatistics_Query>(RequestParm.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = statisticsModule.GetOrderProfitLossList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);

            foreach (var item in list)
            {
                item.ALLCommission = item.CostFreight + item.CostMoney + item.PackingMoney + item.GoodsFreight + item.OneCommission + item.TwoCommission + 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);
            }
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list;
            return ApiResult.Success("", pagelist);
        }



        /// <summary>
        /// 导出订单损益核算
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public FileContentResult GetOrderProfitLossExcel()
        {
            var parms = RequestParm;
            OrderStatistics_Query demodel = JsonConvert.DeserializeObject<OrderStatistics_Query>(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 }
                },
            };
            slist.Add(header);

            try
            {
                demodel.TenantId = UserInfo.TenantId;
                demodel.MallBaseId = parms.MallBaseId;
                var 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.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.OneCommission.ToString("#0.00")) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.TwoCommission.ToString("#0.00")) { });
                    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(RequestParm)));
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }

        }



        #endregion
    }
}