using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using System.Drawing;
//using Cognex.VisionPro;
using System.IO;
//using Cognex.VisionPro.ImageFile;
//using Cognex.VisionPro.ToolBlock;
using System.Reflection;


namespace Kanban
{
    public class DataProcessMethod
    {
        

        #region 文字文本保存


        private static List<string> logText = new List<string>();

        public static void WriteLogText(string str)
        {
            logText.Add(str);
        }
        /// <summary>
        /// 将文本数据写入到指定的文件中
        /// </summary>
        /// <param name="filePath">文件路径</param>
        public static void WriteFile(string filePath)
        {
            int leng = logText.Count();
            if (leng > 0)
            {
                StreamWriter sw = new StreamWriter(filePath, true);
                for (int i = 0; i < leng; i++)
                {
                    sw.WriteLine(logText[0]);
                    sw.Flush();
                    logText.RemoveAt(0);
                }
                //关闭流  
                sw.Close();
            }
        }
        /// <summary>
        /// 运行日志的保存数量
        /// </summary>
        /// <param name="logFilePath">运行日志文件夹路径</param>
        /// <param name="number">运行日志保存数量</param>
         public static  void RunningLog(string logFilePath,int number )
        { 
             DirectoryInfo runLog =new  DirectoryInfo(logFilePath);
             FileInfo[] runLogList =runLog .GetFiles ("*.log", SearchOption.AllDirectories  );
             while (runLogList .Count ()>number  )
             {
                 string deleteLog =logFilePath +runLogList [0].ToString ();
                 File .Delete (deleteLog );
                 runLogList =runLog .GetFiles ("*.log", SearchOption.AllDirectories  );
             }
        }


        #endregion


        public enum e_showMethod
        {
            正常,
            警告,
            错误
        }
        delegate void MyDelegate(e_showMethod showMethod, string str);
        public static void showRunLog(e_showMethod showMethod, string str)
        {
            ////RichTextBox obj = frmMain.form1.rtxRunLog;
            //RichTextBox obj = FormMain.instance.richTextBox1; /////将richTextBox1设成public
            //if (obj.InvokeRequired)
            //{
            //    MyDelegate showLog = showRunLog;
            //    obj.Invoke(showLog, showMethod, str);
            //}
            //else
            //{
            //    string showStr;
            //    showStr = "[" + DateTime.Now.ToString() + "]:" + str;
            //    WriteLogText(showStr);
            //    if (showMethod == e_showMethod.正常)
            //    {
            //        obj.SelectionColor = Color.Green;
            //    }
            //    else if (showMethod == e_showMethod.警告)
            //    {
            //        obj.SelectionColor = Color.Blue;
            //    }
            //    else
            //    {
            //        obj.SelectionColor = Color.Red;
            //    }
            //    obj.AppendText(showStr + "\r\n");
            //    obj.ScrollToCaret();
            //}
        }

        #region 源图保存


        //struct SourceImageSave
        //{
        //    //public ICogImage image; //VisionPro
        //    public HalconDotNet.HObject image;
        //    public string time;
        //    public int camIndex;
        //}
        //static SourceImageSave sourceImage;
        //static List<SourceImageSave> saveSourceImage = new List<SourceImageSave>();
        ///// <summary>
        ///// 获取要保存的源图图片
        ///// </summary>
        ///// <param name="isSaveSourceImage">是否保存源图图片</param>
        ///// <param name="image8">源图图片</param>
        ////public static void SaveSourceImage(bool isSaveSourceImage, ICogImage image8) /////VisionPro
        //public static void SaveSourceImage(bool isSaveSourceImage, HalconDotNet.HObject image8, bool bSaveImageAsDay, int index) /////Halcon
        //{
        //    if (isSaveSourceImage == true)
        //    {
        //        sourceImage.image = image8;
        //        if (bSaveImageAsDay)
        //            sourceImage.time = DateTime.Now.ToString("HH_mm_ss ffff");
        //        else
        //            sourceImage.time = DateTime.Now.ToString("yyyy-MM-dd HH_mm_ss ffff");
        //        sourceImage.camIndex = index;
        //        saveSourceImage.Add(sourceImage);
        //    }
        //}
        ///// <summary>
        ///// 将源图图片保存到文件夹中
        ///// </summary>
        ///// <param name="isSaveSourceImage">是否保存源图图片到文件夹中</param>
        ///// <param name="saveAmount">保存的数量</param>
        ///// <param name="sourceImageFilePath">源图图片保存文件夹路径</param>
        ///// <param name="bSaveImageAsDay">是否按天为文件夹来保存图片</param>
        //public static void SaveAndDeleteSourceImage(bool isSaveSourceImage, int saveAmount, string sourceImageFilePath, bool bSaveImageAsDay, out string strErMsg)
        //{
        //    strErMsg = "";

        //    if (isSaveSourceImage == true)
        //    {
        //        if (saveSourceImage.Count > 0)
        //        {

        //            //添加子目录
        //            string strSubDir = sourceImageFilePath + @"OK\";
        //            if (!Directory.Exists(strSubDir))
        //                Directory.CreateDirectory(strSubDir);
        //            strSubDir = sourceImageFilePath + @"NG\";
        //            if (!Directory.Exists(strSubDir))
        //                Directory.CreateDirectory(strSubDir);
        //            strSubDir = sourceImageFilePath + @"无产品\";
        //            if (!Directory.Exists(strSubDir))
        //                Directory.CreateDirectory(strSubDir);
                    

        //            /////VisionPro
        //            //CogImageFileTool myimage_tool = new CogImageFileTool();
        //            //string saveFileName;
        //            //for (int i = 0; i < saveSourceImage.Count(); i++)
        //            //{
        //            //    saveFileName = sourceImageFilePath + saveSourceImage[0].time + ".bmp";
        //            //    myimage_tool.InputImage = saveSourceImage[0].image;
        //            //    myimage_tool.Operator.Open(saveFileName, CogImageFileModeConstants.Write);
        //            //    myimage_tool.Run();
        //            //    saveSourceImage.RemoveAt(0);
        //            //}

        //            /////Halcon
        //            string saveFileName;
        //            for (int i = 0; i < saveSourceImage.Count(); i++)
        //            {
        //                saveFileName = sourceImageFilePath + saveSourceImage[0].time + ".bmp";
        //                saveFileName = sourceImageFilePath + @"OK\" + saveSourceImage[0].time + ".bmp";
        //                if (saveSourceImage[0].camIndex == 1)
        //                    saveFileName = sourceImageFilePath + @"NG\" + saveSourceImage[0].time + ".bmp";
        //                if (saveSourceImage[0].camIndex == 2)
        //                    saveFileName = sourceImageFilePath + @"无产品\" + saveSourceImage[0].time + ".bmp";
        //                try
        //                {
        //                    HalconDotNet.HOperatorSet.WriteImage(saveSourceImage[0].image, "bmp", 0, (HalconDotNet.HTuple)saveFileName);
        //                }
        //                catch (HalconDotNet.HalconException ex)
        //                {
        //                    string strEr = ex.Message;
        //                    if (strEr.Contains("HALCON"))
        //                        strEr = strEr.Replace("HALCON", "");

        //                    strErMsg = strEr;
        //                    break;
        //                }
        //                saveSourceImage.RemoveAt(0);
        //            }
        //        }

        //        if (!bSaveImageAsDay)
        //        {
        //            DirectoryInfo sourceImage = new DirectoryInfo(sourceImageFilePath);
        //            FileInfo[] sourceImageList = sourceImage.GetFiles("*.bmp", SearchOption.AllDirectories);
        //            while (sourceImageList.Count() > saveAmount)
        //            {
        //                sourceImageList = sourceImage.GetFiles("*.bmp", SearchOption.AllDirectories);
        //                string deleteSourceImage = sourceImageFilePath + sourceImageList[0].ToString();
        //                File.Delete(deleteSourceImage);
        //            }

        //            if (frmBlueLight.bDiskFull) //如果磁盘满了，删除最新的一个文件夹
        //            {
        //                sourceImageList = sourceImage.GetFiles("*.bmp", SearchOption.AllDirectories);
        //                if (sourceImageList.Count() > 0)
        //                {
        //                    string deleteSourceImage = sourceImageFilePath + sourceImageList[0].ToString();
        //                    File.Delete(deleteSourceImage);
        //                }
        //            }
        //        }
        //        else/////是否按天为文件夹来保存图片
        //        {
        //            /////获取上级路径
        //            //sourceImageFilePath = sourceImageFilePath.Remove(sourceImageFilePath.Length - 11);
        //            DirectoryInfo dInfo = new DirectoryInfo(sourceImageFilePath);
        //            sourceImageFilePath = dInfo.Parent.FullName;
        //            sourceImageFilePath += "\\";

        //            DirectoryInfo sourceImage = new DirectoryInfo(sourceImageFilePath);
        //            //FileInfo[] sourceImageList = sourceImage.GetFiles("*.bmp", SearchOption.AllDirectories);
        //            DirectoryInfo[] sourceImageList = sourceImage.GetDirectories();
        //            while (sourceImageList.Count() > saveAmount)
        //            {
        //                //sourceImageList = sourceImage.GetFiles("*.bmp", SearchOption.AllDirectories);
        //                sourceImageList = sourceImage.GetDirectories();
        //                string deleteSourceImage = sourceImageFilePath + sourceImageList[0].ToString();
        //                //File.Delete(deleteSourceImage);
        //                Directory.Delete(deleteSourceImage, true);
        //            }

        //            if (frmBlueLight.bDiskFull) //如果磁盘满了，删除最新的一个文件夹
        //            {
        //                sourceImageList = sourceImage.GetDirectories();
        //                if (sourceImageList.Count() > 0)
        //                {
        //                    string deleteSourceImage = sourceImageFilePath + sourceImageList[0].ToString();
        //                    //File.Delete(deleteSourceImage);
        //                    Directory.Delete(deleteSourceImage, true);
        //                }
        //            }
        //        }
        //    }
        //}
        #endregion


        #region 处理图保存
        //struct ProcessImageSave
        //{
        //    //public Image image; /////VisionPro
        //    public HalconDotNet.HObject image;
        //    public string time;
        //    public int camIndex;
        //}
        //static ProcessImageSave processImage;
        //static List<ProcessImageSave> saveProcessImage = new List<ProcessImageSave>();
        ///// <summary>
        ///// 获取要保存的处理图图片
        ///// </summary>
        ///// <param name="isSaveProcessImage">是否保存处理图</param>
        ///// <param name="displayName">获取处理图的显示控件的名称</param>
        ////public static void SaveProcessImage(bool isSaveProcessImage, CogRecordDisplay displayName) /////VisionPro
        //public static void SaveProcessImage(bool isSaveProcessImage, HalconDotNet.HTuple displayName, bool bSaveImageAsDay,int index)
        //{
        //    if (isSaveProcessImage == true)
        //    {
        //        /////VisionPro
        //        //processImage.image = displayName.CreateContentBitmap(Cognex.VisionPro.Display.CogDisplayContentBitmapConstants.Display);
        //        //processImage.time = DateTime.Now.ToString("yyyyMMddHHmmss");
        //        //saveProcessImage.Add(processImage);

        //        /////Halcon
        //        HalconDotNet.HOperatorSet.DumpWindowImage(out processImage.image, displayName);
        //        if (bSaveImageAsDay)
        //            processImage.time = DateTime.Now.ToString("HH_mm_ss ffff");
        //        else
        //            processImage.time = DateTime.Now.ToString("yyyy-MM-dd HH_mm_ss ffff");
        //        processImage.camIndex = index;
        //        saveProcessImage.Add(processImage);
        //    }
        //}
        ///// <summary>
        ///// 将处理图图片保存到文件夹中
        ///// </summary>
        ///// <param name="isSaveProcessImage">是否保存处理图</param>
        ///// <param name="saveAmount">保存的数量</param>
        ///// <param name="handleImageFilePath">处理图图片保存的文件夹的路径</param>
        ///// <param name="bSaveImageAsDay">是否按天为文件夹来保存图片</param>
        //public static void SaveAndDeleteProcessImage(bool isSaveProcessImage, int saveAmount, string handleImageFilePath, bool bSaveImageAsDay, out string strErMsg)
        //{
        //    strErMsg = "";

        //    if (isSaveProcessImage == true)
        //    {
        //        if (saveProcessImage.Count > 0)
        //        {

        //            //添加子目录
        //            string strSubDir = handleImageFilePath + @"OK\";
        //            if (!Directory.Exists(strSubDir))
        //                Directory.CreateDirectory(strSubDir);
        //            strSubDir = handleImageFilePath + @"NG\";
        //            if (!Directory.Exists(strSubDir))
        //                Directory.CreateDirectory(strSubDir);
        //            strSubDir = handleImageFilePath + @"无产品\";
        //            if (!Directory.Exists(strSubDir))
        //                Directory.CreateDirectory(strSubDir);
                    
        //            string dumpFileName;
        //            for (int i = 0; i < saveProcessImage.Count; i++)
        //            {
        //                /////VisionPro
        //                //dumpFileName = handleImageFilePath + saveProcessImage[0].time + ".bmp";
        //                //saveProcessImage[0].image.Save(dumpFileName);
        //                //saveProcessImage.RemoveAt(0);

        //                /////Halcon
        //                dumpFileName = handleImageFilePath + saveProcessImage[0].time + ".bmp";
        //                dumpFileName = handleImageFilePath + @"OK\" + saveProcessImage[0].time + ".bmp";
        //                if (saveProcessImage[0].camIndex == 1)
        //                    dumpFileName = handleImageFilePath + @"NG\" + saveProcessImage[0].time + ".bmp";
        //                if (saveProcessImage[0].camIndex == 2)
        //                    dumpFileName = handleImageFilePath + @"无产品\" + saveProcessImage[0].time + ".bmp";
        //                try
        //                {
        //                    HalconDotNet.HOperatorSet.WriteImage(saveProcessImage[0].image, "bmp", 0, (HalconDotNet.HTuple)dumpFileName);
        //                }
        //                catch (HalconDotNet.HalconException ex)
        //                {
        //                    string strEr = ex.Message;
        //                    if (strEr.Contains("HALCON"))
        //                        strEr = strEr.Replace("HALCON", "");

        //                    strErMsg = strEr;
        //                    break;
        //                }
        //                saveProcessImage.RemoveAt(0);
        //            }
        //        }

        //        if (!bSaveImageAsDay)
        //        {
        //            DirectoryInfo processingImage = new DirectoryInfo(handleImageFilePath);
        //            FileInfo[] processingImageList = processingImage.GetFiles("*.bmp", SearchOption.AllDirectories);
        //            while (processingImageList.Count() > saveAmount)
        //            {
        //                processingImageList = processingImage.GetFiles("*.bmp", SearchOption.AllDirectories);
        //                string deleteProcessingImage = handleImageFilePath + processingImageList[0].ToString();
        //                File.Delete(deleteProcessingImage);
        //            }

        //            if (frmBlueLight.bDiskFull) //如果磁盘满了，删除最新的一个文件夹
        //            {
        //                processingImageList = processingImage.GetFiles("*.bmp", SearchOption.AllDirectories);
        //                if (processingImageList.Count() > 0)
        //                {
        //                    string deleteProcessingImage = handleImageFilePath + processingImageList[0].ToString();
        //                    File.Delete(deleteProcessingImage);
        //                }
        //            }
        //        }
        //        else/////是否按天为文件夹来保存图片
        //        {
        //            /////获取上级路径
        //            //handleImageFilePath = handleImageFilePath.Remove(handleImageFilePath.Length - 11);
        //            DirectoryInfo dInfo = new DirectoryInfo(handleImageFilePath);
        //            handleImageFilePath = dInfo.Parent.FullName;
        //            handleImageFilePath += "\\";

        //            DirectoryInfo processingImage = new DirectoryInfo(handleImageFilePath);
        //            //FileInfo[] processingImageList = processingImage.GetFiles("*.bmp", SearchOption.AllDirectories);
        //            DirectoryInfo[] processingImageList = processingImage.GetDirectories();
        //            while (processingImageList.Count() > saveAmount)
        //            {
        //                //processingImageList = processingImage.GetFiles("*.bmp", SearchOption.AllDirectories);
        //                processingImageList = processingImage.GetDirectories();
        //                string deleteProcessingImage = handleImageFilePath + processingImageList[0].ToString();
        //                //File.Delete(deleteProcessingImage);
        //                Directory.Delete(deleteProcessingImage, true);
        //            }

        //            if (frmBlueLight.bDiskFull) //如果磁盘满了，删除最新的一个文件夹
        //            {
        //                processingImageList = processingImage.GetDirectories();
        //                if (processingImageList.Count() > 0)
        //                {
        //                    string deleteProcessingImage = handleImageFilePath + processingImageList[0].ToString();
        //                    //File.Delete(deleteProcessingImage);
        //                    Directory.Delete(deleteProcessingImage, true);
        //                }
        //            }
        //        }
        //    }
        //}
        #endregion





        //public static void run(CogAcqFifoTool camera, CogToolBlock block, CogRecordDisplay recordDisplay,string dispose,
        //    bool isSaveSourceImage, bool isSaveProcessImage)
        //{
        //    bool isPhoto = false;
        //    int m = 0;
        //    do
        //    {              
        //        Cognex.VisionPro.ICogImage image8;
        //        try
        //        {
        //            int a = 1;
        //            image8 = camera.Operator.Acquire(out a);
        //        }
        //        catch (Exception ex)
        //        {
        //            DataProcessMethod.showRunLog(DataProcessMethod.e_showMethod.错误, ex.ToString());
        //            return;
        //        }
        //        block.Inputs[0].Value = image8;
        //        block.Run();
        //        recordDisplay.StaticGraphics.Clear();
        //        recordDisplay.InteractiveGraphics.Clear();
        //        recordDisplay.Image = image8;
        //        recordDisplay.Record = block.CreateLastRunRecord();
        //        recordDisplay.BackColor = Color.Gray;
        //        recordDisplay.Fit();
        //        SaveSourceImage(isSaveSourceImage   , image8);
        //        SaveProcessImage(isSaveProcessImage  , recordDisplay);
        //        int i = block.Outputs.Count;
        //        object[] result = new object[i];
        //        if (i > 0)
        //        {
        //            for (int x = 0; x < i; x++)
        //            {
        //                result[x] = block.Outputs[x].Value;
        //            }
        //            if (dispose != null)
        //            {
        //                Type t = typeof(DataDispose);//参数为所要使用的函数所在的类的类名。
        //                //MethodInfo mt = t.GetMethod("Dispose");
        //                MethodInfo mt = t.GetMethod(dispose);
        //                if (mt == null)
        //                {
        //                    Console.WriteLine("该方法不存在！");
        //                }
        //                else
        //                {
        //                    object[] para = new object[] { result };
        //                    feedbackData str = (feedbackData)mt.Invoke(null, para);


        //                    Write_text(str.color, str.text, 500, 400, 120, recordDisplay);
        //                    isPhoto = str.isPhoto;
        //                    if (isPhoto == true)
        //                    {
        //                        m = m + 1;
        //                        if (m == 3)
        //                        {
        //                            isPhoto = false;
        //                            //发送数据处理结果（false）

        //                        }
        //                    }
        //                    else
        //                    {
        //                        //发送数据处理结果(true)
        //                    }


        //                }
        //            }
                    
                  

        //        }
        //        else
        //        {
        //            string[] arr = new string[] { "NG，Block无数据输出" };
        //            Write_text("R", arr, 500, 400, 120, recordDisplay);
        //        }
        //    } while (isPhoto);
        //}

        //public static void run(CogAcqFifoTool camera, CogToolBlock block, CogRecordDisplay recordDisplay, string dispose,
        //  bool isSaveSourceImage, bool isSaveProcessImage,string sendSignal)
        //{
        //    Method.ReceivedTriggerSignal(sendSignal);
        //    bool isPhoto = false;
        //    int m = 0;
        //    do
        //    {
        //        Cognex.VisionPro.ICogImage image8;
        //        try
        //        {
        //            int a = 1;
        //            image8 = camera.Operator.Acquire(out a);
        //        }
        //        catch (Exception ex)
        //        {
        //            DataProcessMethod.showRunLog(DataProcessMethod.e_showMethod.错误, ex.ToString());
        //            return;
        //        }
        //        block.Inputs[0].Value = image8;
        //        block.Run();
        //        recordDisplay.StaticGraphics.Clear();
        //        recordDisplay.InteractiveGraphics.Clear();
        //        recordDisplay.Image = image8;
        //        recordDisplay.Record = block.CreateLastRunRecord();
        //        recordDisplay.BackColor = Color.Gray;
        //        recordDisplay.Fit();
        //        SaveSourceImage(isSaveSourceImage, image8);
        //        SaveProcessImage(isSaveProcessImage, recordDisplay);
        //        int i = block.Outputs.Count;
        //        object[] result = new object[i];
        //        if (i > 0)
        //        {
        //            for (int x = 0; x < i; x++)
        //            {
        //                result[x] = block.Outputs[x].Value;
        //            }
        //            if (dispose != null)
        //            {
        //                Type t = typeof(DataDispose);//参数为所要使用的函数所在的类的类名。
        //                //MethodInfo mt = t.GetMethod("Dispose");
        //                MethodInfo mt = t.GetMethod(dispose);
        //                if (mt == null)
        //                {
        //                    Console.WriteLine("该方法不存在！");
        //                }
        //                else
        //                {
        //                    object[] para = new object[] { result };
        //                    feedbackData str = (feedbackData)mt.Invoke(null, para);


        //                    Write_text(str.color, str.text, 500, 400, 120, recordDisplay);
        //                    isPhoto = str.isPhoto;
        //                    if (isPhoto == true)
        //                    {
        //                        m = m + 1;
        //                        if (m == 3)
        //                        {
        //                            isPhoto = false;
        //                            //发送数据处理结果（false）
        //                            Method.ProcessResult(str.dataProcessingResults);
        //                        }
        //                    }
        //                    else
        //                    {
        //                        Method.ProcessResult(str.dataProcessingResults);
        //                        //发送数据处理结果(true)
        //                    }

        //                }
        //            }
                   

        //        }
        //        else
        //        {
        //            string[] arr = new string[] { "NG，Block无数据输出" };
        //            Write_text("R", arr, 500, 400, 120, recordDisplay);
        //        }
        //    } while (isPhoto);
        //}


       public  struct feedbackData
        {
            /// <summary>
            /// 是否再次拍照
            /// </summary>
           public bool isPhoto;
           /// <summary>
           /// 要在显示控件上显示的文字
           /// </summary>
            public string[] text;
           /// <summary>
           /// 显示文字的颜色
           /// </summary>
            public string color;
           /// <summary>
           /// 数据处理结果
           /// </summary>
            public string dataProcessingResults;
        }
       

      
        #region 在图片上显示文字 VisionPro
        /// <summary>
        /// 在图片上显示文字
        /// </summary>
        /// <param name="Color">欲显示文字的颜色</param>
        /// <param name="text">欲显示的内容</param>
        /// <param name="start_x">显示开始x</param>
        /// <param name="start_y">显示开始y</param>
        /// <param name="nterval_size">间隔大小</param>
        /// <param name="cogdisplay">显示平台</param>
       //private  static void Write_text(string Color, string[] text, double start_x, double start_y, double nterval_size, CogRecordDisplay cogdisplay)
       // {
       //     //int dimension;
       //     // cogRecordDisplay1.StaticGraphics.Clear();
       //     //cogRecordDisplay1.InteractiveGraphics.Clear();
       //     int t_size = text.GetLength(0);
       //     for (int i = 0; i < t_size; i++)
       //     {
       //         Create_lab(Color, start_x, start_y + i * nterval_size, text[i], 14, 0, cogdisplay);
       //     }
       // }
        //private static CogGraphicLabel CreateResult = new CogGraphicLabel();
       //private  static void Create_lab(string Color, double X, double Y, string Text, int FontSize, double rot, CogRecordDisplay cogdisplay)
       // {
       //     Font My_font = new Font("新宋体", FontSize, System.Drawing.FontStyle.Bold);
       //     int int_L = (Text.Length / 2) * FontSize * 2;
       //     CreateResult.Font = My_font;
       //     CreateResult.X = X + int_L;
       //     CreateResult.Y = Y;
       //     CreateResult.Text = Text;
       //     switch (Color)
       //     {
       //         case "R":
       //             CreateResult.Color = CogColorConstants.Red;
       //             break;
       //         case "G":
       //             CreateResult.Color = CogColorConstants.Green;
       //             break;
       //     }
       //     CreateResult.Rotation = rot;
       //     cogdisplay.StaticGraphics.Add(CreateResult, "");
       // }
       // //string[]  arr = new string[] { "NG，有脏污或没产品" };
       // //  Write_text("R", arr, 500, 400, 120, cogRecordDisplay1);
        #endregion
    }
}
