using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using NPOI.HSSF.UserModel;
/// <summary>
/// 功能: 建立顯示處理結果的物件，包含檔案清單、處理過的影像，萃取資訊的小圖與處理程序產生出來的紀錄。
/// 維護: 
/// [108/04/24][15:33] > 完成基礎代碼撰寫，未測試。
/// 建立於: 108/04/24
/// </summary>
namespace ETC_App1
{
    public partial class ETCPictureCheckBox : UserControl
    {
        private Image LostImage = new Bitmap("data" + Path.DirectorySeparatorChar + "lost.jpg");

        private Image BrokeImage = new Bitmap("data" + Path.DirectorySeparatorChar + "broke.jpg");

        public List<Json> Data = new List<Json>();

        public string UsingID { get; set; }

        public Color ErrorColor { get; set; } = Color.Red;

        public Color WarningColor { get; set; } = Color.Blue;

        public long Success { get; set; } = 0;

        public long Failed { get; set; } = 0;

        public long Lost { get; set; } = 0;

        public long Tickoff { get; set; } = 0;
        public ETCPictureCheckBox()
        {
            InitializeComponent();
        }

        public new bool Visible
        {
            set
            {
                base.Visible = value;

                toolStripStatusLabel1.Text = toolStripStatusLabel2.Text = toolStripStatusLabel3.Text = toolStripStatusLabel4.Text = string.Empty;
            }
            get => base.Visible;
        }

        private int StatusStripWidth
        {
            set
            {
                toolStripProgressBar1.Size = new Size(value / 10, toolStripProgressBar1.Size.Height);

                toolStripStatusLabel1.Size = new Size(value * 9 / 10, toolStripStatusLabel1.Size.Height);
            }
        }

        public string ToolStripStatusLabel1
        {
            set => toolStripStatusLabel1.Text = value;
            get => toolStripStatusLabel1.Text;
        }

        public string ToolStripStatusLabel2
        {
            set => toolStripStatusLabel2.Text = value;
            get => toolStripStatusLabel2.Text;
        }

        public string ToolStripStatusLabel3
        {
            set => toolStripStatusLabel3.Text = value;
            get => toolStripStatusLabel3.Text;
        }

        public string ToolStripStatusLabel4
        {
            set => toolStripStatusLabel4.Text = value;
            get => toolStripStatusLabel4.Text;
        }

        public int ToolStripProgressBar
        {
            set => toolStripProgressBar1.Value = value;
            get => toolStripProgressBar1.Value;
        }

        public int SelectedIndex
        {
            set => listBox1.SelectedIndex = value;
            get => listBox1.SelectedIndex;
        }

        public Image Image1 { get => etcPictureBox1.Image; set => etcPictureBox1.Image = value; }

        public Image Image2 { get => etcPictureBox2.Image; set => etcPictureBox2.Image = value; }

        public ListBox.ObjectCollection Item1 { get => listBox1.Items; }

        public ListBox.ObjectCollection Item2 { get => listBox2.Items; }

        public void Add(Json json)
        {
            Data.Add(json);

            Success = Success + (json.success ? 1 : 0);

            Failed = Failed + (!json.success ? 1 : 0);

            Lost = Lost + (json.lost1 ? 1 : 0);

            listBox1.Items.Add((json.lost2 ? "" : json.index + ". ") + (json.success ? json.message1 : "資料異常"));

            listBox2.Items.Add((json.lost2 ? json.filename + "，" : json.index + ". ") + (json.success ? json.message1 : (json.lost1?json.filename:json.message2)));

            listBox1.SelectedIndex = listBox1.Items.Count - 1;

            listBox2.SelectedIndex = listBox2.Items.Count - 1;
        }

        public void Clear()
        {
            listBox1.Items.Clear();

            listBox2.Items.Clear();
        }

        private void EtcStatusStrip1_Resize(object sender, EventArgs e)
        {
            StatusStripWidth = etcStatusStrip1.Size.Width;
        }

        private void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex > -1)
            {
                Json json = Data[listBox1.SelectedIndex];

                if ((json.success || json.failed || json.lost2) && json.content && File.Exists(json.filename))
                {
                    MemoryStream memory = new MemoryStream();

                    using (FileStream file = new FileStream(json.filename, FileMode.Open))
                    {
                        file.CopyTo(memory);

                        file.Close();

                        memory.Flush();
                    }

                    Bitmap image = new Bitmap(memory);

                    if (json.roi != null)
                    {
                        Rectangle rect = new Rectangle(json.roi.x, json.roi.y, json.roi.w, json.roi.h);

                        bool success = false;

                        while (!success)
                        {
                            try
                            {
                                etcPictureBox2.Image = image.Clone(rect, image.PixelFormat);

                                etcPictureBox2.Refresh();

                                success = true;
                            }
                            catch { success = false; }
                        }
                    }
                    else
                    {
                        etcPictureBox2.Image = null;

                        etcPictureBox2.Refresh();
                    }

                    etcPictureBox1.Image = image;

                    etcPictureBox1.Refresh();
                }
                else if (json.lost1)
                {
                    etcPictureBox1.Image = LostImage;

                    etcPictureBox2.Image = null;
                }
                else if (!json.content)
                {
                    etcPictureBox1.Image = BrokeImage;

                    etcPictureBox2.Image = null;
                }

                button1.Text = json.success ? "第 " + json.index + " 筆資料檢查正確。" : button1.Text;

                button1.ForeColor = json.success ? Color.Green : button1.ForeColor;

                button1.Text = json.failed ? "第 " + json.index + " 筆資料異常！" : button1.Text;

                button1.ForeColor = json.failed ? WarningColor : button1.ForeColor;

                button1.Text = !json.content ? "第 " + json.index + " 筆影像損毀！" : button1.Text;

                button1.ForeColor = !json.content ? ErrorColor : button1.ForeColor;

                button1.Text = json.lost1 ? "第 " + json.index + " 筆影像遺失！" : button1.Text;

                button1.ForeColor = json.lost1 ? ErrorColor : button1.ForeColor;

                button1.Text = json.lost2 ? "缺少比對資料！" : button1.Text;
                
                button1.ForeColor = json.lost2 ? ErrorColor : button1.ForeColor;

                button1.Text = json.success && json.failed ? "正確" : button1.Text;

                button1.ForeColor = json.success ? Color.Green : button1.ForeColor;
            }

            listBox2.SelectedIndex = listBox1.SelectedIndex;
        }

        private void ListBox1_DrawItem(object sender, DrawItemEventArgs e)
        {
            if (e.Index > -1)
            {
                string s = listBox1.Items[e.Index] as string;

                Font f = listBox1.Font;

                SolidBrush brush = new SolidBrush(listBox1.ForeColor);

                brush = Data[e.Index].failed ? new SolidBrush(WarningColor) : brush;

                brush = Data[e.Index].lost1 || Data[e.Index].lost2 ? new SolidBrush(ErrorColor) : brush;

                f = Data[e.Index].tickoff ? new Font(f.FontFamily, f.Size, FontStyle.Strikeout) : f;

                e.DrawBackground();

                e.Graphics.DrawString(s, f, brush, e.Bounds);
            }
        }

        private void ListBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            listBox1.SelectedIndex = listBox2.SelectedIndex;
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            if (button1.Text == "正確")
            {
                Data[listBox1.SelectedIndex].failed = false;
                Data[listBox1.SelectedIndex].message1 = Data[listBox1.SelectedIndex].message1+"["+UsingID+"]";
                listBox1.Items[listBox1.SelectedIndex] = listBox1.SelectedIndex + "." + Data[listBox1.SelectedIndex].message1;
                listBox2.Items[listBox1.SelectedIndex] = listBox2.SelectedIndex + "." + Data[listBox1.SelectedIndex].message1;
            }
        }

        private void Button2_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex < listBox1.Items.Count - 1)
            {
                for (int i = listBox1.SelectedIndex; i < listBox1.Items.Count; i++)
                {
                    if(Data[i].success && Data[i].failed)
                    {
                        listBox1.SelectedIndex = i;
                        break;

                    }
                };
            }
        }

        public void SaveLogs(string save_path)
        {
            string file_path = save_path + "/log.txt";

            FileStream fs = new FileStream(@file_path, FileMode.Create, FileAccess.ReadWrite);
            StreamWriter sw = new StreamWriter(fs, Encoding.Default);
            int success = 0;
            int noimg = 0;
            int nodata = 0;
            for (int i = 0; i < Data.Count; i++)
            {
                string msg = "";
                if (Data[i].lost2)
                {
                    msg = msg + Data[i].filename + "，"+ Data[i].message2;
                    nodata++;
                }
                else if(Data[i].success)
                {
                    msg = msg + i + "." + Data[i].message1;
                    success++;
                }
                else if (Data[i].lost1)
                {
                    msg = msg + i + "." + Data[i].filename;
                    noimg++;
                }
                sw.WriteLine(msg);
            }
            sw.WriteLine("完全正確:"+success+" 找不到圖片:"+noimg+" 缺少比對資料:"+nodata);


            sw.Close();
            fs.Close();

        }
        public void SaveExcel(string save_path)
        {
            HSSFWorkbook workbook2003 = new HSSFWorkbook(); //新建工作簿
            workbook2003.CreateSheet("Sheet1");  //新建1個Sheet工作表            
            HSSFSheet SheetOne = (HSSFSheet)workbook2003.GetSheet("Sheet1"); //獲取名稱為Sheet1的工作表
            for (int i = 1; i < 13; i++)    //列數
            {
                SheetOne.CreateRow(i);
                for (int j = 0; j < 20; j++)    //行數
                {
                    SheetOne.GetRow(i).CreateCell(j).SetCellValue(1);
                }
            }
            FileStream file2003 = new FileStream("C:\\Users\\admin\\e-eye\\eee.xls", FileMode.Create);
            workbook2003.Write(file2003);
            file2003.Close();
            workbook2003.Close();
        }
    }
}
