using Autodesk.Revit.DB;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using OfficeOpenXml;
using System.IO;
using System.Linq;

namespace uBIM_EarthTools
{
    class ExcelHelper
    {
        /// <summary>
        /// 读取地质数据
        /// 原数据单位为M,转换为MM
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        public static List<Borehole> GetDataFromXls(string filePath)
        {
            List<Borehole> boreholeList = new List<Borehole>();
            Microsoft.Office.Interop.Excel.Workbook wb = null;
            Microsoft.Office.Interop.Excel.Worksheet ws = null;
            object missing = System.Reflection.Missing.Value;
            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();//lauch excel application
            excel.DisplayAlerts = false;
            if (excel != null)
            {
                excel.Visible = false;
                excel.UserControl = true;// 以只读的形式打开EXCEL文件
                wb = excel.Workbooks.Open(filePath, missing, true, missing, missing, missing,
                 missing, missing, missing, true, missing, missing, missing, missing, missing);

                ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets.Item[1];
                Dictionary<string, string> typeList = new Dictionary<string, string>();
                for (int i = 1; i < ws.UsedRange.Rows.Count + 1; i++)
                {
                    typeList.Add(ws.Cells[i, 1].Text, ws.Cells[i, 2].Text);
                }



                ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets.Item[2];
                //取得总记录行数(包括标题列) 
                int rowsint = ws.UsedRange.Rows.Count; //得到行数 
                                                       //int rowsint = begin_row + 2*10;
                int columnsint = ws.UsedRange.Columns.Count;//得到列数 
                for (int i = 1; i <= rowsint; i += 2)
                {
                    Borehole borehole = new Borehole();
                    borehole.Name = ws.Cells[i, 1].Text;
                    double x = double.Parse(ws.Cells[i, 2].Text) * 1000 / 304.8;
                    double y = double.Parse(ws.Cells[i, 3].Text) * 1000 / 304.8;
                    for (int j = 4; j <= columnsint; j++)
                    {
                        if (null == ws.Cells[i + 1, j].Text || ws.Cells[i + 1, j].Text == "")
                            break;
                        else
                        {
                            string type = string.Empty;
                            try
                            {
                                type = "地质" + ws.Cells[i, j].Text + "-" + typeList[ws.Cells[i, j].Text] + "层";

                            }
                            catch (Exception e)
                            {
                                MessageBox.Show(i.ToString() + "," + j.ToString());
                                throw;
                            }
                            double z = double.Parse(ws.Cells[i + 1, j].Text) * 1000 / 304.8;
                            XYZ xyz = new XYZ(x, y, z);
                            GeologyLayer geologyLayer = new GeologyLayer(type, xyz);
                            borehole.ValueList.Add(geologyLayer);
                        }
                    }
                    boreholeList.Add(borehole);
                }
            }
            KillProcess(excel);
            return boreholeList;
        }

        public static List<Borehole> GetDataFromExcel(string filePath)
        {
            List<Borehole> boreholeList = new List<Borehole>();

            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                using (ExcelPackage excelPackage = new ExcelPackage(fs))
                {
                    Dictionary<string, string> typeList = GetGeologyType(filePath);

                    ExcelWorksheet excelWorksheet = excelPackage.Workbook.Worksheets[2];
                    int endRowNumber = excelWorksheet.Dimension.End.Row;
                    int endColumn = excelWorksheet.Dimension.End.Column;
                    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++)
                        {
                            if (string.IsNullOrEmpty(excelWorksheet.Cells[i, j].Text) || string.IsNullOrEmpty(excelWorksheet.Cells[i + 1, j].Text))
                            {
                                break;
                            }
                            else
                            {
                                string type = string.Empty;
                                try
                                {
                                    type = "地质" + excelWorksheet.Cells[i, j].Text + "-" + typeList[excelWorksheet.Cells[i, j].Text] + "层";
                                }
                                catch (Exception e)
                                {
                                    MessageBox.Show(i.ToString() + "," + j.ToString() + ":" + excelWorksheet.Cells[i, j].Text);
                                    throw;
                                }
                                double z = double.Parse(excelWorksheet.Cells[i + 1, j].Text) * 1000 / 304.8;
                                z = z - 7.8 * 1000 / 304.8;//临时7.8m等于正负0
                                XYZ xyz = new XYZ(x, y, z);
                                GeologyLayer geologyLayer = new GeologyLayer(type, xyz);
                                borehole.ValueList.Add(geologyLayer);
                            }
                        }

                        boreholeList.Add(borehole);
                    }
                }
            }

            return boreholeList;
        }

        public static Dictionary<string, string> GetGeologyType(string filePath)
        {
            Dictionary<string, string> typeList = new Dictionary<string, string>();
            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                using (ExcelPackage excelPackage = new ExcelPackage(fs))
                {
                    ExcelWorksheet excelWorksheet = excelPackage.Workbook.Worksheets[1];
                    int endRowNumber = excelWorksheet.Dimension.End.Row;
                    int endColumn = excelWorksheet.Dimension.End.Column;
                    for (int i = 1; i <= endRowNumber; i++)
                    {
                        typeList.Add(excelWorksheet.Cells[i, 1].Text, excelWorksheet.Cells[i, 2].Text);
                    }
                }
            }
            return typeList;
        }

        #region 结束excel进程
        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        private static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
        private static void KillProcess(Microsoft.Office.Interop.Excel.Application excel)
        {
            IntPtr t = new IntPtr(excel.Hwnd);
            int k = 0;
            GetWindowThreadProcessId(t, out k);
            System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k);
            p.Kill();
        }
        #endregion
    }
}
