using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web;

namespace Bailun.DC.Web.Base
{
    public class BaseController: Controller
    {
        public BaseController()
        {

        }

        #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.Default);

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

            //添加表内容
            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());
                }
            }

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

        #endregion

    }
}
