using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web;

namespace Bailun.DC.Web.Base
{
    public class BaseController: Controller
    {
        //private readonly IHttpContextAccessor _contextAccessor;

        //public BaseController(IHttpContextAccessor contextAccessor)
        //{
        //    _contextAccessor = contextAccessor;

        //    var cookie = HttpContext.Request.Cookies["BLUserAcct"];
        //    if (cookie == null)
        //    {
        //        HttpContext.Response.Redirect(ConfigHelper.GetByName("LoginUrl"), true);
        //    }
        //}

        /// <summary>
        /// 查看是否还有物流往来统计服务在跑
        /// </summary>
        public static bool isRunLogisticsSupplierTransaction = false;


        #region Excel表格导出
        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="list"></param>
        /// <param name="columns"></param>
        /// <param name="tbName"></param>
        public void ToCSV(List<string> list, List<string> columns, string tbName, string filePath)
        {
            var strb = string.Empty;

            if (System.IO.File.Exists(filePath + tbName + ".csv"))
            {
                System.IO.File.Delete(filePath + tbName + ".csv");
            }

            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }

            StreamWriter writer = new StreamWriter(filePath + tbName + ".csv", true, System.Text.Encoding.UTF8);
            writer.AutoFlush = true;
            //var ms = new System.IO.MemoryStream();

            //添加表头
            foreach (var item in columns)
            {
                strb += (item + ",");
            }
            strb.Remove(strb.Length - 1, 1);
            writer.WriteLine(strb.ToString());

            //ms.Write(System.Text.Encoding.UTF8.GetBytes(strb.ToString()+"\n"));

            //添加表内容
            foreach (var item in list)
            {
                var arr = item.Split('|');
                strb = string.Empty;
                foreach (var rowitem in arr)
                {
                    var temp = rowitem.Replace("\"", "\"\"");//替换英文冒号 英文冒号需要换成两个冒号
                    if (temp.Contains(",") || temp.Contains("\"")
                        || temp.Contains("\r") || temp.Contains("\n")) //含逗号 冒号 换行符的需要放到引号中
                    {
                        temp = string.Format("\"{0}\"", temp);
                    }

                    strb += (temp + ",");
                }

                if (arr.Length > 0)
                {
                    strb.Remove(strb.Length - 1, 1);
                    writer.WriteLine(strb.ToString());
                    //ms.Write(System.Text.Encoding.UTF8.GetBytes(strb.ToString() + "\n"));
                }
            }

            writer.Flush();
            writer.Close();
            writer.Dispose();
        }

        public void ToExcel(DataTable dt, string filename, string filePath)
        {
            #region 3s  

            //创建全新的Workbook 
            var workbook = new HSSFWorkbook();//一個sheet最多65536行
            var count = 0;
            for (double i = 0; i < Convert.ToDouble(dt.Rows.Count) / Convert.ToDouble(65534); i++)//每个Excel文件的一个页签只能存放65536行数据
            {
                var row_index = 0;
                //创建Sheet
                workbook.CreateSheet("Sheet" + (i+1));
                //根据Sheet名字获得Sheet对象  
                var sheet = workbook.GetSheet("Sheet" + (i + 1));
                IRow row;
                row = sheet.CreateRow(row_index);

                //写入标题
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    row.CreateCell(j).SetCellValue(dt.Columns[j].Caption.ToString());
                }
                row = sheet.CreateRow(++row_index);

                //写入数据
                for (int j = 0; j < (dt.Rows.Count - count > 65534 ? 65534 : dt.Rows.Count - count); j++)
                {
                    var r = dt.Rows[j + count];
                    for (int k = 0; k < dt.Columns.Count; k++)
                    {
                        row.CreateCell(k).SetCellValue(r[k].ToString());

                        //如果是数字,判断是否需要转换为数字
                        //if (IsNumeric(r[k].ToString()))
                        //{
                        //    row.CreateCell(k).SetCellValue(Convert.ToDouble(r[k].ToString()));
                        //}
                        //else
                        //{
                        //    row.CreateCell(k).SetCellValue(r[k].ToString());
                        //}
                    }

                    row = sheet.CreateRow(++row_index);
                }
                count += row_index - 2;
            }
            //保存Workbook方式一： 以文件形式保存到服务器中（每次导出都会生成一个文件，慎重使用）
            //var FileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";

            var sw = System.IO.File.Create(filePath + filename+ ".xls");
            workbook.Write(sw);
            sw.Close();
            
            #endregion
        }

        #endregion

    }
}
