using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using OfficeOpenXml;
using Siger.Middlelayer.Utility.ExcelImport;

namespace Siger.Middlelayer.Utility.Helpers
{
    public class EpPlusForBeatSetHelper : IDisposable
    {
        private ExcelWorksheet sheet { get; set; }
        public EpPlusForBeatSetHelper()
        {

        }

        public void GenerateExcel(List<string> columns, List<string> levels, string filePath)
        {
            var file = new FileInfo(filePath);
            var package = new ExcelPackage(file);
            var worksheet = package.Workbook.Worksheets.Add("sheet1");
            try
            {
                for (var i = 0; i < columns.Count; i++)
                {
                    worksheet.Cells[1, i + 1].Value = columns[i];
                    worksheet.Column(i + 1).Width = 18;
                }

                worksheet.Cells.Style.ShrinkToFit = true;
                //插入产线层级
                for (int i = 0; i < levels.Count; i++)
                {
                    var level = levels[i].Split(',');
                    for (var j = 0; j < level.Length; j++)
                    {
                        worksheet.Cells[i + 2, j + 1].Value = level[j];
                    }
                }

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

        public List<string> CheckExcel(string filePath, int levelCount)
        {
            if (!File.Exists(filePath))
            {
                throw new Exception("excel file not found.");
            }
            var file = new FileInfo(filePath);
            var excelPackage = new ExcelPackage(file);
            if (excelPackage.Workbook == null || excelPackage.Workbook.Worksheets.Count <= 0)
            {
                throw new Exception("read excel failed.");
            }
            var messages = new List<string>();

            sheet = excelPackage.Workbook.Worksheets.First();
            var columnCount = sheet.Dimension.End.Column;

            var endRow = sheet.Dimension.Rows;
            for (var row = 2; row <= sheet.Dimension.Rows; row++)
            {
                var columnValues = new List<string>();
                for (var i = 1; i <= columnCount; 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 i = 2; i <= endRow; i++)
            {
                for (var j = 1; j <= columnCount; j++)
                {
                    if (j <= levelCount)
                    {
                        var value = sheet.Cells[i, j].Value;
                        if (string.IsNullOrEmpty(value?.ToString()))
                        {
                            messages.Add($"{i},{(int)ImportEnum.MachineLevelIsEmpty}");
                        }
                    }
                    else
                    {
                        if (j == levelCount + 1) //加工程序号
                        {
                            var value = sheet.Cells[i, j].Value;
                            if (string.IsNullOrEmpty(value?.ToString()))
                            {
                                messages.Add($"{i},{(int)ImportEnum.ProgramNoIsEmpty}");
                            }
                        }

                        if (j == levelCount + 3) //产品图纸号
                        {
                            var value = sheet.Cells[i, j].Value;
                            if (string.IsNullOrEmpty(value?.ToString()))
                            {
                                messages.Add($"{i},{(int)ImportEnum.ProductDrawCodeIsEmpty}");
                            }
                        }

                        if (j == levelCount + 4) //工序名称
                        {
                            var value = sheet.Cells[i, j].Value;
                            if (string.IsNullOrEmpty(value?.ToString()))
                            {
                                messages.Add($"{i},{(int)ImportEnum.RouteNameIsEmpty}");
                            }
                        }

                        if (j == levelCount + 5) //标准节拍
                        {
                            var value = sheet.Cells[i, j].Value;
                            if (string.IsNullOrEmpty(value?.ToString()))
                            {
                                messages.Add($"{i},{(int)ImportEnum.BeatSetIsEmpty}");
                            }
                        }

                        if (j == levelCount + 7) //日标准产量
                        {
                            var value = sheet.Cells[i, j].Value;
                            if (string.IsNullOrEmpty(value?.ToString()))
                            {
                                messages.Add($"{i},{(int)ImportEnum.OutputIsEmpty}");
                            }
                        }
                        if (j == levelCount + 11) //开始时间
                        {
                            var value = sheet.Cells[i, j].Value;
                            if (string.IsNullOrEmpty(value?.ToString()))
                            {
                                //messages.Add($"{i},{(int)ImportEnum.StartTimeIsEmpty}");
                            }
                            else
                            {
                                var success = DateTime.TryParse(value.ToString(), out var dt);
                                if (!success)
                                {
                                    messages.Add($"{i},{(int)ImportEnum.DateTimeIsInValid}");
                                }
                            }
                        }
                        if (j == levelCount + 12) //结束时间
                        {
                            var value = sheet.Cells[i, j].Value;
                            if (string.IsNullOrEmpty(value?.ToString()))
                            {
                                //messages.Add($"{i},{(int)ImportEnum.EndTimeIsEmpty}");
                            }
                            else
                            {
                                var success = DateTime.TryParse(value.ToString(), out var dt);
                                if (!success)
                                {
                                    messages.Add($"{i},{(int)ImportEnum.DateTimeIsInValid}");
                                }
                            }
                        }
                    }
                }
            }

            return messages;
        }

        public IEnumerable<BeatSetEntity> ConvertSheetToList(int levelCount)
        {
            var list = new List<BeatSetEntity>();
            if (sheet == null)
            {
                throw new Exception("read excel failed.");
            }
            var columnCount = sheet.Dimension.End.Column;

            var endRow = 2;
            for (var row = 2; row <= sheet.Dimension.Rows; row++)
            {
                var columnValues = new List<string>();
                for (var i = 1; i <= columnCount; 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;
            }

            for (var i = 2; i <= endRow; i++)
            {
                var entity = new BeatSetEntity();
                for (var j = 1; j <= columnCount; j++)
                {
                    var value = sheet.Cells[i, j].Value?.ToString();
                    if (j <= levelCount)
                    {
                        entity.Levels.Add(value);
                    }
                    else
                    {
                        if (j == levelCount + 1) //加工程序号
                        {
                            entity.ProgramNo = value ?? "";
                        }
                        if (j == levelCount + 2) //产品名称
                        {
                            entity.ProductName = value ?? "";
                        }
                        if (j == levelCount + 3) //产品图纸号
                        {
                            entity.ProductDrawingCode = value ?? "";
                        }
                        if (j == levelCount + 4) //工序名称
                        {
                            entity.RouteName = value ?? "";
                        }
                        if (j == levelCount + 5) //标准节拍
                        {
                            entity.CycleTime = value ?? "";
                        }
                        if (j == levelCount + 6) //上下料节拍
                        {
                            entity.UpDownBesat = value ?? "";
                        }
                        if (j == levelCount + 7) //日标准产量
                        {
                            entity.OutPut = value ?? "";
                        }
                        if (j == levelCount + 8) //换型时间
                        {
                            entity.ChangeModelTime = value ?? "";
                        }
                        if (j == levelCount + 9) //产量系数
                        {
                            entity.YieldRate = value ?? "1";
                        }
                        if (j == levelCount + 10) //工序顺序
                        {
                            entity.RouteNumber = value ?? "";
                        }
                        if (j == levelCount + 11) //开始时间
                        {
                            entity.StartTime = value ?? "";
                        }
                        if (j == levelCount + 12) //结束时间
                        {
                            entity.EndTime = value ?? "";
                        }
                    }
                }
                list.Add(entity);
            }

            return list;
        }

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