using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Microsoft.AspNetCore.Hosting;
using System.Threading.Tasks;
using Bailun.ServiceFabric.Authorize;
using Bailun.ServiceFabric.Core.Extension.HttpContext;
using Bailun.ServiceFabric.Core.Extension;
using Microsoft.AspNetCore.Http;

namespace Bailun.DC.Web.Areas.DataWareHouse.Controllers
{
    [Area("DataWareHouse")]
    public class PlatformOrderController : Base.BaseController
    {
        private readonly IHostingEnvironment _hostingEnvironment;

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

        public IActionResult OrderBillings(string platform)
        {
            var listsite = new Services.DataWareHouse.PlatformOrderServices().ListPlatformSite(platform);
            ViewBag.platform = platform;

            ViewBag.sites = listsite;
            return View();
        }


        [HttpPost]
        public JsonResult OrderBillingsJson(int page,string platform,string website,string account,DateTime? start,DateTime? end,string orderno, int pagesize = 25)
        {
            if (string.IsNullOrEmpty(platform))
            {
                return Json(new { 
                    success=  false,
                    msg = "请选择平台类型"
                });
            }

            //if(string.IsNullOrEmpty(website))
            //{
            //    return Json(new { 
            //        success = false,
            //        msg = "请选择站点",
            //    });
            //}

            //if(string.IsNullOrEmpty(month))
            //{
            //    return Json(new { 
            //        success = false,
            //        msg = "请选择月份"
            //    });
            //}

            if(page<=0)
            {
                page = 1;
            }

            int total = 0;
            var obj = new Services.DataWareHouse.PlatformOrderServices().List(page, platform, website, account, start,end,orderno, ref total,pagesize);

            var list = obj.Select(a => new { 
                a.accountname,
                a.createtime,
                jsondata = Newtonsoft.Json.Linq.JRaw.Parse(a.jsondata),
                a.month,
                a.orderno,
                a.platform,
                a.website,
                datatime = a.datatime.HasValue?a.datatime.Value.ToString("yyyy-MM-dd HH:mm:ss"):"",
            });

            return Json(new { 
                success = true,
                msg = "",
                rows = list,
                total = total,
                page = page,
                totalpage = total/pagesize+(total%pagesize>0?1:0),
            });
        }

        public ActionResult ExportOrderBillings(string platform, string website, string account, DateTime? start,DateTime? end,string orderno)
        {
            if (string.IsNullOrEmpty(platform))
            {
                return Json(new
                {
                    success = false,
                    msg = "请选择平台类型"
                });
            }

            //if (string.IsNullOrEmpty(website))
            //{
            //    return Json(new
            //    {
            //        success = false,
            //        msg = "请选择站点",
            //    });
            //}

            //if (string.IsNullOrEmpty(month))
            //{
            //    return Json(new
            //    {
            //        success = false,
            //        msg = "请选择月份"
            //    });
            //}


            var total = 0;
            var obj = new Services.DataWareHouse.PlatformOrderServices().List(1, platform, website, account, start,end, orderno, ref total, 0);

            if(obj.Count==0)
            {
                return Json(new
                {
                    success = true,
                    msg = "没有数据"
                });
            }

            //列头

            DataTable dataTable = new DataTable(); //实例化
            var objFirst = obj.FirstOrDefault();
            var jsonData = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(objFirst.jsondata);
            var colnames = new List<string>();

            foreach (var item in jsonData)
            {
                dataTable.Columns.Add(item.Key, typeof(string));
                colnames.Add(item.Key);
            }

            foreach (var item in obj)
            { 
                jsonData = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(item.jsondata);

                DataRow dataRow = dataTable.NewRow();

                foreach (var c in jsonData)
                {

                    dataRow[c.Key] = c.Value;
                }

                dataTable.Rows.Add(dataRow);
            }

            
            //for (var i = 0; i < dataTable.Columns.Count; i++)
            //{
            //    colnames.Add(dataTable.Columns[i].ColumnName);
            //}

            var listVal = new List<string>();
            for (int j = 0; j < dataTable.Rows.Count; j++)
            {
                var s = "";
                for (int k = 0; k < dataTable.Columns.Count; k++)
                {
                    string tmpRowValue = dataTable.Rows[j][k].ToString();

                    s += tmpRowValue + "|";
                }

                //s = s.Substring(0, s.Length - 1);
                listVal.Add(s);
            }

            var guid = Guid.NewGuid().ToString();
            var filename = platform+ " " + ((start.HasValue?start.Value.ToString("yyyy-MM-dd"):""+(end.HasValue?"至"+end.Value.ToString("yyyy-MM-dd"):""))) + "的账单流水";
            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");
        }
    
        /// <summary>
        /// 下载销售平台流水上传模版
        /// </summary>
        /// <param name="platform"></param>
        /// <param name="website"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public ActionResult DownLoadOrderBillingTemplate(string platform,string website,DateTime? start,DateTime? end)
        {
            if (string.IsNullOrEmpty(platform))
            {
                return Content("请选择完平台再导出");
            }

            var obj = new Services.DataWareHouse.PlatformOrderServices().Get(platform, website, start, end);
            if (obj == null)
            {
                return Content("系统没有该平台的模版可导出，你可自定义一个模版，后面的导入都以本次导入的格式作为新模板。");
            }

            DataTable dataTable = new DataTable(); //实例化
            var jsonData = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(obj.jsondata);
            var colnames = new List<string>();

            foreach (var item in jsonData)
            {
                dataTable.Columns.Add(item.Key, typeof(string));
                colnames.Add(item.Key);
            }

            jsonData = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(obj.jsondata);

            DataRow dataRow = dataTable.NewRow();

            foreach (var c in jsonData)
            {

                dataRow[c.Key] = c.Value;
            }

            dataTable.Rows.Add(dataRow);


            //for (var i = 0; i < dataTable.Columns.Count; i++)
            //{
            //    colnames.Add(dataTable.Columns[i].ColumnName);
            //}

            var listVal = new List<string>();
            for (int j = 0; j < dataTable.Rows.Count; j++)
            {
                var s = "";
                for (int k = 0; k < dataTable.Columns.Count; k++)
                {
                    string tmpRowValue = dataTable.Rows[j][k].ToString();

                    s += tmpRowValue + "|";
                }

                //s = s.Substring(0, s.Length - 1);
                listVal.Add(s);
            }

            var guid = Guid.NewGuid().ToString();
            var filename = platform + " " + ((start.HasValue ? start.Value.ToString("yyyy-MM-dd") : "" + (end.HasValue ? "至" + end.Value.ToString("yyyy-MM-dd") : ""))) + "的上传模版";
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            //ToCSV(listVal, colnames, guid, filepath);

            ToExcel(dataTable, guid, filepath);

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

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

        }

        /// <summary>
        /// 上传销售平台流水
        /// </summary>
        /// <param name="platform">平台类型</param>
        /// <param name="website">站点</param>
        /// <returns></returns>
        //[BailunAuthentication(LoginMode.Enforce)]
        [DisableRequestSizeLimit]
        public JsonResult UploadOrderBilling(string platform, string website)
        {
            
            if (Request.Form.Files.Count == 0)
            {
                return Json(new
                {
                    success = false,
                    msg = "请上传文件！"
                });
            }

            //var user = HttpContextHelper.Current?.User;

            var file = Request.Form.Files[0];
            
            Dictionary<string, DataTable> dic = Base.NpolHelper.ExcelToDataTable(file.OpenReadStream(), file.FileName, true);
            if (dic.Count > 0)
            {
                var tb = dic.FirstOrDefault();

                var list = Dtb2Json(tb.Value);
                var listOrders = new List<Models.DataWareHouse.flowing_sales>();
                foreach (var item in list)
                {
                    //保存数据
                    var m = new Models.DataWareHouse.flowing_sales { 
                        accountname = "",
                        createtime = DateTime.Now,
                        jsondata = Newtonsoft.Json.JsonConvert.SerializeObject(item),
                        month = "",
                        platform = platform,
                        website = website??"",
                        orderno = "",
                        platformsku = "",
                        createuser = "页面上传"
                        
                    };
                    listOrders.Add(m);
                }

                var result = new Services.DataWareHouse.PlatformOrderServices().InsertOrderBilling(listOrders);
                return Json(new { 
                    success = string.IsNullOrEmpty(result),
                    msg = result
                });
            }

            return Json(new { 
                success = false,
                msg="无法识别表格的数据，请下载模版重新导入，或者检查下表格数据是否正确。",
            });
        }

        /// <summary>
        /// 平台站点合并单个文件上传
        /// </summary>
        /// <param name="platform"></param>
        /// <param name="website"></param>
        /// <returns></returns>
        public JsonResult UploadOrderBillingMerge(string platform)
        {
            if (Request.Form.Files.Count == 0)
            {
                return Json(new
                {
                    success = false,
                    msg = "请上传文件！"
                });
            }

            //var user = HttpContextHelper.Current?.User;

            var file = Request.Form.Files[0];

            Dictionary<string, DataTable> dic = Base.NpolHelper.ExcelToDataTable(file.OpenReadStream(), file.FileName, true);

            if (dic.Count > 0)
            {
                var tb = dic.FirstOrDefault();

                var list = Dtb2Json(tb.Value);
                var listOrders = new List<Models.DataWareHouse.flowing_sales>();
                foreach (var item in list)
                {
                    //保存数据
                    var m = new Models.DataWareHouse.flowing_sales
                    {
                        accountname = "",
                        createtime = DateTime.Now,
                        jsondata = Newtonsoft.Json.JsonConvert.SerializeObject(item),
                        month = "",
                        platform = platform,
                        //website = website ?? "",
                        orderno = "",
                        platformsku = "",
                        createuser = "页面上传"

                    };
                    listOrders.Add(m);
                }

                var result = new Services.DataWareHouse.PlatformOrderServices().InsertOrderBilling(listOrders);
                return Json(new
                {
                    success = string.IsNullOrEmpty(result),
                    msg = result
                });
            }

            return Json(new
            {
                success = false,
                msg = "无法识别表格的数据，请下载模版重新导入，或者检查下表格数据是否正确。",
            });

        }


        private System.Collections.ArrayList Dtb2Json(DataTable dtb)
        {
            
            System.Collections.ArrayList dic = new System.Collections.ArrayList();
            foreach (DataRow dr in dtb.Rows)
            {
                System.Collections.Generic.Dictionary<string, object> drow = new System.Collections.Generic.Dictionary<string, object>();

                foreach (DataColumn dc in dtb.Columns)
                {
                    drow.Add(dc.ColumnName, dr[dc.ColumnName]);
                }

                //判断是否空行，如果null值
                if (drow.ToList().Where(a => a.Value == null).Count() == drow.Count || drow.FirstOrDefault().Value == null)
                {
                    continue;
                }
                else
                {
                    dic.Add(drow);
                }
                
            }

            return dic;

        }
    }
}
