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

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,string month, 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, month, 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,
            });

            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, string month)
        {
            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, month, 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+ " " + month + "的账单流水";
            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");
        }
    }
}
