using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Bailun.DC.Models;
using Bailun.DC.Services;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Hosting;

namespace Bailun.DC.Web.Areas.Reports.Controllers
{
    [Area("Reports")]
    public class PurchaseController : Base.BaseController
    {

        private readonly IHostingEnvironment _hostingEnvironment;

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


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

        /// <summary>
        /// 采购单
        /// </summary>
        /// <returns></returns>
        public ActionResult ListPurchase()
        {
            return View();
        }

        /// <summary>
        /// 采购单列表
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="warehouse">仓库编码</param>
        /// <param name="sku">sku编码</param>
        /// <param name="no">采购单号</param>
        /// <param name="status">采购单状态</param>
        /// <returns></returns>
        [BrowseLog("Bailun_data", "访问【百伦数据中心】->【订单】->【采购单】->【查询】页面", 0)]
        public string ListPurchaseJson(BtTableParameter parameter, string warehouse, string sku, string no, int? status)
        {
            var total = 0;
            var service = new Services.PurchaseServices();
            var obj = service.ListPurchase(parameter, warehouse, sku, no, status, ref total);
            var countM = service.ListPurchaseCount(warehouse, sku, no, status);

            countM.bailun_sku = "总计：";

            var list = obj.Select(p => new {
                p.amount,
                p.arrivalcount,
                p.bailun_sku,
                p.breakcount,
                p.buyer_name,
                p.category_name,
                p.character,
                p.checkcount,
                p.check_fail_count,
                p.check_success_count,
                p.color,
                p.count,
                create_time = p.create_time.ToString("yyyy-MM-dd HH:mm:ss"),
                p.currency,
                p.exchangecount,
                gmt_modified = p.gmt_modified.ToString("yyyy-MM-dd HH:mm:ss"),
                has_transfer = p.has_transfer==1?"采购调拨":"采购入库",
                p.losscount,
                p.noarrivalcount,
                p.nosendcount,
                p.price,
                p.purchase_id,
                p.putincount,
                p.qccount,
                p.qccount_fail,
                p.qccount_success,
                p.returncount,
                p.sendcount,
                p.sku_image,
                p.sku_title_cn,
                p.sku_title_en,
                buy_status = Enum.GetName(typeof(Models.Purchase.EnumPurchaseStatus),p.buy_status),
                p.supplier_name,
                update_time = p.update_time.ToString("yyyy-MM-dd HH:mm:ss"),
                p.waitallotcount,
                p.warehouse_name_from,
                p.warehouse_name_to,
            });

            return JsonConvert.SerializeObject(new { total = total, rows = list,count_row = countM });
        }

        /// <summary>
        /// 获取采购单的明细
        /// </summary>
        /// <param name="start">创建开始时间</param>
        /// <param name="end">创建结束时间</param>
        /// <param name="t">0:成品采购，1：半成品采购</param>
        /// <returns></returns>
        public ActionResult ExportListPurchase(DateTime start,DateTime end,int t)
        {
            var _service = new Services.PurchaseServices();

            var colNames = new List<string> {"采购单号","Sku","采购数量", "价格", "金额",
                                             "下单时间", "状态"
            };

            var listVal = new List<string>();

            if (t == 0)
            {
                colNames.Add("百伦简易分类");

                var obj = _service.ListPurchase(start, end);

                foreach (var item in obj)
                {
                    listVal.Add(
                        item.purchase_id + "|" + item.bailun_sku + "|" + item.count + "|" + item.price + "|" + (item.count * item.price) + "|" +
                        item.create_time.ToString("yyyy-MM-dd HH:mm:ss") + "|" + item.status+"|"+item.category_simple_name
                        );
                }
            }
            else if (t == 1)
            {
                colNames.Add("仓库");

                var obj = _service.ListSemiPurchase(start, end);
                foreach (var item in obj)
                {
                    listVal.Add(
                        item.purchase_id + "|" + item.bailun_sku + "|" + item.quantity_purchase + "|" + item.unit_price + "|" + (item.quantity_purchase * item.unit_price) + "|" +
                        item.create_time.ToString("yyyy-MM-dd HH:mm:ss") + "|" + item.status+"|"+item.warehouse_from_name
                        );
                }
            }
            
            
            var guid = Guid.NewGuid().ToString();
            var filename = start.ToString("yyyy-MM-dd")+"至"+end.ToString("yyyy-MM-dd")+"的"+(t==0?"成品":"半成品")+"采购单明细";
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(listVal, 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");
            
        }
    }
}