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;
using AutoTurnOver.DB;
using AutoTurnOver.Models.dc_base_purchase;

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([FromQuery] dc_auto_purchase_advise_detailed_search_dto m, [FromQuery]int limit, [FromQuery]int offset, [FromQuery] string sort, [FromQuery] string order)
        {
            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([FromQuery] dc_auto_purchase_advise_detailed_search_dto m, [FromQuery]int limit, [FromQuery]int offset, [FromQuery] string sort, [FromQuery] string order)
        {
            m.isSum = true;

            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 JsonResult Export([FromQuery] dc_auto_purchase_advise_detailed_search_dto m, [FromQuery]int limit, [FromQuery]int offset, [FromQuery] string sort, [FromQuery] string order)
        {

            try
            {
                var user = AutoUtility.GetUser();
                dc_task_download_dao.PushData<dc_auto_purchase_advise_detailed_search_dto>(new dc_task_download
                {
                    parameter = m.ToJson(),
                    task_name = "采购建议"
                }, user);
                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", "触发【百伦自动周转系统】->【自动下单管理】->【采购建议列表】->【保存】操作", 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>
        [HttpPost]
        [BrowseLog("Bailun_aims", "触发【百伦自动周转系统】->【自动下单管理】->【采购建议列表】->【设置是否需要优先】操作", 1)]
        public JsonResult UpdatePriorityStorageCapacity([FromBody] SetPriorityStorageCapacityInputDto data)
        {
            try
            {
                PurchaseAdviseServices.UpdatePriorityStorageCapacity(data);
                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([FromQuery] dc_auto_purchase_advise_detailed_search_dto m)
        {
            try
            {
                m.ispush = false;

                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, 
                    stack_trace = ex.StackTrace
                });
            }
        }

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


        [HttpGet]
        [BrowseLog("Bailun_aims", "触发【百伦自动下单系统】->【自动下单管理】->【退货汇总】->【查询】操作", 0)]
        public string ReturnGoodsList([FromQuery] dc_aims_return_goods_search_dto m, [FromQuery]int limit, [FromQuery]int offset )
        {
            var total = 0;
            var list = new  PurchaseAdviseServices().ReturnGoodsList(m, offset, limit, ref total);

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

        [HttpGet]
        public JsonResult GetToDayDatas()
        {
            var list = new PurchaseAdviseServices().GetToDayDatas();
            return new JsonResult(list);
        }


        public JsonResult ExportReturnGoods([FromQuery] dc_auto_purchase_advise_detailed_search_dto m, [FromQuery]int limit, [FromQuery]int offset, [FromQuery] string sort, [FromQuery] string order)
        {

            try
            {
                var user = AutoUtility.GetUser();
                dc_task_download_dao.PushData<dc_auto_purchase_advise_detailed_search_dto>(new dc_task_download
                {
                    parameter = m.ToJson(),
                    task_name = "退货汇总"
                }, user);
                return new JsonResult(new { success = true });
            }
            catch (Exception ex)
            {
                return new JsonResult(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 分页查询推送采购系统sku
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult GetPurchaseAdviseSkuPageList([FromQuery] dc_purchase_advise_sku_search_dto input)
        {
            var total = 0;
            var list =new PurchaseAdviseServices().GetPurchaseAdviseSkuPageList(input, ref total);
            return new JsonResult(new
            {
                rows = list,
                total = total,
            });
        }

        /// <summary>
        /// 导出推送采购系统sku
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [NoLogin]
        public FileResult PurchaseAdviseSkuExport([FromQuery] dc_purchase_advise_sku_search_dto input)
        {
            var total = 0;
            input.IsPage = false;
            var list = new PurchaseAdviseServices().GetPurchaseAdviseSkuPageList(input, ref total);

            DataTable table = new DataTable();
            string[] cols = new string[] {
                "采购计划单号", "供应商货号sku", "日期", "仓库编码","仓库名称", "Sku","Sku名称", "单价", "下单数", "下单时间", "推单时间","供应商名称"
            };
            foreach (var item in cols)
            {
                table.Columns.Add(item);
            }

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

                row["采购计划单号"] = itemData.plan_nos;
                row["供应商货号sku"] = itemData.supplier_sku;
                row["日期"] = itemData.create_order_date;
                row["仓库编码"] = itemData.warehouse_code;
                row["仓库名称"] = itemData.warehouse_name;
                row["Sku"] = itemData.bailun_sku;
                row["Sku名称"] = itemData.sku_title_cn;
                row["单价"] = itemData.unit_price;
                row["下单数"] = itemData.quantity_actual;
                row["下单时间"] = itemData.push_dateStr;
                row["推单时间"] = itemData.push_dateStr;
                row["供应商名称"] = itemData.suppliers_name;
                table.Rows.Add(row);
            }

            var fileName = AppContext.BaseDirectory + @"Result\RealtimeStock\推采购sku计划列表.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", "推采购sku计划列表.csv");
        }
    }
}