using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using OfficeOpenXml;
using OfficeOpenXml.Style;
using Siger.Middlelayer.Utility.ExcelImport;
using ExcelColumn = Siger.Middlelayer.Utility.ExcelImport.ExcelColumn;

namespace Siger.Middlelayer.Utility.Helpers
{
    public class EpPlusForQmsHelper<T> : IDisposable where T: ImportBase, new()
    {
        private ExcelWorksheet Sheet { get; }

        public EpPlusForQmsHelper()
        {

        }

        public EpPlusForQmsHelper(string filePath)
        {
            if (File.Exists(filePath))
            {
                var file = new FileInfo(filePath);
                var excelPackage = new ExcelPackage(file);
                if (excelPackage.Workbook != null && excelPackage.Workbook.Worksheets.Count > 0)
                {
                    Sheet = excelPackage.Workbook.Worksheets.First();
                }
                else
                {
                    throw new Exception("read excel failed.");
                }
            }
        }

        /// <summary>
        /// create excel file by list and filepath
        /// </summary>
        /// <param name="list"></param>
        /// <param name="filePath"></param>
        public void GenerateExcel(IEnumerable<T> list, string filePath,bool longTimeFormat=false)
        {
            var file = new FileInfo(filePath);
            var package = new ExcelPackage(file);
            var worksheet = package.Workbook.Worksheets.Add("sheet1");

            try
            {
                //add head
                bool ColumnOnly(CustomAttributeData y) => y.AttributeType == typeof(ExcelColumn);
                var columns = typeof(T)
                    .GetProperties()
                    .Where(x => x.CustomAttributes.Any(ColumnOnly) 
                                && x.CustomAttributes.All(m => m.AttributeType != typeof(DonnetExportAttribute)))
                    .Select(p => new
                    {
                        Property = p,
                        Column = p.GetCustomAttributes<ExcelColumn>().First().ColumnName
                    }).ToList();

                for (var i = 0; i < columns.Count; i++)
                {
                    worksheet.Cells[1, i + 1].Value = columns[i].Column;
                    worksheet.Column(i+1).Width = 18;
                }

                worksheet.Column(1).Width = 10;
                worksheet.Cells[1, 1].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                worksheet.Cells.Style.ShrinkToFit = true;
                worksheet.Cells.Style.WrapText = true;

                //add content
                var entities = list.ToList();
                for (var i = 0; i < entities.Count; i++)
                {
                    var entity = entities[i];
                    for (var j = 0; j < columns.Count; j++)
                    {
                        var value = entity.GetType().InvokeMember(columns[j].Property.Name,
                            BindingFlags.GetProperty, null, entity, null);

                        var propertyType = columns[j].Property.PropertyType;
                        if (propertyType.ToString().Contains("System.DateTime"))
                        {
                            if (value != null)
                            {
                                var date = DateTime.Parse(value.ToString());
                                if (date != DateTime.MinValue)
                                {
                                    var result = date.ToString((longTimeFormat)? DateFormatHelper.DateTimeFormat: DateFormatHelper.DateFormat);
                                    worksheet.Cells[i + 2, j + 1].Value = result;
                                }
                            }
                        }
                        //other type
                        else
                        {
                            worksheet.Cells[i + 2, j + 1].Value = value;
                        }
                    }
                    worksheet.Cells[i + 2, 1].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                }

                package.Save();
            }
            finally
            {
                package.Dispose();
            }
        }

        private int GetColumnByName(string columnName)
        {
            if (Sheet == null)
            {
                throw new ArgumentNullException(nameof(Sheet));
            }

            var column = Sheet.Cells["1:1"].FirstOrDefault(c => c.Value.ToString() == columnName);
            if (column == null)
            {
                return 0;
            }
            return Sheet.Cells["1:1"].First(c => c.Value.ToString() == columnName).Start.Column;
        }

        /// <summary>
        /// 动态生成产线结构导入
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public IEnumerable<T> ConvertSheetToList(int levelCount, int language = 0)
        {
            if (Sheet == null)
            {
                throw new ArgumentNullException(nameof(Sheet));
            }
            bool ColumnOnly(CustomAttributeData y) => y.AttributeType == typeof(ExcelColumn);
            var columns = typeof(T)
                .GetProperties()
                .Where(x => x.CustomAttributes.Any(ColumnOnly) && x.CustomAttributes.All(m => m.AttributeType != typeof(DonnetValidateAttribute)))
                .Select(p => new
                {
                    Property = p,
                    Column = (language == 0 || !EpPlusLanguageHelper.LanguageDictionary.ContainsKey(p.GetCustomAttributes<ExcelColumn>().First().ColumnName))
                        ? p.GetCustomAttributes<ExcelColumn>().First().ColumnName
                        : EpPlusLanguageHelper.LanguageDictionary[p.GetCustomAttributes<ExcelColumn>().First().ColumnName]
                }).ToList();

            var endRow = 2;
            for (var row = 2; row <= Sheet.Dimension.Rows; row++)
            {
                var columnValues = new List<string>();
                for (var i = 1; i <= columns.Count; i++)
                {
                    var val = Sheet.Cells[row, i];
                    if (val != null)
                    {
                        columnValues.Add(val.Text);
                    }
                }

                if (columnValues.All(string.IsNullOrWhiteSpace))
                {
                    endRow = row - 1;
                    break;
                }

                endRow = row;
            }

            var cloumnName = "";
            if (EpPlusLanguageHelper.LanguageDictionary.ContainsKey("产线结构") && language == 1)
            {
                cloumnName = EpPlusLanguageHelper.LanguageDictionary["产线结构"];
            }
            else
            {
                cloumnName = "产线结构";
            }

            IList<int> rows = new List<int>();
            for (var i = 2; i <= endRow; i++)
            {
                rows.Add(i);
            }
            var collection = rows
                .Select(row =>
                {
                    var sections = new List<string>();
                    for (var i = 1; i <= levelCount; i++)
                    {
                        sections.Add(Sheet.Cells[row, i].GetValue<string>());
                    }
                    var j = levelCount - 1;
                    var tnew = new T();
                    columns.ForEach(col =>
                    {
                        j++;
                        if (col.Column == cloumnName)
                        {
                            col.Property.SetValue(tnew, sections);
                        }
                        else
                        {
                            var val = Sheet.Cells[row, j];
                            if (val.Value == null)
                            {
                                col.Property.SetValue(tnew, string.Empty);
                                return;
                            }

                            if (col.Property.PropertyType == typeof(int))
                            {
                                col.Property.SetValue(tnew, val.GetValue<int>());
                                return;
                            }

                            if (col.Property.PropertyType == typeof(double))
                            {
                                col.Property.SetValue(tnew, val.GetValue<double>());
                                return;
                            }

                            if (col.Property.PropertyType == typeof(DateTime?))
                            {
                                col.Property.SetValue(tnew, val.GetValue<DateTime?>());
                                return;
                            }

                            if (col.Property.PropertyType == typeof(DateTime))
                            {
                                col.Property.SetValue(tnew, val.GetValue<DateTime>());
                                return;
                            }

                            if (col.Property.PropertyType == typeof(bool))
                            {
                                col.Property.SetValue(tnew, val.GetValue<bool>());
                                return;
                            }

                            col.Property.SetValue(tnew,
                                string.IsNullOrWhiteSpace(val.GetValue<string>()) ? "" : val.GetValue<string>());
                        }
                    });

                    return tnew;
                });
            return collection;
        }

        public List<string> CheckExcel()
        {
            if (Sheet == null)
            {
                throw new ArgumentNullException(nameof(Sheet));
            }

            bool ColumnOnly(CustomAttributeData y) => y.AttributeType == typeof(ExcelColumn);
            var messages = new List<string>();
            var columns = typeof(T)
                 .GetProperties()
                 .Where(x => x.CustomAttributes.Any(ColumnOnly) && x.CustomAttributes.All(m => m.AttributeType != typeof(DonnetValidateAttribute)))
                 .Select(p => new
                 {
                     Property = p,
                     Column = p.GetCustomAttributes<ExcelColumn>().First().ColumnName
                 }).ToList();

            var rows = Sheet.Cells.Select(cell => cell.Start.Row).Distinct().OrderBy(x => x).ToList().Skip(1);
            if (!rows.Any())
            {
                messages.Add($"{(int)ImportEnum.NoRecordForImport}");
                return messages;
            }

            var endRow = 2;
            for (var row = 2; row <= Sheet.Dimension.Rows; row++)
            {
                var columnValues = new List<string>();
                for (var i = 1; i <= columns.Count; i++)
                {
                    var val = Sheet.Cells[row, i];
                    if (val != null)
                    {
                        columnValues.Add(val.Text);
                    }
                }

                if (!columnValues.All(string.IsNullOrWhiteSpace))
                {
                    continue;
                }
                endRow = row - 1;
                break;
            }

            for (var row = 2; row <= endRow; row++)
            {
                foreach (var col in columns)
                {
                    var column = GetColumnByName(col.Column);
                    if (column == 0)
                    {
                        messages.Add($"{row},{(int)ImportEnum.ColumnNameNotFound}");
                        continue;
                    }
                    var val = Sheet.Cells[row, column];
                    if (val == null)
                    {
                        continue;
                    }
                    //非空验证
                    var emptyValidate = col.Property.CustomAttributes.FirstOrDefault(m => m.AttributeType == typeof(EmptyValidate));
                    if (emptyValidate != null)
                    {
                        if (string.IsNullOrWhiteSpace(val.Text))
                        {
                            var errorMessage = emptyValidate.ConstructorArguments[0].Value;
                            var errorKey = (int) Enum.Parse(typeof(ImportEnum), errorMessage.ToString());
                            messages.Add($"{row},{errorKey}");
                        }
                    }
                    //正则验证
                    var expressionValidate = col.Property.CustomAttributes.FirstOrDefault(m => m.AttributeType == typeof(RegularExpressionValidate));
                    if (expressionValidate != null)
                    {
                        if (!string.IsNullOrWhiteSpace(val.Text))
                        {
                            var expression = expressionValidate.ConstructorArguments[0].Value.ToString();
                            var errorMessage = expressionValidate.ConstructorArguments[1].Value.ToString();
                            var regex = new Regex(expression);
                            if (!regex.IsMatch(val.Text))
                            {
                                var errorKey = (int)Enum.Parse(typeof(ImportEnum), errorMessage);
                                messages.Add($"{row},{errorKey}");
                            }
                        }
                    }

                    if (string.IsNullOrWhiteSpace(val.Text))
                    {
                        continue;
                    }

                    bool result;
                    if (col.Property.PropertyType == typeof(int))
                    {
                        result = int.TryParse(val.Text, out var _);
                        if (!result)
                        {
                            messages.Add($"{row},{(int)ImportEnum.NumberIsValid}");
                        }
                    }

                    if (col.Property.PropertyType == typeof(DateTime))
                    {
                        result = DateTime.TryParse(val.Text, out DateTime _);
                        if (!result)
                        {
                            messages.Add($"{row},{(int)ImportEnum.DateTimeIsInValid}");
                        }
                    }
                }
            }
            
            return messages;
        }

        public void Dispose()
        {
            Sheet?.Dispose();
        }
    }
}
