using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Autodesk.Revit.DB;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using OfficeOpenXml;
using uBIMEarthTools.Model;
using CellType = NPOI.SS.UserModel.CellType;

namespace uBIMEarthTools.Utils
{
    class ExcelHelper
    {
        public static List<Borehole> GetDataFromExcel(string filePath)
        {
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
            List<Borehole> boreholeList = new List<Borehole>();

            using (ExcelPackage excelPackage = new ExcelPackage(new FileInfo(filePath)))
            {
                List<Tuple<string, string, string>> typeList = GetGeologyType(filePath);

                ExcelWorksheet excelWorksheet = excelPackage.Workbook.Worksheets[1];
                int endRowNumber = excelWorksheet.Dimension.End.Row;
                int endColumn = excelWorksheet.Dimension.End.Column;
                double x1 = double.Parse(excelWorksheet.Cells[1, 2].Text) * 1000 / 304.8;
                double y1 = double.Parse(excelWorksheet.Cells[1, 3].Text) * 1000 / 304.8;
                for (int i = 1; i <= endRowNumber; i += 2)
                {
                    Borehole borehole = new Borehole();
                    borehole.Name = excelWorksheet.Cells[i, 1].Text;
                    double x = double.Parse(excelWorksheet.Cells[i, 2].Text) * 1000 / 304.8;
                    double y = double.Parse(excelWorksheet.Cells[i, 3].Text) * 1000 / 304.8;

                    for (int j = 4; j <= endColumn; j++)
                    {
                        string current = excelWorksheet.Cells[i, j].Text.Replace("\r","").Replace("\n","");
                        string next = excelWorksheet.Cells[i + 1, j].Text;

                        if (string.IsNullOrEmpty(current) || string.IsNullOrEmpty(next))
                        {
                            break;
                        }
                        else
                        {
                            string type = string.Empty;
                            try
                            {
                                type = "地质" + current + "-" + typeList.Find(t => t.Item1.Equals(current)).Item2 + "层";
                            }
                            catch (Exception e)
                            {
                                MessageBox.Show(i.ToString() + "," + j.ToString() + ":" + current);
                                throw;
                            }

                            try
                            {

                                double z = double.Parse(next) * 1000 / 304.8;

                                XYZ xyz = new XYZ(x, y, z);
                                //XYZ xyz = new XYZ(x - x1, y - y1, z);
                                GeologyLayer geologyLayer = new GeologyLayer(type, xyz);
                                borehole.ValueList.Add(geologyLayer);
                            }
                            catch (Exception e)
                            {
                                MessageBox.Show((i + 1).ToString() + "," + j.ToString() + ":" + next);
                                throw;
                            }
                        }
                    }

                    boreholeList.Add(borehole);
                }
            }

            return boreholeList;
        }

        public static List<Tuple<string, string, string>> GetGeologyType(string filePath)
        {
            List<Tuple<string, string, string>> typeList = new List<Tuple<string, string, string>>();
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
            //FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
            using (ExcelPackage excelPackage = new ExcelPackage(new FileInfo(filePath)))
            {
                ExcelWorksheet excelWorksheet = excelPackage.Workbook.Worksheets[0];
                int endRowNumber = excelWorksheet.Dimension.End.Row;
                //int endColumn = excelWorksheet.Dimension.End.Column;
                for (int i = 1; i <= endRowNumber; i++)
                {
                    typeList.Add(new Tuple<string, string, string>(excelWorksheet.Cells[i, 1].Text.Trim(' '), excelWorksheet.Cells[i, 2].Text.Trim(' '), excelWorksheet.Cells[i, 3].Style.Fill.BackgroundColor.ToString()));
                }
            }
            return typeList;
        }


        #region 根据Excel和Sheet返回DataTable
        /// <summary>
        /// 根据Excel和Sheet返回DataTable
        /// </summary>
        /// <param name="filePath">Excel文件地址</param>
        /// <param name="sheetIndex">Sheet索引</param>
        /// <returns>DataTable</returns>
        public static DataTable GetDataTable(string filePath, int sheetIndex)
        {
            return GetDataSet(filePath, sheetIndex).Tables[0];
        }
        #endregion

        #region 根据Excel返回DataSet
        /// <summary>
        /// 根据Excel返回DataSet
        /// </summary>
        /// <param name="filePath">Excel文件地址</param>
        /// <param name="sheetIndex">Sheet索引，可选，默认返回所有Sheet</param>
        /// <returns>DataSet</returns>
        public static DataSet GetDataSet(string filePath, int? sheetIndex = null)
        {
            DataSet ds = new DataSet();
            IWorkbook fileWorkbook;
            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                if (filePath.Last() == 's')
                {
                    try
                    {
                        fileWorkbook = new HSSFWorkbook(fs);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
                else
                {
                    try
                    {
                        fileWorkbook = new XSSFWorkbook(fs);
                    }
                    catch
                    {
                        fileWorkbook = new HSSFWorkbook(fs);
                    }
                }
            }

            for (int i = 0; i < fileWorkbook.NumberOfSheets; i++)
            {
                if (sheetIndex != null && sheetIndex != i)
                    continue;
                DataTable dt = new DataTable();
                ISheet sheet = fileWorkbook.GetSheetAt(i);

                //表头
                IRow header = sheet.GetRow(sheet.FirstRowNum);
                List<int> columns = new List<int>();
                for (int j = 0; j < header.LastCellNum; j++)
                {
                    object obj = GetValueTypeForXLS(header.GetCell(j));
                    if (obj == null || obj.ToString() == string.Empty)
                    {
                        dt.Columns.Add(new DataColumn("Columns" + j.ToString()));
                    }
                    else
                        dt.Columns.Add(new DataColumn(obj.ToString()));
                    columns.Add(j);
                }
                //数据
                IEnumerator rows = sheet.GetEnumerator();
                int r = sheet.FirstRowNum + 1;
                while (rows.MoveNext())
                {
                    if (null == sheet.GetRow(r))
                    {
                        break;
                    }
                    DataRow dr = dt.NewRow();
                    bool hasValue = false;
                    foreach (int K in columns)
                    {
                        dr[K] = GetValueTypeForXLS(sheet.GetRow(r).GetCell(K));
                        if (dr[K] != null && dr[K].ToString() != string.Empty)
                        {
                            hasValue = true;
                        }
                    }
                    if (hasValue)
                    {
                        dt.Rows.Add(dr);
                    }
                    r++;
                }
                ds.Tables.Add(dt);
            }

            return ds;
        }
        #endregion

        #region 根据DataTable导出Excel
        /// <summary>
        /// 根据DataTable导出Excel
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <param name="file">保存地址</param>
        public static void GetExcelByDataTable(DataTable dt, string file)
        {
            DataSet ds = new DataSet();
            ds.Tables.Add(dt);
            GetExcelByDataSet(ds, file);
        }
        #endregion

        #region 根据DataSet导出Excel
        /// <summary>
        /// 根据DataSet导出Excel
        /// </summary>
        /// <param name="ds">DataSet</param>
        /// <param name="file">保存地址</param>
        public static void GetExcelByDataSet(DataSet ds, string file)
        {
            IWorkbook fileWorkbook = new HSSFWorkbook();
            int index = 0;
            foreach (DataTable dt in ds.Tables)
            {
                index++;
                ISheet sheet = fileWorkbook.CreateSheet("Sheet" + index);

                //表头
                IRow row = sheet.CreateRow(0);
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    ICell cell = row.CreateCell(i);
                    cell.SetCellValue(dt.Columns[i].ColumnName);
                }

                //数据
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    IRow row1 = sheet.CreateRow(i + 1);
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        ICell cell = row1.CreateCell(j);
                        cell.SetCellValue(dt.Rows[i][j].ToString());
                    }
                }
            }

            //转为字节数组
            MemoryStream stream = new MemoryStream();
            fileWorkbook.Write(stream);
            var buf = stream.ToArray();

            //保存为Excel文件
            using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write))
            {
                fs.Write(buf, 0, buf.Length);
                fs.Flush();
            }
        }
        #endregion

        #region 根据单元格将内容返回为对应类型的数据
        /// <summary>
        /// 根据单元格将内容返回为对应类型的数据
        /// </summary>
        /// <param name="cell">单元格</param>
        /// <returns>数据</returns>
        private static object GetValueTypeForXLS(ICell cell)
        {
            if (cell == null)
                return null;
            switch (cell.CellType)
            {
                case CellType.Blank: //BLANK:
                    return null;
                case CellType.Boolean: //BOOLEAN:
                    return cell.BooleanCellValue;
                case CellType.Numeric: //NUMERIC:
                    return cell.NumericCellValue;
                case CellType.String: //STRING:
                    return cell.StringCellValue;
                case CellType.Error: //ERROR:
                    return cell.ErrorCellValue;
                case CellType.Formula: //FORMULA:
                default:
                    return "=" + cell.CellFormula;
            }
        }
        #endregion
    }
}

