using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.IO;

namespace Bailun.DC.WebApi.Controllers
{
    /// <summary>
    /// 基类Api控制器
    /// </summary>
    public class BaseController : ControllerBase
    {
        /// <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();
        }
    }
}
