using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;

namespace Bailun.DC.Web.Areas.ExportFile.Controllers
{
    [Area("ExportFile")]
    public class ShippingController : Base.BaseController
    {
        private readonly IHostingEnvironment _hostingEnvironment;
        public ShippingController(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }

        /// <summary>
        /// 发货明细
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="companyid"></param>
        /// <returns></returns>
        public ActionResult ListShipping(DateTime start, DateTime end, int companyid)
        {
            var _service = new Services.ExportServices();
            var obj = _service.ListShipping(start, end, companyid);

            var colNames = new List<string> {"平台单号","配货单号","运单号", "仓库编码", "仓库名称",
                                             "Sku","发货数量","采购金额","发货时间" };

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.origin_order_id + "|" + item.pick_order_id + "|" + item.logistics_order_id + "|" + item.warehouse_code + "|" + item.warehouse_name + "|" +
                    item.bailun_sku + "|" + item.quantity_shipped + "|" + item.amount + "|"+item.shipping_time.ToString("yyyy-MM-dd HH:mm:ss"));
            }

            var guid = Guid.NewGuid().ToString();
            var filename = "发货明细" + start.ToString("yyyy-MM-dd") + "至" + end.ToString("yyyy-MM-dd");
            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");

        }
    }
}