using ProjectManagementSystem.Device.CasunBox;
using ProjectManagementSystem.Common.Core;
using ProjectManagementSystem.Common.Device;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ProjectManagementSystem.UI
{
    public partial class CallBoxUI : UserControl, IDisplayUI
    {
        private int selectRowIndexOfordersDataGridView;         // 记录选中的行号
        private int selectColumnIndexOfordersDataGridView;      // 记录选中的列号
        private int scrollingRowIndexOfordersDataGridView;      // 记录垂直滚动条位置
        private int scrollingColumnIndexOfordersDataGridView;   // 记录水平滚动条的位置

        public CallBoxUI()
        {
            InitializeComponent();

            dataGridView1.AutoGenerateColumns = false;
        }

        public bool Init()
        {
            return true;
        }

        public void UpdateDisplay()
        {
            if (!this.Visible)
            {
                return;
            }

            this.Invoke(new MethodInvoker(() =>
            {
                this.SuspendLayout();
                if (dataGridView1.CurrentCell != null && dataGridView1.RowCount != 0 && dataGridView1.ColumnCount != 0)
                {
                    selectRowIndexOfordersDataGridView = dataGridView1.CurrentCell.RowIndex;
                    selectColumnIndexOfordersDataGridView = dataGridView1.CurrentCell.ColumnIndex;
                    scrollingRowIndexOfordersDataGridView = dataGridView1.FirstDisplayedScrollingRowIndex;
                    scrollingColumnIndexOfordersDataGridView = dataGridView1.FirstDisplayedScrollingColumnIndex;
                }
                var allInfoBox = BoxFactory.GetInfoBox();
                this.dataGridView1.DataSource = allInfoBox?.OrderBy(d => d.Name).ThenBy(d => d.Route).ToList();

                int n = dataGridView1.RowCount;
                int m = dataGridView1.ColumnCount;

                if (n != 0 && m != 0)
                {
                    if (selectRowIndexOfordersDataGridView < n && selectColumnIndexOfordersDataGridView < m &&
                        scrollingRowIndexOfordersDataGridView < n && scrollingColumnIndexOfordersDataGridView < m)
                    {
                        dataGridView1.CurrentCell = dataGridView1.Rows[selectRowIndexOfordersDataGridView].Cells[selectColumnIndexOfordersDataGridView];
                        dataGridView1.FirstDisplayedScrollingRowIndex = scrollingRowIndexOfordersDataGridView;
                        dataGridView1.FirstDisplayedScrollingColumnIndex = scrollingColumnIndexOfordersDataGridView;
                    }
                }

                this.ResumeLayout(false);
            }));

        }
    }
}

