using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using AutoTurnOver.Common;
using AutoTurnOver.Models;
using AutoTurnOver.Services;
using AutoTurnOver.Utility;
using Dapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using AutoTurnOver.Utility;

namespace AutoTurnOver.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class CashFlowController : ControllerBase
    {
        [BrowseLog("Bailun_aims", "访问【百伦自动周转系统】->【现金流】->【报表】->【搜索】页面", 0)]
        public JsonResult GetView(DateTime? btime, DateTime? etime, string platform_type, string web_site, string bailun_sku, string warehouse_code)
        {
            report_cash_flow_view_search_dto search_data = new report_cash_flow_view_search_dto
            {
                etime = etime,
                btime = btime,
                web_site = web_site,
                platform_type = platform_type,
                warehouse_code = warehouse_code,
                bailun_sku = bailun_sku
            };

            var list = new CashFlowServices().GetView(search_data);
            return new JsonResult(new
            {
                rows = list,
                total = 0,
            });
        }

        public FileResult ExportView(DateTime? btime, DateTime? etime, string platform_type, string web_site, string bailun_sku, string warehouse_code)
        {
            report_cash_flow_view_search_dto search_data = new report_cash_flow_view_search_dto
            {
                etime = etime,
                btime = btime,
                web_site = web_site,
                platform_type = platform_type,
                warehouse_code = warehouse_code,
                bailun_sku = bailun_sku
            };

            var e_btime = DateTime.Now.AddDays(-8).ToDayHome();
            var e_etime = DateTime.Now.AddDays(-1).ToDayEnd();
            if (search_data.btime != null)
            {
                e_btime = search_data.btime.Value.ToDayHome();
            }
            if (search_data.etime != null)
            {
                e_etime = search_data.etime.Value.ToDayEnd();
            }

            var list = new CashFlowServices().GetView(search_data);

            DataTable table = new DataTable();
            string[] cols = new string[] { "类型", "汇总-发生", "汇总-支付"};
            foreach (var item in cols)
            {
                table.Columns.Add(item);
            }
            var col_this_date =e_etime;
            while (col_this_date.ToDayHome()> e_btime.ToDayHome())
            {
                table.Columns.Add($"{col_this_date.ToString("MM-dd")}-发生");
                table.Columns.Add($"{col_this_date.ToString("MM-dd")}-支付");
                col_this_date = col_this_date.AddDays(-1);
            }


            foreach (var itemDataD in list)
            {
                DataRow row = table.NewRow();
                var itemData = (IDictionary<string, object>)itemDataD;
                row["类型"] = itemData["date_type_str"];
                row["汇总-发生"] = itemData["v_occur_汇总"];
                row["汇总-支付"] = itemData["v_pay_汇总"];

                var row_this_date = e_etime;
                while (row_this_date.ToDayHome() > e_btime.ToDayHome())
                {
                    row[$"{row_this_date.ToString("MM-dd")}-发生"] =itemData["v_occur_" + $"{row_this_date.Month}-{row_this_date.Day}"];
                    row[$"{row_this_date.ToString("MM-dd")}-支付"] =itemData["v_pay_" + $"{row_this_date.Month}-{row_this_date.Day}"];
                    row_this_date = row_this_date.AddDays(-1);
                }

                table.Rows.Add(row);
            }

            var fileName = AppContext.BaseDirectory + @"Result\RealtimeStock\现金流报表.csv";

            DataTableHelper.SaveCSV(table, fileName);

            var memory = new MemoryStream();
            using (var stream = new FileStream(fileName, FileMode.Open))
            {
                stream.CopyTo(memory);
            }
            memory.Position = 0;
            return File(memory, "text/csv", "现金流报表.csv");
        }

        public FileResult Export(DateTime? btime, DateTime? etime, string bailun_sku, string data_type = null, int? type = null, string platform_type = null, string warehouse_code = null, string web_site = "", int? view_type = 1)
        {
            var m = new dc_report_cash_flow_log_export_page_search_dto
            {
                data_type = string.IsNullOrWhiteSpace(data_type) ? new List<int> { } : data_type.Split(',').Select(s => int.Parse(s)).ToList(),
                btime = btime,
                etime = etime,
                type = type,
                bailun_sku = bailun_sku,
                page =1,
                rows = int.MaxValue,
                platform_type = platform_type,
                issum = false,
                warehouse_code = warehouse_code,
                web_site = web_site,
                view_type = view_type
            };


            var service = new Services.CashFlowServices();
            var list = service.LogPage(m).Items;

            DataTable table = new DataTable();
            string[] cols = new string[] { "Sku","仓库编码","仓库名称","平台","站点","数据类型","金额","时间","相关单号","备注"
            };
            foreach (var item in cols)
            {
                table.Columns.Add(item);
            }

            foreach (var itemData in list)
            {
                DataRow row = table.NewRow();

                row["Sku"] = itemData.bailun_sku;
                row["仓库编码"] = itemData.warehouse_code;
                row["仓库编码"] = itemData.warehouse_code;
                row["仓库名称"] = itemData.warehouse_name;
                row["平台"] = itemData.platform_type;
                row["平台"] = itemData.web_site;
                row["数据类型"] = itemData.data_type_str;
                row["时间"] = itemData.show_time;
                row["相关单号"] = itemData.no;
                row["备注"] = itemData.remarks;
                row["金额"] = itemData.val;

                table.Rows.Add(row);
            }

            var fileName = AppContext.BaseDirectory + @"Result\RealtimeStock\现金流明细.csv";

            DataTableHelper.SaveCSV(table, fileName);

            var memory = new MemoryStream();
            using (var stream = new FileStream(fileName, FileMode.Open))
            {
                stream.CopyTo(memory);
            }
            memory.Position = 0;
            return File(memory, "text/csv", "现金流明细.csv");
        }
        [BrowseLog("Bailun_aims", "访问【百伦自动周转系统】->【现金流】->【仓库sku现金流列表】->【搜索】页面", 0)]
        public JsonResult GetSkuView(int? data_type, string sku_label, string bailun_sku, int offset, int limit, string order, string sort, string buyer_name, string warehousecode, string supplier_name, string warehousetype, int? warehousearea, int? monitor_status = null, string product_type = null)
        {
            try
            {
                var m = new dc_report_cash_flow_sku_group_search_dto
                {
                    bailun_sku = bailun_sku,
                    page = (offset / limit) + 1,
                    rows = limit,
                    sidx = sort,
                    sord = order,
                    buyer_name = buyer_name,
                    sku_label = string.IsNullOrWhiteSpace(sku_label) ? null : WebUtility.UrlDecode(sku_label),
                    data_type = data_type,
                    supplier_name = supplier_name,
                    product_type = product_type,
                    warehouse_code = warehousecode,
                    monitor_status = monitor_status,
                    warehousearea = warehousearea,
                    warehousetype = warehousetype,
                    is_sum = false
                };
                var services = new CashFlowServices();
                var page_data = services.SkuView(m);
                return new JsonResult(new
                {
                    rows = page_data.Items,
                    total = page_data.TotalItems
                });
            }
            catch (Exception ex)
            {
                return new JsonResult(new
                {
                    message = ex.Message,
                    stack_trace = ex.StackTrace
                });
            }

        }

        public JsonResult SkuViewSumFooter(int? data_type, string sku_label, string bailun_sku, int offset, int limit, string order, string sort, string buyer_name, string warehousecode, string supplier_name, string warehousetype, int? warehousearea, int? monitor_status = null, string product_type = null)
        {
            var m = new dc_report_cash_flow_sku_group_search_dto
            {
                bailun_sku = bailun_sku,
                page = 1,
                rows = 1,
                sidx = sort,
                sord = order,
                buyer_name = buyer_name,
                sku_label = string.IsNullOrWhiteSpace(sku_label) ? null : WebUtility.UrlDecode(sku_label),
                data_type = data_type,
                supplier_name = supplier_name,
                product_type = product_type,
                warehouse_code = warehousecode,
                monitor_status = monitor_status,
                warehousearea = warehousearea,
                warehousetype = warehousetype,
                is_sum = true
            };
            var services = new CashFlowServices();
            var list = services.SkuView(m);

            return new JsonResult(list == null || list.Items.Count <= 0 ? new dc_report_cash_flow_sku_group_dto() : list.Items[0]);
        }

        public FileResult ExportSkuView(int? data_type, string sku_label, string bailun_sku, int offset, int limit, string order, string sort, string buyer_name, string warehousecode, string supplier_name, string warehousetype, int? warehousearea, int? monitor_status = null, string product_type = null)
        {
            var m = new dc_report_cash_flow_sku_group_search_dto
            {
                bailun_sku = bailun_sku,
                page = 1,
                rows = int.MaxValue,
                sidx = sort,
                sord = order,
                buyer_name = buyer_name,
                sku_label = string.IsNullOrWhiteSpace(sku_label) ? null : WebUtility.UrlDecode(sku_label),
                data_type = data_type,
                supplier_name = supplier_name,
                product_type = product_type,
                warehouse_code = warehousecode,
                monitor_status = monitor_status,
                warehousearea = warehousearea,
                warehousetype = warehousetype
            };
            var services = new CashFlowServices();
            var list = services.SkuView(m).Items;

            DataTable table = new DataTable();
            string[] cols = new string[] { "sku","仓库编码","仓库名称","名称","累计值","本月结余","本月正数","本月负数","上月结余","上月正数","上月负数","采购员","可用库存"
                ,"可用库存金额","在途数量","在途金额","7日日均","14日日均","30日日均","停售状态"
            };
            foreach (var item in cols)
            {
                table.Columns.Add(item);
            }

            foreach (var itemData in list)
            {
                DataRow row = table.NewRow();

                row["sku"] = itemData.bailun_sku;
                row["仓库编码"] = itemData.warehouse_code;
                row["仓库名称"] = itemData.warehouse_name;
                row["名称"] = itemData.sku_name;
                row["累计值"] = itemData.balance;
                row["本月结余"] = itemData.current_balance;
                row["本月正数"] = itemData.current_income;
                row["本月负数"] = itemData.current_expend;
                row["上月结余"] = itemData.last_balance;
                row["上月正数"] = itemData.last_income;
                row["上月负数"] = itemData.last_expend;
                row["采购员"] = itemData.buyer_name;
                row["可用库存"] = itemData.usable_stock;
                row["可用库存金额"] = itemData.stock_amount;
                row["在途数量"] = itemData.on_the_way;
                row["在途金额"] = itemData.on_the_way_amount;
                row["7日日均"] = itemData.history_sevenday_sales;
                row["14日日均"] = itemData.history_fourteenday_sales;
                row["30日日均"] = itemData.history_thirtyday_sales;
                row["停售状态"] = itemData.sku_status==1? "停售" : "在售";
               

                table.Rows.Add(row);
            }

            var fileName = AppContext.BaseDirectory + @"Result\RealtimeStock\现金流明细.csv";

            DataTableHelper.SaveCSV(table, fileName);

            var memory = new MemoryStream();
            using (var stream = new FileStream(fileName, FileMode.Open))
            {
                stream.CopyTo(memory);
            }
            memory.Position = 0;
            return File(memory, "text/csv", "现金流明细.csv");
        }

        [HttpGet]
        public JsonResult LogPage(int limit, int offset, string order, string sort, DateTime? btime, DateTime? etime, string bailun_sku, string data_type = null, int? type = null, string platform_type = null, string warehouse_code = null, string web_site = "", int? view_type = 1)
        {
            try
            {

                var m = new dc_report_cash_flow_log_export_page_search_dto
                {
                    data_type = string.IsNullOrWhiteSpace(data_type) ? new List<int> { } : data_type.Split(',').Select(s => int.Parse(s)).ToList(),
                    btime = btime,
                    etime = etime,
                    type = type,
                    bailun_sku = bailun_sku,
                    page = (offset / limit) + 1,
                    rows = limit,
                    platform_type = platform_type,
                    issum = false,
                    sord = order,
                    sidx = sort,
                    warehouse_code = warehouse_code,
                    web_site = web_site,
                    view_type = view_type
                };


                var service = new Services.CashFlowServices();
                var list = service.LogPage(m);
                var total = list.TotalItems;
                return new JsonResult(new
                {
                    rows = list.Items,
                    total = total,
                    pagecount = list.TotalPages
                });
            }
            catch (Exception ex)
            {
                return new JsonResult(new
                {
                    message = ex.Message,
                    stack_trace = ex.StackTrace
                });
            }

        }

        public JsonResult LogPageSumFooter(DateTime? btime, DateTime? etime, string bailun_sku, string data_type = null, int? type = null, string platform_type = null, string warehouse_code = null, string web_site = "")
        {
            var m = new dc_report_cash_flow_log_export_page_search_dto
            {
                data_type = string.IsNullOrWhiteSpace(data_type) ? new List<int> { } : data_type.Split(',').Select(s => int.Parse(s)).ToList(),
                btime = btime,
                etime = etime,
                type = type,
                bailun_sku = bailun_sku,
                page =1,
                rows = 1,
                platform_type = platform_type,
                issum = true,
                warehouse_code = warehouse_code,
                web_site = web_site
            };
            var total = 0;
            var service = new Services.CashFlowServices();
            var list = service.LogPage(m);

            return new JsonResult(list == null || list.Items.Count <= 0 ? new  dc_report_cash_flow_log_dto() : list.Items[0]);
        }
    }
}