using HKLib.Dto;
using HKLib.Interfaces;
using HKLib.SQLHelper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HKCardManager.UserPages
{
    public partial class ReportFormPage : UserControl
    {
        private int PageSize = 10;
        private int Total;
        private int PageIndex;
        private double TotalPage;
        public ReportFormPage()
        {
            InitializeComponent();
            dataGridView1.AutoGenerateColumns = false;
            button2.Enabled = false;
            DataGridViewInit();
            PageIndex = 1;
            TotalPage = 0;
            Total = 0;
            this.button3.Enabled = false;
            this.button4.Enabled = false;
        }


        private void DataGridViewInit()
        {
            dataGridView1.AllowUserToResizeRows = false;
            dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            dataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;
        }

        private void ExportDataToExcel(DataGridView TableName, string FileName)
        {
            try
            {
                var d = TableName.DataSource as List<ReportCountDto>;
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Title = "导出Excel文件";  //设置文件标题
                saveFileDialog.Filter = "Microsoft Office Excel 工作簿(*.xls)|*.xls"; //设置文件类型
                saveFileDialog.FilterIndex = 1; //设置默认文件类型显示顺序  
                saveFileDialog.AddExtension = true; //是否自动在文件名中添加扩展名
                saveFileDialog.RestoreDirectory = true; //是否记忆上次打开的目录
                saveFileDialog.FileName = FileName; //设置默认文件名
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    string localFilePath = saveFileDialog.FileName.ToString();
                    //数据初始化
                    int TotalCount;     //总行数
                    int RowRead = 0;    //已读行数
                    int Percent = 0;    //百分比
                    TotalCount = TableName.Rows.Count;
                    Stream myStream = saveFileDialog.OpenFile();
                    Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                    StreamWriter sw = new StreamWriter(myStream, Encoding.GetEncoding("gb2312"));
                    string strHeader = string.Empty;

                    Stopwatch timer = new Stopwatch();
                    timer.Start();

                    try
                    {
                        //写入标题
                        for (int i = 0; i < TableName.Columns.Count; i++)
                        {
                            if (TableName.Columns[i].Visible)
                            {
                                if (i > 0 && !string.IsNullOrEmpty(strHeader)) strHeader += "\t";
                                strHeader += TableName.Columns[i].HeaderText.ToString();
                            }
                        }
                        sw.WriteLine(strHeader);
                        for (int i = 0; i < TableName.Rows.Count + 1; i++)
                        {
                            RowRead++;
                            Percent = (int)(100 * RowRead / (TotalCount + 1));
                            Application.DoEvents();
                            string strData = string.Empty;
                            for (int j = 0; j < TableName.Columns.Count; j++)
                            {
                                if (i == TableName.Rows.Count)
                                {
                                    if (TableName.Columns[j].Visible && TableName.Columns[j].Name == "早上消费金额")
                                    {
                                        if (j > 0 && !string.IsNullOrEmpty(strData)) strData += "\t";
                                        strData += d.Sum(t => t.AM);
                                    }
                                    else if (TableName.Columns[j].Visible && TableName.Columns[j].Name == "中午消费金额")
                                    {
                                        if (j > 0 && !string.IsNullOrEmpty(strData)) strData += "\t";
                                        strData += d.Sum(t => t.PM);
                                    }
                                    else if (TableName.Columns[j].Visible && TableName.Columns[j].Name == "晚上消费金额")
                                    {
                                        if (j > 0 && !string.IsNullOrEmpty(strData)) strData += "\t";
                                        strData += d.Sum(t => t.AT);
                                    }
                                    else if (TableName.Columns[j].Visible && TableName.Columns[j].Name == "金额总计")
                                    {
                                        if (j > 0 && !string.IsNullOrEmpty(strData)) strData += "\t";
                                        strData += d.Sum(t => t.Total);
                                    }
                                    else if (TableName.Columns[j].Visible)
                                    {
                                        if (j > 0 && !string.IsNullOrEmpty(strData)) strData += "\t";
                                        strData += "-";
                                    }
                                }
                                else
                                {
                                    if (i <= TableName.Rows.Count - 1)
                                    {
                                        string? res = TableName.Rows[i].Cells[j].Value?.ToString();
                                        if (TableName.Columns[j].Visible)
                                        {
                                            if (j > 0 && !string.IsNullOrEmpty(strData)) strData += "\t";
                                            strData += string.IsNullOrEmpty(res) ? "" : res;
                                        }
                                    }
                                }
                            }
                            sw.WriteLine(strData);
                        }
                        sw.Close();
                        myStream.Close();
                        timer.Reset();
                        timer.Stop();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    finally
                    {
                        sw.Close();
                        myStream.Close();
                        timer.Stop();
                    }
                    MessageLogNotify.GetInstance.Show("数据导出成功");
                }
            }
            catch (Exception)
            {
                MessageBox.Show("文件已被打开，请先关闭后在导出", "提示");
            }

        }
        List<ReportCountDto> reportCountDtos = new List<ReportCountDto>();
        //查询
        private async void button1_Click(object sender, EventArgs e)
        {
            string TagName = this.Tag.ToString();
            int type = 0;
            if (TagName == "月餐段消费表") type = 2;
            else if (TagName == "记次就餐天消费表") type = 1;
            else if (TagName == "月餐段汇总表") type = 3;

            this.Invoke(() => { button1.Enabled = false; });
            var res = await HKLibHelper.Report(new ReportDto() { StartTime = dateTimePicker1.Value, EndTime = dateTimePicker2.Value }, type);
            var price = SqlLogic.GetPrice();

            foreach (var item in res)
            {

                item.AM = price == null ? 0 : price.AM * item.AMCount;
                item.PM = item.PMCount >= 20 ? 75 : price == null ? 0 : price.PM * item.PMCount;
                item.AT = price == null ? 0 : price.AT * item.ATCount;
                item.Total = item.AM + item.PM + item.AT;
            }
            reportCountDtos = res;
            Total = res.Count;
            TotalPage = Math.Ceiling(Total * 1.0 / PageSize);
            res = res.Skip(0).Take(PageSize).ToList();
            label1.Text = $"{PageIndex}/{TotalPage}";
          
            if (res != null)
            {
                if (res.Count > 0)
                {
                    this.Invoke(() =>
                    {
                        this.button4.Enabled = true;
                        if (type == 1)
                        {
                            dataGridView1.Columns[0].Visible = true;
                            dataGridView1.Columns[1].Visible = false;
                            dataGridView1.Columns[2].Visible = true;
                            dataGridView1.Columns[3].Visible = false;
                        }
                        else if (type == 2)
                        {
                            dataGridView1.Columns[0].Visible = false;
                            dataGridView1.Columns[1].Visible = false;
                            dataGridView1.Columns[2].Visible = true;
                            dataGridView1.Columns[3].Visible = false;
                        }
                        else if (type == 3)
                        {
                            dataGridView1.Columns[0].Visible = true;
                            dataGridView1.Columns[1].Visible = false;
                            dataGridView1.Columns[2].Visible = false;
                            dataGridView1.Columns[3].Visible = true;
                        }
                        dataGridView1.DataSource = res;
                        button2.Enabled = true;
                    });
                    MessageLogNotify.GetInstance.Show("获取表数据成功");
                }
                else if (res.Count <= 0)
                {
                    MessageLogNotify.GetInstance.ShowWarning("未查询到数据");
                    this.Invoke(() => dataGridView1.DataSource = new List<ReportCountDto>());
                }
            }
            else
            {
                MessageLogNotify.GetInstance.ShowError("查询失败，请输入正确的时间段");
            }
            this.Invoke(() => { button1.Enabled = true; });

        }

        //导出
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                this.Invoke(() => { button2.Enabled = false; });
                dataGridView1.DataSource = reportCountDtos;
                ExportDataToExcel(dataGridView1, this.Tag.ToString());
                var data = reportCountDtos.Skip((PageIndex - 1) * PageSize).Take(PageSize).ToList();
                dataGridView1.DataSource = data;
            }
            catch (Exception ex)
            {
                MessageLogNotify.GetInstance.ShowEx(ex.ToString());
            }
            finally
            {
                this.Invoke(() => { button2.Enabled = true; });
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (PageIndex <= 1)
            {
                this.button3.Enabled = false;
                return;
            }
            PageIndex = PageIndex - 1;
      
            var data = reportCountDtos.Skip((PageIndex - 1) * PageSize).Take(PageSize).ToList();
            dataGridView1.DataSource = data;
            this.button4.Enabled = true;
            label1.Text = $"{PageIndex}/{TotalPage}";
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (PageIndex >= TotalPage)
            {
                this.button4.Enabled = false;
                return;
            }
            PageIndex = PageIndex + 1;

            var data = reportCountDtos.Skip((PageIndex - 1) * PageSize).Take(PageSize).ToList();
            dataGridView1.DataSource = data;
            this.button3.Enabled = true;
            label1.Text = $"{PageIndex}/{TotalPage}";

        }
    }
}
