using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using MESClassLibrary.BLL.BasicInfo;
using MESClassLibrary.BLL.Log;
using MESClassLibrary.Model;

namespace InjectionPC
{
    public partial class FrmQuality : Form
    {
        private static string position = "", reason = "";
        int count = 0; //缺陷图选择个数
        public FrmQuality()
        {
            InitializeComponent();
        }

        private void label9_Click(object sender, EventArgs e)
        {
            this.Close();
            //OnVisibleChanged()
        }

        protected override void OnVisibleChanged(EventArgs e)
        {
            base.OnVisibleChanged(e);
            if (!IsHandleCreated)
            {
                this.Close();
            }
        }

        private void FrmQuality_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            string LineID = "";
            label6.Text = Program.station;
            label8.Text = Program.OperatorName;
            comboBox1.Text = Program.Shift;
            textBox3.TabIndex = 0;
            textBox3.Focus();
            Thread t = new Thread(new ThreadStart(TimeGo));
            t.Start();
            #region 测试

            //获取服务器上图片
            //Ping p1 = new Ping();
            //bool status = false;

            //PingReply reply = p1.Send(Program.IP); //发送主机名或Ip地址
            //StringBuilder sbuilder;
            //if (reply.Status == IPStatus.Success)
            //{
            //    status = Upload.DoConnComputer(Program.IP, "aa", "Administrator", "Wff775168+");
            //    if (status == true)
            //    {
            //        //共享文件夹的目录
            //        DirectoryInfo theFolder = new DirectoryInfo(@"\\" + Program.IP + "\\aa\\");                
            //        string filename = theFolder.ToString();                
            //        //执行方法
            //        TransportRemoteToLocal(@"D:\车间.png", filename, "车间.png");    //实现将远程服务器文件写入到本地
            //    }
            //}
            //FileStream fs = new FileStream("D:\\2.jpg", FileMode.Open,
            //    FileAccess.Read);//获取图片文件流
            //Image img = Image.FromStream(fs); // 文件流转换成Image格式
            //pictureBox2.Image = img;   //给 图片框设置要显示的图片
            //fs.Close(); // 关闭流,释放图片资源

            //Label[] lb = new Label[5];
            //string[] str = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O" };

            //for (int i = 0; i < 5; i++)
            //{
            //    for (int j = 0; j < 3; j++)
            //    {
            //        lb[i] = new Label();
            //        lb[i].Text = str[i].ToString();
            //        lb[i].Font = new Font(lb[i].Font.FontFamily, 32, FontStyle.Bold);

            //        lb[i].Size = new Size(pictureBox2.Width / 5, pictureBox2.Height / 3);
            //        lb[i].Location = new Point(0 + i * lb[i].Size.Width, 0 + j * lb[i].Size.Height);
            //        lb[i].BorderStyle = BorderStyle.FixedSingle;
            //        lb[i].BackColor = Color.Transparent;
            //        lb[i].TextAlign = ContentAlignment.MiddleCenter;
            //        pictureBox2.Controls.Add(lb[i]);

            //        lb[i].Click += new EventHandler(lblRoom_Click);
            //    }
            //}
            //StationBLL sbll = new StationBLL();
            //DataTable sdt = sbll.SearchInfoByNo(Program.station);
            //if (sdt != null && sdt.Rows.Count > 0)
            //{
            //    LineID = sdt.Rows[0]["LineID"].ToString();
            //}
            //sdt.Dispose();

            //int row = 0, col = 6;

            //DefectBLL dbll = new DefectBLL();
            //DataTable dt3 = dbll.SearchInfo(LineID);
            //if (dt3 != null && dt3.Rows.Count > 0)
            //{
            //    row = Convert.ToInt32(Math.Ceiling((double)dt3.Rows.Count / 6));
            //    Label[] dLb = new Label[7];
            //    string[] dstr = new string[dt3.Rows.Count];


            //    for (int i = 0; i < dt3.Rows.Count; i++)
            //    {
            //        dstr[i] = dt3.Rows[i]["DefectName"].ToString();
            //    }

            //    for (int i = 0; i < 6; i++)  //列
            //    {
            //        for (int j = 0; j < row;j++)   //行
            //        {
            //            dLb[i] = new Label();
            //            if ((i + 6 * j) < dstr.Length)
            //            {
            //                dLb[i].Text = dstr[i + 6 * j].ToString();
            //                dLb[i].Font = new Font(dLb[i].Font.FontFamily, 24, FontStyle.Bold);

            //                dLb[i].Size = new Size(150, 50);
            //                dLb[i].Location = new Point(20 + i * (dLb[i].Size.Width+25), 5 + j * (dLb[i].Size.Height+20));
            //                dLb[i].BorderStyle = BorderStyle.FixedSingle;
            //                dLb[i].BackColor = Color.Transparent;
            //                dLb[i].TextAlign = ContentAlignment.MiddleCenter;
            //                panel2.Controls.Add(dLb[i]);
            //            }
            //        }
            //    }
            //}

            #endregion


        }


        private void TimeGo()
        {
            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Interval = 1000;
            timer.Enabled = true;
            timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Tick);
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            label2.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            Thread.Sleep(500);
        }


        /// <summary>
        /// 从远程服务器下载文件到本地
        /// </summary>
        /// <param name="src">下载到本地后的文件路径,包含文件的扩展名</param>
        /// <param name="dst">远程服务器路径(共享文件夹路径)</param>
        /// <param name="fileName">远程服务器(共享文件夹)中的文件名称,包含扩展名</param>
        public static void TransportRemoteToLocal(string src, string dst, string fileName)   //src:下载到本地后的文件路径     dst:远程服务器路径    fileName:远程服务器dst路径下的文件名
        {
            try
            {
                FileStream inFileStream = new FileStream(src, FileMode.Open); //远程服务器文件  此处假定远程服务器共享文件夹下确实包含本文件,否则程序报错

                if (!Directory.Exists(dst))
                {
                    Directory.CreateDirectory(dst);
                }
                dst = dst + fileName;
                FileStream outFileStream = new FileStream(dst, FileMode.OpenOrCreate);   //从远程服务器下载到本地的文件
                byte[] buf = new byte[inFileStream.Length];
                int byteCount;
                while ((byteCount = inFileStream.Read(buf, 0, buf.Length)) > 0)
                {
                    outFileStream.Write(buf, 0, byteCount);
                }
                inFileStream.Flush();
                inFileStream.Close();
                outFileStream.Flush();
                outFileStream.Close();
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }
        }

        void lblRoom_Click(object sender, EventArgs e)
        {
            Label a = (Label) sender;
            //foreach (Control c  in pictureBox2.Controls)
            //{
            //    c.BackColor = Color.Transparent;
            //}
            if (a.BackColor == Color.Transparent)
            {
                a.BackColor = Color.FromArgb(150, System.Drawing.Color.Chartreuse);
                count++;
            }
            else
            {
                a.BackColor = Color.Transparent;
                count--;
            }
            
            //position +=a.Text+",";
        }


        void dLbRoom_Click(object sender, EventArgs e)
        {
            //if (count == 0)
            //{
            //    MessageBox.Show("请选择缺陷位置!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    return;
            //}
            Label a = (Label)sender;

            string aa = a.Text;
            if (a.BackColor == Color.Transparent)
            {
                a.BackColor = Color.FromArgb(150, Color.Chartreuse);
                reason += a.Text+";";
            }
            else
            {
                reason = reason.Replace(a.Text+";","");
                a.BackColor = Color.Transparent;
            }
        }

        /// <summary>
        /// 保存缺陷
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            string stockNo = "",batchNo="",partNo="";

            foreach (Control c in pictureBox2.Controls)
            {
                Label lab = c as Label;
                if (lab.BackColor != Color.Transparent)
                {
                    position += lab.Text + ";";
                }
            }

            if (position == "")
            {
                MessageBox.Show("请选择缺陷位置!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (reason == "")
            {
                MessageBox.Show("请选择缺陷原因!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                
                return;
            }
            

            BadInjectionBLL badBLL = new BadInjectionBLL();
            BadInjectionModel badmd = new BadInjectionModel();
            ProductOfInjectionModel md = new ProductOfInjectionModel();
            ProductOfInjectionBLL bll=new ProductOfInjectionBLL();

            #region 判断是否已做过报废

            DataTable baddt = badBLL.SearchByCode(textBox3.Text.Trim());
            if (baddt != null && baddt.Rows.Count > 0)
            {
                MessageBox.Show("请产品已做过报废处理!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                reason = "";
                textBox3.Text = "";
                textBox3.TabIndex = 0;
                textBox3.Focus();

                textBox4.Text = "";
                pictureBox2.Image = null;

                pictureBox2.Controls.Clear();

                panel2.Controls.Clear();
                return;
            }

            #endregion

            #region 保存报废详细信息

            badmd.ID = Guid.NewGuid().ToString();
            if (textBox3.Text.Trim().Contains("."))
            {
                badmd.BarCode = textBox3.Text.Trim();
                badmd.OneBarCode = "";
            }
            else
            {
                badmd.OneBarCode = textBox3.Text.Trim();
                badmd.BarCode = "";
            }
            badmd.BadPosition = position;
            badmd.BadReason = reason.Trim();
            badBLL.Add_Info(badmd);

            #endregion

            #region 修改注塑产量表,如果是开机报废则把产量减1,报废数不变

            //DataTable dt = badBLL.SearchByCode(textBox3.Text.Trim());
            //if (dt != null && dt.Rows.Count != 1)
            //{

            //}
            //else
            //{
            //    Program.GetCode(textBox3.Text.Trim(), out stockNo, out batchNo, out partNo);

            //    md.BadCount = 1;
            //    md.ClassName = Program.Shift;

            //    StationBLL sbll = new StationBLL();
            //    DataTable sdt = sbll.SearchInfoByNo(Program.station);
            //    if (sdt != null && sdt.Rows.Count > 0)
            //    {
            //        md.StationID = sdt.Rows[0]["StationID"].ToString();
            //    }
            //    else
            //    {
            //        md.StationID = "";
            //    }

            //    sdt.Dispose();

            //    md.ProductDate = Program.ProductDate;
            //    md.PartNo = partNo;
            //    md.StockNo = stockNo;

            //    if (reason.Contains("开机报废"))
            //    {
            //        md.ProductCount = 1;
            //        bll.updateProductCount(md);
            //    }
            //    else
            //    {
            //        bll.UpdateBad_Info(md);
            //    }

            //}

            #endregion

            reason = "";
            textBox3.Text = "";
            textBox3.TabIndex = 0;
            textBox3.Focus();

            textBox4.Text = "";
            pictureBox2.Image = null;

            pictureBox2.Controls.Clear();

            panel2.Controls.Clear();
            position = "";
            reason = "";
            //this.Close();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Form fr = new FrmBarCode();
            this.Hide();
            fr.Show();
        }

        private void textBox3_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                string[] barcode=new string[3];
                int row = 0, col = 0;
                string picture = "";
                string LineID = "";
                ProductBLL bll = new ProductBLL();

                string aa = textBox3.Text.Trim();
                if (textBox3.Text.Length == 20)
                {
                    DataTable dt = bll.SearchInfoByStock(textBox3.Text.Substring(0,10));

                    if (dt != null && dt.Rows.Count > 0)
                    {
                        textBox4.Text = dt.Rows[0]["ProductName"].ToString();
                        row = Convert.ToInt32(dt.Rows[0]["Rows"].ToString());
                        col = Convert.ToInt32(dt.Rows[0]["Cols"].ToString());
                        picture = dt.Rows[0]["PicturePath"].ToString();
                        dt.Dispose();
                    }
                }
                else
                {
                    barcode = textBox3.Text.Trim().Split('.');
                    DataTable dt = bll.SearchInfoByPartNo(barcode[0]);

                    if (dt != null && dt.Rows.Count > 0)
                    {
                        textBox4.Text = dt.Rows[0]["ProductName"].ToString();
                        row = Convert.ToInt32(dt.Rows[0]["Rows"].ToString());
                        col = Convert.ToInt32(dt.Rows[0]["Cols"].ToString());
                        picture = dt.Rows[0]["PicturePath"].ToString();
                        dt.Dispose();
                    }
                }
                
                
                try
                {
                    #region Load PictureBox

                    if (!string.IsNullOrEmpty(picture))
                    {
                        if (!File.Exists(System.IO.Directory.GetCurrentDirectory() + @"\" + picture))
                        {
                            string strImageURL = "http://10.60.101.10:8001/PDF/" + picture;

                            System.Net.WebClient webClient = new System.Net.WebClient();
                            webClient.DownloadFile(strImageURL, Directory.GetCurrentDirectory() + @"\" + picture);
                        }

                        FileStream fs = new FileStream(Directory.GetCurrentDirectory() + "\\" + picture, FileMode.Open,
                            FileAccess.Read); //获取图片文件流
                        Image img = Image.FromStream(fs); // 文件流转换成Image格式
                        pictureBox2.Image = img; //给 图片框设置要显示的图片
                        fs.Close(); // 关闭流,释放图片资源
                    }
                    //if (!File.Exists(System.IO.Directory.GetCurrentDirectory() + @"\" + picture))
                    //{
                    //    Ping p1 = new Ping();
                    //    bool status = false;

                    //    PingReply reply = p1.Send(Program.RemoteIP); //发送主机名或Ip地址
                    //    StringBuilder sbuilder;
                    //    if (reply.Status == IPStatus.Success)
                    //    {
                    //        string PictureFolder = ConfigurationManager.AppSettings["PictureFolder"].ToString();
                    //        string User = ConfigurationManager.AppSettings["PictureUser"].ToString();
                    //        string UserPwd = ConfigurationManager.AppSettings["PicturePsw"].ToString();
                    //        status = Upload.DoConnComputer(Program.RemoteIP, PictureFolder, User, UserPwd);
                    //        if (status == true)
                    //        {
                    //            //共享文件夹的目录
                    //            string path = ConfigurationManager.AppSettings["PicturePath"].ToString() + picture;
                    //            DirectoryInfo theFolder = new DirectoryInfo(path);
                    //            string filename = theFolder.ToString();

                    //            //执行方法
                    //            TransportRemoteToLocal(filename, System.Environment.CurrentDirectory + "\\", picture);    //实现将远程服务器文件写入到本地

                    //        }
                    //        //string PictureFolder = ConfigurationManager.AppSettings["PictureFolder"].ToString();
                    //        //string User = ConfigurationManager.AppSettings["User"].ToString();
                    //        //string UserPwd = ConfigurationManager.AppSettings["UserPwd"].ToString();
                    //        //status = Upload.DoConnComputer(Program.IP, "aa", "Administrator", "Wff775168+");
                    //        //if (status == true)
                    //        //{
                    //        //    //共享文件夹的目录
                    //        //    DirectoryInfo theFolder = new DirectoryInfo(@"\\" + Program.IP + "\\aa\\");
                    //        //    string filename = theFolder.ToString();
                    //        //    //执行方法
                    //        //    TransportRemoteToLocal(@"D:\" + picture, filename, picture); //实现将远程服务器文件写入到本地
                    //        //}
                    //    }
                    //}

                    //FileStream fs = new FileStream(System.Environment.CurrentDirectory + "\\" + picture, FileMode.Open,
                    //    FileAccess.Read); //获取图片文件流
                    //Image img = Image.FromStream(fs); // 文件流转换成Image格式
                    //pictureBox2.Image = img; //给 图片框设置要显示的图片
                    //fs.Close(); // 关闭流,释放图片资源


                    #endregion

                    #region 缺陷图划分区域

                    Label[] lb = new Label[5];
                    string[] str =
                    {
                        "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
                        "U", "V", "W", "X", "Y", "Z"
                    };

                    for (int i = 0; i < col; i++)
                    {
                        for (int j = 0; j < row; j++)
                        {
                            lb[i] = new Label();
                            lb[i].Text = str[i + col * j].ToString();
                            lb[i].Font = new Font(lb[i].Font.FontFamily, 32, FontStyle.Bold);

                            lb[i].Size = new Size(pictureBox2.Width / col, pictureBox2.Height / row);
                            lb[i].Location = new Point(0 + i * lb[i].Size.Width, 0 + j * lb[i].Size.Height);
                            lb[i].BorderStyle = BorderStyle.FixedSingle;
                            lb[i].BackColor = Color.Transparent;
                            lb[i].TextAlign = ContentAlignment.MiddleCenter;
                            pictureBox2.Controls.Add(lb[i]);

                            lb[i].Click += new EventHandler(lblRoom_Click);
                        }
                    }

                    #endregion

                    #region 缺陷原因

                    StationBLL sbll = new StationBLL();
                    DataTable sdt = sbll.SearchInfoByNo(Program.station);
                    if (sdt != null && sdt.Rows.Count > 0)
                    {
                        LineID = sdt.Rows[0]["LineID"].ToString();
                    }

                    sdt.Dispose();

                    int drow = 0, dcol = 6;

                    DefectBLL dbll = new DefectBLL();
                    DataTable dt3 = dbll.SearchInfo(LineID);
                    if (dt3 != null && dt3.Rows.Count > 0)
                    {
                        drow = Convert.ToInt32(Math.Ceiling((double) dt3.Rows.Count / dcol));
                        Label[] dLb = new Label[7];
                        string[] dstr = new string[dt3.Rows.Count];


                        for (int i = 0; i < dt3.Rows.Count; i++)
                        {
                            dstr[i] = dt3.Rows[i]["DefectName"].ToString();
                        }

                        for (int i = 0; i < dcol; i++) //列
                        {
                            for (int j = 0; j < drow; j++) //行
                            {
                                dLb[i] = new Label();
                                if ((i + dcol * j) < dstr.Length)
                                {
                                    dLb[i].Text = dstr[i + dcol * j].ToString();
                                    dLb[i].Font = new Font(dLb[i].Font.FontFamily, 20, FontStyle.Bold);

                                    dLb[i].Size = new Size(130, 50);
                                    dLb[i].Location = new Point(50 + i * (dLb[i].Size.Width + 25),
                                        50 + j * (dLb[i].Size.Height + 20));
                                    dLb[i].BorderStyle = BorderStyle.FixedSingle;
                                    dLb[i].BackColor = Color.Transparent;
                                    dLb[i].TextAlign = ContentAlignment.MiddleCenter;
                                    panel2.Controls.Add(dLb[i]);
                                    dLb[i].Click += new EventHandler(dLbRoom_Click);
                                }
                            }
                        }
                    }

                    #endregion
                }
                catch (Exception ex)
                {
                    LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
                }
            }
        }

        private void label2_Click(object sender, EventArgs e)
        {
            Environment.Exit(0); 
        }
    }
}