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

namespace AutoTurnOver.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ForecastTaskController : ControllerBase
    {
        #region 配置页面


        [HttpGet]
        [BrowseLog("Bailun_aims", "访问【百伦自动周转系统】->【现金流】->【预测现金流任务】->【搜索】页面", 0)]
        public JsonResult Page(int limit, int offset, string order, string sort, string bailun_sku)
        {
            var m = new dc_report_cash_flow_forecast_task_search_dto
            {
                bailun_sku = bailun_sku
            };

            var total = 0;
            var service = new Services.ForecastTaskServices();
            var list = service.Page(m, offset, limit, ref total);

            return new JsonResult(new
            {
                rows = list,
                total = total,
            });
        }

        [HttpPost]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【现金流】->【预测现金流任务】->【新增(修改)】->【保存】操作", 1)]
        public JsonResult Save([FromBody]dc_report_cash_flow_forecast_task_input_dto m)
        {
            try
            {
                new Services.ForecastTaskServices().Save(m);
                return new JsonResult(new
                {
                    success =true
                });
            }
            catch (Exception ex)
            {
                return new JsonResult(new
                {
                    success = false,
                    message  =ex.Message,
                    stack_trace = ex.StackTrace
                });
            }
          
           
        }


        [HttpGet]
        public JsonResult GetById(int id)
        {
            var m = new Services.ForecastTaskServices().GetById(id);

            return new JsonResult(m);
        }

        #endregion

        [HttpGet]
        public JsonResult GetInfo(int id)
        {
            var list = new Services.ForecastTaskServices().GetInfo(new report_cash_flow_view_forecast_task_search_dto {task_id = id });

            return new JsonResult(new
            {
                rows = list,
                total = 0,
            });
        }  
        
        [HttpGet]
        public JsonResult GetDate(int id)
        {
            var m = new Services.ForecastTaskServices().GetDate(id);

            return new JsonResult(m);
        }

        public FileResult Export(DateTime? btime, DateTime? etime, string data_type = null, int? type = null, int? view_type = 1,int? task_id= null)
        {
            var m = new dc_report_cash_flow_log_export_forecast_task_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,
                task_id = task_id,
                page = 1,
                rows = int.MaxValue,
                issum = false,
                view_type = view_type
            };


            var service = new Services.ForecastTaskServices();
            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");
        }


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

                var m = new dc_report_cash_flow_log_export_forecast_task_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,
                    task_id = task_id,
                    page = (offset / limit) + 1,
                    rows = limit,
                    issum = false,
                    sord = order,
                    sidx = sort,
                    view_type = view_type
                };


                var service = new Services.ForecastTaskServices();
                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 data_type = null, int? type = null, int? task_id = null)
        {
            var m = new dc_report_cash_flow_log_export_forecast_task_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,
                task_id = task_id,
                page = 1,
                rows = 1,
                issum = true
            };
            var total = 0;
            var service = new Services.ForecastTaskServices();
            var list = service.LogPage(m);

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