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

namespace AutoTurnOver.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ExceptionReminderController : ControllerBase
    {
        [HttpGet]
        public JsonResult List(int limit, int offset, string order, string sort, string sku, string warehousecode, string warehousetype, int? warehousearea,
            bool? has_overdue = null, bool? has_confirm = null, bool? has_solve = null,int? err_type = null)
        {
            var m = new dc_auto_forecast_fluctuation_search_dto
            {
                sku = sku,
                warehouse_code = warehousecode,
                has_overdue = has_overdue,
                has_confirm = has_confirm,
                has_solve = has_solve,
                warehousetype = warehousetype,
                warehousearea = warehousearea,
                err_type = err_type
            };

            var total = 0;
            var service = new Services.ExceptionReminderServices();
            var list = service.List(m, offset, limit, ref total, order, sort);

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

        public FileResult Export(int limit, int offset, string order, string sort, string sku, string warehousecode, string warehousetype, int? warehousearea,
            bool? has_overdue = null, bool? has_confirm = null, bool? has_solve = null, int? err_type = null)
        {
            var m = new dc_auto_forecast_fluctuation_search_dto
            {
                sku = sku,
                warehouse_code = warehousecode,
                has_overdue = has_overdue,
                has_confirm = has_confirm,
                has_solve = has_solve,
                warehousetype = warehousetype,
                warehousearea = warehousearea,
                err_type = err_type
            };

            var total = 0;
            var service = new Services.ExceptionReminderServices();
            var list = service.List(m, 0, int.MaxValue, ref total, order, sort);

            DataTable table = new DataTable();
            string[] cols = new string[] { "Sku","中文名称","仓库编码","仓库名称","最近3日日均","异常类型","开始时间",
                "总缺货数","在途数量","采购员","预计到货","bi 采购单号","供应商","逾期状态",
                "结束时间","是否确认","确认人","预计解决时间",
                "处理方案","是否解决"
            };
            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.sku_title_cn;
                row["仓库编码"] = itemData.warehouse_code;
                row["仓库名称"] = itemData.warehouse_name;
                row["最近3日日均"] = itemData.avg_sales_three;
                row["异常类型"] = itemData.bailun_sku;
                row["开始时间"] = itemData.typeStr;

                row["总缺货数"] = itemData.quantity_out_stock;
                row["在途数量"] = itemData.ontheway_quantity;
                row["采购员"] = itemData.buyer_name;
                row["预计到货"] = itemData.estimated_arrival_time;
                row["bi 采购单号"] = itemData.purchase_id;
                row["供应商"] = itemData.deliver_name;
                row["逾期状态"] = itemData.is_overdue==1?"逾期":"未逾期";


                row["结束时间"] = itemData.end_time;
                row["是否确认"] = itemData.has_confirm==1?"是":"否";
                row["确认人"] = itemData.bl_operator;
                row["预计解决时间"] = itemData.forecast_solve_time;
                row["处理方案"] = itemData.remark;
                row["是否解决"] = itemData.has_solve == 1 ? "是" : "否";
                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">销售设置id</param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult Info(int id)
        {
            var m = new Services.ExceptionReminderServices().Info(id);

            return new JsonResult(m);
        }

        /// <summary>
        /// 确认异常
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Confirm([FromBody]dc_auto_forecast_fluctuation m)
        {
            try
            {
                var user = AutoUtility.GetUser();
                if (user == null) return null;
                new Services.ExceptionReminderServices().Confirm(m, user);
                return new JsonResult(new { success = true });
            }
            catch (Exception ex)
            {
                return new JsonResult(new { success = false, message = ex.Message });
            }
            
        }
    }
}