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]
        [UseAction]
        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, string order,
            bool? ispush = null, int? type = null, string supplier_name = null, string purchase_user = null, string product_inner_code = null, bool? is_multiple_warehouse = false,int? is_replace_logistics = null,
            decimal? quantity_final_advise_price_max = null, decimal? quantity_final_advise_price_min = null,int? purchase_type_jit = 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,
                supplier_name = supplier_name,
                purchase_user = purchase_user,
                product_inner_code = product_inner_code,
                is_multiple_warehouse = is_multiple_warehouse.Value,
                is_replace_logistics = is_replace_logistics,
                quantity_final_advise_price_max = quantity_final_advise_price_max,
                quantity_final_advise_price_min = quantity_final_advise_price_min,
                purchase_type_jit = purchase_type_jit
            };

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

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

        /// <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]
        [BrowseLog("Bailun_aims", "访问【百伦自动周转系统】->【自动下单管理】->【采购建议列表】->【搜索】页面", 0)]
        public JsonResult DetailListSumFooter(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, string supplier_name = null, string purchase_user = null, string product_inner_code = null, bool is_multiple_warehouse = false, int? is_replace_logistics = null,
            decimal? quantity_final_advise_price_max = null, decimal? quantity_final_advise_price_min = null,int? purchase_type_jit = 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,
                supplier_name = supplier_name,
                purchase_user = purchase_user,
                product_inner_code = product_inner_code,
                isSum = true,
                is_multiple_warehouse = is_multiple_warehouse,
                is_replace_logistics = is_replace_logistics,
                quantity_final_advise_price_max = quantity_final_advise_price_max,
                quantity_final_advise_price_min = quantity_final_advise_price_min,
                purchase_type_jit = purchase_type_jit
            };

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

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

        /// <summary>
        /// 导出实时库存
        /// </summary>
        /// <param name="sku"></param>
        /// <param name="warehousecode"></param>
        /// <returns></returns>
        public FileResult Export(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, string supplier_name = null, string purchase_user = null, string product_inner_code = null, bool is_multiple_warehouse = false, int? is_replace_logistics = null,
           decimal? quantity_final_advise_price_max = null, decimal? quantity_final_advise_price_min = null,int? purchase_type_jit = 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,
                supplier_name = supplier_name,
                purchase_user = purchase_user,
                product_inner_code = product_inner_code,
                isSum = false,
                is_multiple_warehouse = is_multiple_warehouse,
                is_replace_logistics = is_replace_logistics,
                quantity_final_advise_price_max = quantity_final_advise_price_max,
                quantity_final_advise_price_min = quantity_final_advise_price_min,
                purchase_type_jit = purchase_type_jit
            };

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

            DataTable table = new DataTable();
            string[] cols = new string[] { "初始建议数", "系统建议数", "采购数量", "是否已推送","jit备货类型", "时间", "sku", "产品名称", "产品14日日均", "仓库编码","仓库名称","源仓库",
                 "内部商品编码", "商品建议采购", "商品14日日均", "商品moq", "日均加权销量","安全库存", "缺货","实时缺货", "调拨在途", "采购在途", "库存数",
                 "采购金额", "供应链长度", "供应商名称", "采购类型","采购员","突增关注","待发货百伦单号","7日日均","14日日均","30日日均"
            };
            foreach (var item in cols)
            {
                table.Columns.Add(item);
            }

            foreach (var itemData in list)
            {
                DataRow row = table.NewRow();
                row["7日日均"] = itemData.t_history_sevenday_sales;
                row["14日日均"] = itemData.t_history_fourteenday_sales;
                row["30日日均"] = itemData.t_history_thirtyday_sales;
                row["源仓库"] = itemData.source_warehouse_code_name_str;
                row["初始建议数"] = itemData.quantity_init_advise;
                row["系统建议数"] = itemData.quantity_final_advise;
                row["采购数量"] = itemData.quantity_actual;
                row["是否已推送"] = itemData.ispush == 1 ? "是" : "否";
                row["jit备货类型"] = itemData.purchase_type_jit_str;
                row["时间"] = itemData.create_time_str;
                row["sku"] = itemData.bailun_sku;
                row["产品名称"] = itemData.sku_name;
                row["产品14日日均"] = itemData.history_fourteenday_sales;
                row["仓库编码"] = itemData.warehouse_code;
                row["仓库名称"] = itemData.warehouse_name;
                row["内部商品编码"] = itemData.product_inner_code;
                row["商品建议采购"] = itemData.goods_quantity_init_advise;
                row["商品14日日均"] = itemData.goods_history_fourteenday_sales;
                row["商品moq"] = itemData.goods_moq;
                row["日均加权销量"] = itemData.daily_weighted_sales;
                row["安全库存"] = itemData.quantity_safe_inventory;
                row["缺货"] = itemData.quantity_out_stock;
                row["实时缺货"] = itemData.realtime_quantity_out_stock;
                row["调拨在途"] = itemData.quantity_transfer;
                row["采购在途"] = itemData.quantity_purchase;
                row["库存数"] = itemData.quantity_inventory;
                row["采购金额"] = itemData.quantity_final_advise_price;
                row["供应链长度"] = itemData.turnover_days;
                row["供应商名称"] = itemData.suppliers_name;
                row["采购类型"] = itemData.type_str;
                row["采购员"] = itemData.buyer_name;
                row["突增关注"] = itemData.sudden_increase;
                row["待发货百伦单号"] = itemData.bailun_order_ids;
                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>
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【自动下单管理】->【采购建议列表】->【保存】操作", 1)]
        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>
        [HttpPost]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【自动下单管理】->【采购建议列表】->【批量保存】操作", 1)]
        public JsonResult BatchSetQuantityActual([FromBody] BatchSetQuantityActualInputDataDto data)
        {
            try
            {
                PurchaseAdviseServices.BatchSetQuantityActual(data.datas);
                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>
        [BrowseLog("Bailun_aims", "访问【百伦自动周转系统】->【自动下单管理】->【采购建议列表】->【推送采购系统】页面", 0)]
        public JsonResult PushBuySys(int limit, int offset, int main_id, string sort, string sku, string warehousecode,
            DateTime? end_date, DateTime? start_date, string warehousetype, int? warehousearea, string order,
            bool? ispush = null, int? type = null, string supplier_name = null, string purchase_user = null, string product_inner_code = null, bool? is_multiple_warehouse = false, int? is_replace_logistics = null,
            decimal? quantity_final_advise_price_max = null, decimal? quantity_final_advise_price_min = null, int? purchase_type_jit = null)
        {
            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,
                    type = type,
                    supplier_name = supplier_name,
                    purchase_user = purchase_user,
                    product_inner_code = product_inner_code,
                    is_multiple_warehouse = is_multiple_warehouse.Value,
                    quantity_final_advise_price_max = quantity_final_advise_price_max,
                    quantity_final_advise_price_min = quantity_final_advise_price_min,
                    purchase_type_jit = purchase_type_jit,
                    is_replace_logistics = is_replace_logistics
                };

                var total = 0;
                var list = PurchaseAdviseServices.DetailList(m, 0, int.MaxValue, ref total);
                PurchaseAdviseServices.PushBuySys(1,list, AutoUtility.GetUser(), false);


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

        /// <summary>
        /// 删除采购建议
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [BrowseLog("Bailun_aims", "触发【百伦自动下单系统】->【自动下单管理】->【采购建议列表】->【删除采购建议】操作",2)]
        public JsonResult Del(int id)
        {
            try
            {
                PurchaseAdviseServices.Del(id);
                return new JsonResult(new
                {
                    success = true
                });

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



    }
}