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 ProductionControl.UI
{
    public partial class UIPagination : UserControl
    {
        /// <summary>
        /// 1-n
        /// </summary>
        public int CurrentPage { get; private set; } = 1; 
        /// <summary>
        /// 每页条数
        /// </summary>
        public int PageSize { get; set; } = 20;
        /// <summary>
        /// 总条数
        /// </summary>
        public int TotalCount { get; set; } = 0;
        /// <summary>
        ///  
        /// </summary>
        public Action refresh;

        /// <summary>
        /// 总页数
        /// </summary>
        private int TotalPages
        {
            get { return (int)(TotalCount * 1.0f / PageSize + 0.5); }
        }

        public UIPagination()
        {
            InitializeComponent();
        }

        private void UIPagination_Load(object sender, EventArgs e)
        {
            this.cobPageNum.Items.Add(1);
        }
        private void freshUI()
        {
            this.btnFirst.Enabled = this.btnPre.Enabled = (CurrentPage > 1);
            this.btnLast.Enabled = this.btnNext.Enabled = (CurrentPage < TotalPages);
            if (CurrentPage > TotalPages) 
                CurrentPage = TotalPages; 

            this.lblPagesCount.Text = $"/{TotalPages}页";
            int liTotalPages = TotalPages;
            while (this.cobPageNum.Items.Count != liTotalPages)
            {
                if (this.cobPageNum.Items.Count > liTotalPages)
                    this.cobPageNum.Items.RemoveAt(this.cobPageNum.Items.Count - 1);
                else
                    this.cobPageNum.Items.Add(this.cobPageNum.Items.Count + 1);
            }
        }

        private void numPageSize_ValueChanged(object sender, EventArgs e)
        {
            PageSize = (int)numPageSize.Value; 
            freshUI();  
            refresh?.Invoke();
        }

        private void btnPre_Click(object sender, EventArgs e)
        {
            CurrentPage--;
            freshUI();
            refresh?.Invoke();
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            CurrentPage++;
            freshUI();
            refresh?.Invoke();
        }

        private void btnFirst_Click(object sender, EventArgs e)
        {
            CurrentPage = 1;
            freshUI();
            refresh?.Invoke();
        }

        private void btnLast_Click(object sender, EventArgs e)
        {
            CurrentPage = TotalPages;
            freshUI();
            refresh?.Invoke();
        }

        private void cobPageNum_SelectedIndexChanged(object sender, EventArgs e)
        {
            CurrentPage = cobPageNum.SelectedIndex + 1;
            freshUI();
            refresh?.Invoke();
        }

    }
}
