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 Dapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace AutoTurnOver.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class CashFlowController : ControllerBase
    {
        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 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");
        }

        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
                };
                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
                });
            }

        }

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