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.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());
            Model.Entity.AppletWeChat.RB_Live_House demodel = JsonConvert.DeserializeObject<Model.Entity.AppletWeChat.RB_Live_House>(requestParm.msg.ToString());
            demodel.TenantId = requestParm.TenantId;
            demodel.MallBaseId = requestParm.MallBaseId;
            var list = appletWeChatModule.GetLiveHousePageList(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,
                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 "";
            }
        }
        #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;
            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(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>(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 }
                },
            };
            slist.Add(header);

            try
            {
                demodel.TenantId = requestParm.TenantId;
                demodel.MallBaseId = requestParm.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.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>
        /// <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(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;
            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);
            }

            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),//二级返佣小计
                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),//毛利小计
            };


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