using Esoft;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Excel = Microsoft.Office.Interop.Excel;
using Word = Microsoft.Office.Interop.Word;
using System.Windows.Forms.DataVisualization.Charting;
using System.Windows.Forms.Integration;

namespace Esoft.Pages
{
    /// <summary>
    /// Логика взаимодействия для Diagram.xaml
    /// </summary>
    public partial class Diagram : Window
    {
        private user6Entities _context = new user6Entities();
        List<string> listStatus = new List<string>()
        {
            "запланирована", "выполнена", "отменена", "исполняется"
        };
        public Diagram()
        {
            InitializeComponent();
            ChartPayments.ChartAreas.Add(new ChartArea("Main"));

            var currentSeries = new Series("Количество")
            {
                IsValueShownAsLabel = true
            };
            ChartPayments.Series.Add(currentSeries);

            ComboExecutor.ItemsSource = listStatus;
            ComboChartTypes.ItemsSource = Enum.GetValues(typeof(SeriesChartType));
        }
        private void UpdateChart(object sender, SelectionChangedEventArgs e)
        {
            if (ComboExecutor.SelectedItem is string value &&
                ComboChartTypes.SelectedItem is SeriesChartType chartType)
            {
                Series currentSeries = ChartPayments.Series.FirstOrDefault();
                currentSeries.ChartType = chartType;
                currentSeries.Points.Clear();

                var categoriesList = _context.Task.ToList();
                currentSeries.Points.AddXY(value, categoriesList.Where(x => x.Status == value).Count());
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (Owner != null)
                Owner.IsEnabled = false;
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            if (Owner != null)
                Owner.IsEnabled = true;
        }

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void btnMinimize_Click(object sender, RoutedEventArgs e)
        {
            WindowState = WindowState.Minimized;
        }

        private void Window_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed) { DragMove(); }
        }

        private void btnExcel_Click(object sender, RoutedEventArgs e)
        {
            var allTask = _context.Task.ToList();
            var executor = _context.Executor.ToList();

            var application = new Excel.Application();
            application.SheetsInNewWorkbook = executor.Count();

            Excel.Workbook workbook = application.Workbooks.Add(Type.Missing);


            for (int i = 0; i < executor.Count(); i++) 
            {
                int startRowIndex = 1;
                Excel.Worksheet worksheet = application.Worksheets.Item[i + 1];
                worksheet.Name = executor[i].User.MiddleName;

                worksheet.Cells[1][startRowIndex] = "Менеджер";
                worksheet.Cells[2][startRowIndex] = "Статус задачи";
                worksheet.Cells[3][startRowIndex] = "Тип работы";
                worksheet.Cells[4][startRowIndex] = "Время на выполнение";
                worksheet.Cells[5][startRowIndex] = "Время на выполнение в часах";
                worksheet.Cells[6][startRowIndex] = "Сложность";

                startRowIndex++;

                foreach (var titleTask in allTask.Where(x => x.Executor.User.MiddleName == executor[i].User.MiddleName))
                {
                    Excel.Range headerRange = worksheet.Range[worksheet.Cells[1][startRowIndex], worksheet.Cells[8][startRowIndex]];
                    headerRange.Merge();
                    headerRange.Value = titleTask.Title;
                    headerRange.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                    headerRange.Font.Italic = true;

                    startRowIndex++;

                    foreach (var mainDateTask in allTask.Where(x => x.Executor.User.MiddleName == executor[i].User.MiddleName))
                    {
                        worksheet.Cells[1][startRowIndex] = mainDateTask.Executor.Manager.User.MiddleName;
                        worksheet.Cells[2][startRowIndex] = mainDateTask.Status;
                        worksheet.Cells[3][startRowIndex] = mainDateTask.WorkType;
                        worksheet.Cells[4][startRowIndex] = mainDateTask.Time;

                        worksheet.Cells[5][startRowIndex].Formula = $"=F{startRowIndex}/60";

                        worksheet.Cells[8][startRowIndex] = mainDateTask.Difficulty;
                        worksheet.Cells[8][startRowIndex].NumberFormat =
                            worksheet.Cells[8][startRowIndex].NumberFormat = "0";

                        startRowIndex++;
                    }
                }

                Excel.Range cauntTask = worksheet.Range[worksheet.Cells[1][startRowIndex], worksheet.Cells[7][startRowIndex]];
                cauntTask.Merge();
                cauntTask.Value = "Итоговое количество задач:";
                cauntTask.HorizontalAlignment = Excel.XlHAlign.xlHAlignRight;

                worksheet.Cells[8][startRowIndex] = allTask.Where(x => x.ExecutorID == executor[i].ID).ToList().Count();

                startRowIndex++;

                Excel.Range rangBorder = worksheet.Range[worksheet.Cells[1][1], worksheet.Cells[8][startRowIndex - 1]];
                rangBorder.Borders[Excel.XlBordersIndex.xlEdgeBottom].LineStyle =
                    rangBorder.Borders[Excel.XlBordersIndex.xlEdgeLeft].LineStyle =
                    rangBorder.Borders[Excel.XlBordersIndex.xlEdgeRight].LineStyle =
                    rangBorder.Borders[Excel.XlBordersIndex.xlEdgeTop].LineStyle =
                    rangBorder.Borders[Excel.XlBordersIndex.xlInsideVertical].LineStyle =
                    rangBorder.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle = Excel.XlLineStyle.xlContinuous;

                worksheet.Columns.AutoFit();
            }
            application.Visible = true;
        }

        private void btnWord_Click(object sender, RoutedEventArgs e)
        {
            var allTask = _context.Task.ToList();
            var allExecuters = _context.Executor.ToList();

            var application = new Word.Application();

            Word.Document document = application.Documents.Add();

            foreach (var ex in allExecuters)
            {
                Word.Paragraph executerParagraph = document.Paragraphs.Add();
                Word.Range executerRange = executerParagraph.Range;
                executerRange.Text = ex.User.MiddleName;
                executerParagraph.set_Style("Заголовок");
                executerRange.InsertParagraphAfter();


                Word.Paragraph tableParagraph = document.Paragraphs.Add();
                Word.Range tableRange = tableParagraph.Range;
                Word.Table tasksTable = document.Tables.Add(tableRange,
                    allExecuters.Count(), 3);
                tasksTable.Borders.InsideLineStyle = tasksTable.Borders.OutsideLineStyle
                    = Word.WdLineStyle.wdLineStyleSingle;
                tasksTable.Range.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                Word.Range cellRange;

                cellRange = tasksTable.Cell(1, 1).Range;
                cellRange.Text = "Название задачи";
                cellRange = tasksTable.Cell(1, 2).Range;
                cellRange.Text = "Крайняя дата задачи";
                cellRange = tasksTable.Cell(1, 3).Range;
                cellRange.Text = "Статус";

                tasksTable.Rows[1].Range.Bold = 1;
                tasksTable.Rows[1].Range.Paragraphs.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;

                for (int i = 1; i < allExecuters.Count(); i++)
                {
                    cellRange = tasksTable.Cell(i + 2, 1).Range;
                    cellRange.Text = allTask[i].Title;

                    cellRange = tasksTable.Cell(i + 2, 2).Range;
                    cellRange.Text = allTask[i].Deadline.ToString();

                    cellRange = tasksTable.Cell(i + 2, 3).Range;
                    cellRange.Text = allTask[i].Status;
                }

                if (ex != allExecuters.LastOrDefault())
                    document.Words.Last.InsertBreak(Word.WdBreakType.wdPageBreak);
            }
            application.Visible = true;
        }
    }
}
