using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Bailun.DC.Models;
using Bailun.ServiceFabric.Authorize;
using Bailun.ServiceFabric.Core.Extension;
using Bailun.ServiceFabric.Core.Extension.HttpContext;
using Bailun.ServiceFabric.Extension;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Linq;

namespace Bailun.DC.Web.Areas.Reports.Controllers
{
    /// <summary>
    /// 在途相关
    /// </summary>
    [Area("Reports")]
    public class OnWayController : Base.BaseController
    {
        private readonly IHostingEnvironment _hostingEnvironment;

        public OnWayController(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }

        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 调拨在途明细
        /// </summary>
        /// <returns></returns>
        public ActionResult ListAllot()
        {
            return View();
        }

        /// <summary>
        /// 调拨在途明细
        /// </summary>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        public string ListAllotJson(BtTableParameter parameter,string orderno,string sku,string warehousetype,string warehousecode)
        {
            var total = 0;
            var companyid = HttpContextHelper.Current?.User.GetCompanyId().ToInt32();

            var _service = new Services.AllotServices();
            var obj = _service.ListAllotOnWay(parameter, orderno, sku, warehousetype, warehousecode, ref total);
            var list = obj.Select(a=> new {
                a.code,
                a.deliverycount,
                a.onwaycount,
                a.schedulecode,
                a.sku,
                a.sourcewareno,
                a.sourcewarename,
                stateid = Enum.GetName(typeof(Models.Allot.EnumAllotStatus),a.stateid),
                a.storagecount,
                a.targetwareno,
                a.targetwarename
            });

            var objCount = _service.ListAllotOnWayCount(orderno, sku, warehousetype, warehousecode);

            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = list,
                companyid = companyid,
                isexport = Services.UserAuthorityServices.checkUserExportAuthority("ExportAllotOnWay", HttpContextHelper.Current.User.GetUserName()),
                count_row = new
                {
                    sku = "总计",
                    objCount.deliverycount,
                    objCount.storagecount,
                    objCount.onwaycount
                }
            });
        }

        /// <summary>
        /// 导出调拨在途明细
        /// </summary>
        /// <param name="orderno">调拨单号</param>
        /// <param name="sku">sku</param>
        /// <param name="warehousetype">目的仓库类型</param>
        /// <param name="warehousecode">目的仓库编码</param>
        /// <returns></returns>
        public ActionResult ExportListAllot(string orderno, string sku, string warehousetype, string warehousecode)
        {
            var total = 0;
            var _service = new Services.AllotServices();
            var obj = _service.ListAllotOnWay(new BtTableParameter { limit=0,offset=1}, orderno, sku, warehousetype, warehousecode, ref total);

            var colNames = new List<string> { "调拨单号", "计划单号", "起始仓库", "目的仓库名称", "sku", "调拨数量", "入库数量", "在途数量", "调拨状态"};

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.code + "|" + item.schedulecode + "|" + item.sourcewarename + "|" + item.targetwarename + "|" + item.sku + "|" +
                    item.deliverycount + "|" + item.storagecount+"|"+item.onwaycount+"|"+ Enum.GetName(typeof(Models.Allot.EnumAllotStatus), item.stateid)
                    );
            }

            var guid = Guid.NewGuid().ToString();
            var filename = "调拨在途明细 " + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");
        }

        /// <summary>
        /// 调拨计划在途
        /// </summary>
        /// <returns></returns>
        public ActionResult AllotPlan()
        {
            return View();
        }

        [BailunAuthentication(LoginMode.Enforce)]
        [BrowseLog("Bailun_data", "访问【百伦数据中心】->【订单】->【调拨计划在途明细】->【查询】页面", 0)]
        public string AllotPlanJson(BtTableParameter parameter, string orderno, string sku, string warehousetype, string warehousecode)
        {
            var total = 0;
            var companyid = HttpContextHelper.Current?.User.GetCompanyId().ToInt32();
            var _service = new Services.AllotServices();

            var obj = _service.ListAllotPlanOnWay(parameter, orderno, sku, warehousetype, warehousecode, ref total);

            var objCount = _service.ListAllotPlanOnWayCount(orderno, sku, warehousetype, warehousecode);

            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = obj,
                companyid = companyid,
                isexport = Services.UserAuthorityServices.checkUserExportAuthority("ExportAllotPlanOnWay", HttpContextHelper.Current.User.GetUserName()),
                count_row = new
                {
                    bailun_sku = "总计",
                    objCount.count
                }
            });

        }

        /// <summary>
        /// 导出调拨计划在途明细
        /// </summary>
        /// <param name="orderno">调拨计划单号</param>
        /// <param name="sku">sku</param>
        /// <param name="warehousetype">目的仓库类型</param>
        /// <param name="warehousecode">目的仓库编码</param>
        /// <returns></returns>
        public ActionResult ExportAllotPlan(string orderno, string sku, string warehousetype, string warehousecode)
        {
            var total = 0;
            var _service = new Services.AllotServices();
            var obj = _service.ListAllotPlanOnWay(new BtTableParameter { limit = 0, offset = 1 }, orderno, sku, warehousetype, warehousecode, ref total);

            var colNames = new List<string> { "调拨计划单号", "仓库编码", "仓库名称", "sku", "数量"};

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.transfer_plan_order_id + "|" + item.warehouse_code + "|" + item.warehouse_name + "|" + item.bailun_sku + "|" + item.count);
            }

            var guid = Guid.NewGuid().ToString();
            var filename = "调拨计划在途明细 " + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");
        }



    }
}