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

namespace AutoTurnOver.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class PurchaseAdviseController : ControllerBase
    {
        /// <summary>
        /// 采购建议列表
        /// </summary>
        /// <param name="limit"></param>
        /// <param name="offset"></param>
        /// <param name="has_push"></param>
        /// <param name="sort"></param>
        /// <param name="end_date"></param>
        /// <param name="start_date"></param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult List(int limit, int offset, bool? has_push, string sort, DateTime? end_date, DateTime? start_date, bool? is_outofstock)
        {
            var m = new dc_auto_purchase_advise_search_dto
            {
                end_date = end_date,
                has_push = has_push,
                start_date = start_date,
                is_outofstock = is_outofstock
            };

            var total = 0;
            var list = PurchaseAdviseServices.List(m, offset, limit, ref total);

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

        /// <summary>
        /// 采购建议列表
        /// </summary>
        /// <param name="limit"></param>
        /// <param name="offset"></param>
        /// <param name="has_push"></param>
        /// <param name="sort"></param>
        /// <param name="end_date"></param>
        /// <param name="start_date"></param>
        /// <returns></returns>
        [HttpGet]
        public string DetailList(int limit, int offset, int main_id, string sort, string sku, string warehousecode, DateTime? end_date, DateTime? start_date, string warehousetype, int? warehousearea, bool? ispush = null,int? type = null)
        {
            var m = new dc_auto_purchase_advise_detailed_search_dto
            {
                main_id = main_id,
                sku = sku,
                warehouse_code = warehousecode,
                end_date = end_date,
                start_date = start_date,
                warehousearea = warehousearea,
                warehousetype = warehousetype,
                ispush = ispush,
                type = type
            };

            var total = 0;
            var list = PurchaseAdviseServices.DetailList(m, offset, limit, ref total);

            return new
            {
                rows = list,
                total = total,
            }.ToJson(false);
        }

        /// <summary>
        /// 导出实时库存
        /// </summary>
        /// <param name="sku"></param>
        /// <param name="warehousecode"></param>
        /// <returns></returns>
        public FileResult Export(int main_id, string sort, string sku, string warehousecode, DateTime? end_date, DateTime? start_date, string warehousetype, int? warehousearea, bool? ispush = null)
        {
            var m = new dc_auto_purchase_advise_detailed_search_dto
            {
                main_id = main_id,
                sku = sku,
                warehouse_code = warehousecode,
                end_date = end_date,
                start_date = start_date,
                warehousearea = warehousearea,
                warehousetype = warehousetype,
                ispush = ispush
            };

            var total = 0;
            var list = PurchaseAdviseServices.DetailList(m, 0, int.MaxValue, ref total);

            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["时间"] = itemData.create_time_str;
                row["sku"] = itemData.bailun_sku;
                row["产品名称"] = itemData.sku_name;
                row["仓库编码"] = itemData.warehouse_code;
                row["仓库名称"] = itemData.warehouse_name;
                row["初始建议数"] = itemData.quantity_init_advise;
                row["建议采购数量"] = itemData.quantity_final_advise;
                row["实际下单数量"] = itemData.quantity_actual;
                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");
        }

        /// <summary>
        /// 设置采购数量
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public JsonResult SetQuantityActual(int id, int quantity_actual)
        {
            try
            {
                PurchaseAdviseServices.SetQuantityActual(id, quantity_actual);
                return new JsonResult(new
                {
                    success = true
                });
            }
            catch (Exception ex)
            {
                return new JsonResult(new
                {
                    success = false,
                    message = ex.Message
                });
            }
        }

        /// <summary>
        /// 推送采购计划
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public JsonResult PushBuySys(int main_id, string sort, string sku, string warehousecode, DateTime? end_date, DateTime? start_date, string warehousetype, int? warehousearea)
        {
            try
            {
                var m = new dc_auto_purchase_advise_detailed_search_dto
                {
                    main_id = main_id,
                    sku = sku,
                    warehouse_code = warehousecode,
                    end_date = end_date,
                    start_date = start_date,
                    warehousearea = warehousearea,
                    warehousetype = warehousetype,
                    ispush = false
                };

                var total = 0;
                var list = PurchaseAdviseServices.DetailList(m, 0, int.MaxValue, ref total);
                foreach (var item in list.GroupBy(s=>s.type))
                {
                    PurchaseAdviseServices.PushBuySys(item.ToList(), item.Key);
                }
                
                
                return new JsonResult(new
                {
                    success = true
                });
            }
            catch (Exception ex)
            {
                return new JsonResult(new
                {
                    success = false,
                    message = ex.Message
                });
            }
        }

        /// <summary>
        /// 查询采购建议
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public JsonResult DetailInfo(string sku, string warehousecode, DateTime dateTime)
        {
            try
            {
                return new JsonResult(new
                {
                    success = true,
                    data = PurchaseAdviseServices.DetailInfo(sku, warehousecode, dateTime)
                });

            }
            catch (Exception ex)
            {
                return new JsonResult(new
                {
                    success = false,
                    message = ex.Message
                });
            }
        }


    }
}