using Edge.Core.Domain.FccOrderInfo.Input;
using Edge.Core.Domain.FccOrderInfo.Output;
using FccLite.Web.Repositories.FccOrderInfo;
using FccLite.Web.Repositories.FccStationInfo;
using Microsoft.AspNetCore.Mvc;
using OfficeOpenXml;

namespace FccLite.Web.Services.FccOrderInfo
{
    public class OrderInfoService : IOrderInfoService
    {
        static NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
        private readonly IOrderInfoReposity _orderInfoReposity;
        private readonly IStationRepository _stationRepository;

        private readonly string[] tableTitle = { "流水号", "油站", "油机号", "油枪", "油品", "单价", "升数", "金额", "挂枪时间", "交易时间", "支付方式", "支付状态", "支付用户" };
        private readonly string[] prepaytTableTitle = { "订单id","云端订单id","流水号","油站", "油机号", "油枪", "油品", "单价", "升数", "金额", "实付金额","实加升数","退款金额",
            "挂枪时间", "交易时间", "支付方式","授权状态","支付状态", "支付用户","手机号", };
        private readonly Dictionary<int, string> _afterPayType = new Dictionary<int, string>
        {
            {0,"未支付" },
            {1,"已支付" }
        };

        public OrderInfoService(IOrderInfoReposity orderInfoReposity,IStationRepository stationRepository) 
        {
            _orderInfoReposity = orderInfoReposity;
            _stationRepository = stationRepository;
        }

        

        public async Task<OrderInfoOutput> GetPage(OrderInfoPageInput orderInfoPageInput)
        {
            IEnumerable<OrderInfo> enumerable = await _orderInfoReposity.GetPage(orderInfoPageInput);
            List<OrderInfo> orderInfos = enumerable.ToList();
            return new OrderInfoOutput()
            {
                Total = orderInfos.Count,
                List = orderInfos
            };
        }

        /// <summary>
        /// 后支付订单下载excel
        /// </summary>
        /// <param name="orderInfoPageInput"></param>
        /// <returns></returns>
        public async Task<byte[]> DownloadAfterPayOrderExcel(OrderInfoPageInput orderInfoPageInput)
        {
            IEnumerable<OrderInfo> enumerable = await _orderInfoReposity.GetOrderFilter(orderInfoPageInput);
            try
            {
                var package = new ExcelPackage();
                ExcelWorksheet excelWorksheet = package.Workbook.Worksheets.Add("Sheet1");

                for (int index = 0; index < tableTitle.Length; index++)
                {
                    excelWorksheet.Cells[1, index+1].Value = tableTitle[index];
                }

                using (var range = excelWorksheet.Cells[1, 1, 1, tableTitle.Length])
                {
                    range.Style.Font.Bold = true;
                }

                int row = 2;
                decimal allVolume = 0;
                decimal allAmount = 0;
                foreach (var order in enumerable)
                {
                    excelWorksheet.Cells[row, 1].Value = order.Ttc;
                    excelWorksheet.Cells[row, 2].Value = order.StationName;
                    excelWorksheet.Cells[row, 3].Value = order.MachineName;
                    excelWorksheet.Cells[row, 4].Value = order.NozzleNum;
                    excelWorksheet.Cells[row, 5].Value = order.OilName;
                    excelWorksheet.Cells[row, 6].Value = order.Price;
                    excelWorksheet.Cells[row, 7].Value = order.Volume;
                    excelWorksheet.Cells[row, 8].Value = order.Amount;
                    excelWorksheet.Cells[row, 9].Value = order.EndTime != null ? order.EndTime?.ToString("yyyy-MM-dd HH:mm:ss") : "";
                    excelWorksheet.Cells[row, 10].Value = order.PaymentTime != null ? order.PaymentTime?.ToString("yyyy-MM-dd HH:mm:ss") : "";
                    excelWorksheet.Cells[row, 11].Value = order.PaymentName;

                    string payTypeStr = "未知状态";
                    _afterPayType.TryGetValue(order.PaymentStatus, out payTypeStr);
                    excelWorksheet.Cells[row, 12].Value = payTypeStr;

                    excelWorksheet.Cells[row, 13].Value = order.UserName;

                    allVolume += order.Volume;
                    allAmount += order.Amount;
                    row++;
                }
                excelWorksheet.Cells[row, 7].Value = allVolume;
                excelWorksheet.Cells[row, 8].Value = allAmount;

                return package.GetAsByteArray();
            } catch(Exception e)
            {
                Console.WriteLine(e);
                Logger.Error($"报错：{e.Message}");
            }

            return new byte[0];
        }

        /// <summary>
        /// 预支付获取订单页
        /// </summary>
        /// <param name="orderInfoPageInput"></param>
        /// <returns></returns>
        public async Task<PrepayOrderInfoOutput> GetPrepayPage(OrderInfoPageInput orderInfoPageInput)
        {
            IEnumerable<OrderInfo> enumerable = await _orderInfoReposity.GetPage(orderInfoPageInput);
            List<PrepayOrderInfo> prepayOrderInfos = enumerable.Select(order => new PrepayOrderInfo(order)).ToList();

            return new PrepayOrderInfoOutput()
            {
                Total = prepayOrderInfos.Count,
                List = prepayOrderInfos
            };
        }

        /// <summary>
        /// 预支付下载订单excel
        /// </summary>
        /// <param name="orderInfoPageInput"></param>
        /// <returns></returns>
        public async Task<byte[]> DownloadPrepayOrderExcel(OrderInfoPageInput orderInfoPageInput)
        {
            IEnumerable<OrderInfo> enumerable = await _orderInfoReposity.GetOrderFilter(orderInfoPageInput);
            List<PrepayOrderInfo> prepayOrderInfos = enumerable.Select(order => new PrepayOrderInfo(order)).ToList();
            try
            {
                var package = new ExcelPackage();
                ExcelWorksheet excelWorksheet = package.Workbook.Worksheets.Add("Sheet1");

                for (int index = 0; index < prepaytTableTitle.Length; index++)
                {
                    excelWorksheet.Cells[1, index + 1].Value = prepaytTableTitle[index];
                }

                using (var range = excelWorksheet.Cells[1, 1, 1, prepaytTableTitle.Length])
                {
                    range.Style.Font.Bold = true;
                }

                int row = 2;
                decimal allVolume = 0;
                decimal allAmount = 0;
                decimal allAmountPayable = 0;
                decimal allVolumePayable = 0;
                decimal allRefundAmount = 0;
                foreach (var order in prepayOrderInfos)
                {
                    excelWorksheet.Cells[row, 1].Value = order.Id;
                    excelWorksheet.Cells[row, 2].Value = order.CloundOrderId;
                    excelWorksheet.Cells[row, 3].Value = order.Ttc;
                    excelWorksheet.Cells[row, 4].Value = order.StationName;
                    excelWorksheet.Cells[row, 5].Value = order.MachineName;
                    excelWorksheet.Cells[row, 6].Value = order.NozzleNum;
                    excelWorksheet.Cells[row, 7].Value = order.OilName;
                    excelWorksheet.Cells[row, 8].Value = order.Price;
                    excelWorksheet.Cells[row, 9].Value = order.Volume;
                    excelWorksheet.Cells[row, 10].Value = order.Amount;
                    excelWorksheet.Cells[row, 11].Value = order.AmountPayable;
                    excelWorksheet.Cells[row, 12].Value = order.VolumePayable;
                    excelWorksheet.Cells[row, 13].Value = order.RefundAmount;
                    excelWorksheet.Cells[row, 14].Value = order.EndTime != null ? order.EndTime?.ToString("yyyy-MM-dd HH:mm:ss") : "";
                    excelWorksheet.Cells[row, 15].Value = order.PaymentTime != null ? order.PaymentTime?.ToString("yyyy-MM-dd HH:mm:ss") : "";
                    excelWorksheet.Cells[row, 16].Value = order.PaymentName;
                    excelWorksheet.Cells[row, 17].Value = order.AuthorizationStatus;
                    excelWorksheet.Cells[row, 18].Value = order.PaymentStatus;
                    excelWorksheet.Cells[row, 19].Value = order.UserName;
                    excelWorksheet.Cells[row, 20].Value = order.PhoneNumber;

                    allVolume += order.Volume;
                    allAmount += order.Amount;
                    allAmountPayable += order.AmountPayable ?? 0;
                    allVolumePayable += order.VolumePayable ?? 0;
                    allRefundAmount += order.RefundAmount ?? 0;
                    row++;
                }
                excelWorksheet.Cells[row, 9].Value = allVolume;
                excelWorksheet.Cells[row, 10].Value = allAmount;
                excelWorksheet.Cells[row, 11].Value = allAmount;
                excelWorksheet.Cells[row, 12].Value = allAmount;
                excelWorksheet.Cells[row, 13].Value = allAmount;

                return package.GetAsByteArray();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                Logger.Error(e.Message);
            }

            return new byte[0];
        }
    }
}
