using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.IO;
using Microsoft.Win32;
using System.Configuration;
using WinForm = System.Windows.Forms;
using System.Windows.Media.Animation;
using System.Threading;
using System.Data;
using System.Data.SQLite;
using AIRS.usercontrol;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace AIRS
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        

        #region 系统变量
        //程序工作目录
        private string path = Directory.GetCurrentDirectory();
        private AutoResetEvent autoResetEvent = new AutoResetEvent(false);
        //数据库
        SQLiteConnection conn = new SQLiteConnection();
        SQLiteConnectionStringBuilder connstr = new SQLiteConnectionStringBuilder();

        //SQLiteDataAdapter da = new SQLiteDataAdapter();

        public string lname = "";
        public string password = "";//密码
        //public string entryclerk = "";//录入员

        private List<Label> list_lblsteel = new List<Label>();
        private List<Label> list_lblstandard = new List<Label>();
        private List<Label> list_lbltestitems = new List<Label>();

        //private List<String> filenames = new List<String>();
        private Dictionary<String, List<String>> page_filenames = new Dictionary<string, List<string>>();
        private Dictionary<String, List<String>> image_name = new Dictionary<string, List<string>>();
        //临时存放图片文件名
        private List<String> fns = new List<String>();
        //临时存放图片文件名
        private List<String> fns_name = new List<String>();
        private Dictionary<String, List<Picturebox>> dic_pic = new Dictionary<String, List<Picturebox>>();
        private Dictionary<String, double> pich = new Dictionary<String, double>();
        private Dictionary<String, double> picw = new Dictionary<String, double>();
        private Dictionary<String, double> zoom = new Dictionary<String, double>();
        private int canvas_height = 0;

        private Boolean mousedown = false;

        //cantab标签字典
        private Dictionary<String, PageControl> listpage = new Dictionary<String, PageControl>();
        private Dictionary<String, HomePageEntry> listhompage = new Dictionary<string, HomePageEntry>();
        private List<String> listpagename = new List<String>();
        private String selectpage = "首页";

        //蒙板
        Grid layer = new Grid() { Background = new SolidColorBrush(Color.FromArgb(128, 255, 255, 255)) };

        //检测
        private static int test_index = 0;

        //全屏返回
        private int full_return_index = 0;

        //钢种

        private string YGXZDZ = "亚共析钢带状";
        private int DZ_direction = 0;//带状方向默认纵向为0
        DetectParams detectParams = null;//带状横向或纵向null为纵向
        List<string> deletelabel = new List<string>();//所有菜单中选项卡

        //选项卡宽度，本机为选项卡宽为142，任务标签共计157，窗体1350,142*8=1136,1350-1136=214,214-157=57，
        //选项卡宽为(1350-157-57)/142
        private int tab_num = 0;//tab_num = 8;
       
        DateTime time_start_grade = Convert.ToDateTime(DateTime.Now);

        //评级状态
        Boolean grade_state = false;

        //标尺长度
        double rulerl = 0;
        String ret_shape = "";
        double ret_dia = 0;
        int ret_mul = 0;

        //正在评级的selectpage
        String grade_selectpage = "";

        private SynchronizationContext synchronizationContext = null;

        //评级统计
        GradeCount gc = null;

        //是否强制关闭检测
        bool isforced = false;

        #endregion

        #region 构造函数
        /// <summary>
        /// 构造函数，加载界面和添加事件
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();

            //窗体变化事件和最大化
            this.SizeChanged += new System.Windows.SizeChangedEventHandler(MainWindow_Resize);
            this.WindowState = WindowState.Maximized;

            //为自定义控件增加事件
            this.pagetitle.imgmin1.PreviewMouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(window_min_PreviewMouseLeftButtonDown);
            this.pagetitle.imgmax1.PreviewMouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(window_max_PreviewMouseLeftButtonDown);
            this.pagetitle.imgclosed1.PreviewMouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(window_close_PreviewMouseLeftButtonDown);
            this.pagetitle.start_grade.PreviewMouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(start_grade);
            this.pagetitle.cangradesum.PreviewMouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(GradeSum);
            this.subtitle.sldzoom.ValueChanged += new System.Windows.RoutedPropertyChangedEventHandler<double>(zoomchange);
            this.pagetitle.canfill.PreviewMouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(canfill);
            this.pagefirst.txtinput.PreviewMouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(openfiles);
            this.pbw.btncancle.PreviewMouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(progressbar_cancle);
            this.pbw.canvas_min.PreviewMouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(progressbar_canvas_min); 
            this.minpbw.canvas_changeMax.PreviewMouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(minprogressbar_canvas_max);
            this.pagetitle.task.PreviewMouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(lblhomepage_PreviewMouseLeftButtonDown);
            this.completetest.BtnOK.PreviewMouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(completetest_PreviewMouseLeftButtonDown);
            //this.pagetitle.field.PreviewMouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(draw_viewport);
            //this.pagetitle.lblmdfpwd.PreviewMouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(lblmdfpwd_uppassword);
            //this.pagetitle.lblchange.PreviewMouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(lblchange_cut);
            this.pagetitle.history.PreviewMouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(history_down);//历史评级单击事件
            //this.pagetitle.out_export.PreviewMouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(out_report);//生成报告
            this.forcedcancelusercontrol.fBtnOK.PreviewMouseLeftButtonDown+= new System.Windows.Input.MouseButtonEventHandler(forcedOK);//取人强制关闭当前检测
            this.forcedcancelusercontrol.fBtnExit.PreviewMouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(forcedCancel);//取人强制关闭当前检测
            cmd.Click += (obj, args) => { menu.IsOpen = true; };

            //蒙板
            this.root.Children.Add(layer);

            //子控件调用父控件的函数（子控件控制父控件的属性等）
            LoginWindow.TestEvent += func;
            Sample_Information_Enter.MBEvent += func;
            Page_FirstControl.ShowpageEvent += screen_label;
            GradeCount.SelectGradeEvent += GradeGradeEvent;

            //线程间同步上下文
            this.synchronizationContext = SynchronizationContext.Current;
          
        }
        #endregion

        #region 评级统计及事件
        private void GradeSum(object sender,MouseButtonEventArgs e)
        {
            Dictionary<String, int> gradesum = new Dictionary<String, int>();
            Dictionary<String, String> aiRES = new Dictionary<String, String>();
            for (int i=0;i<page_filenames[selectpage].Count;i++)
            {
                String filename_ai = System.IO.Path.GetDirectoryName(page_filenames[selectpage][i]) + "\\AI\\" +
                    System.IO.Path.GetFileNameWithoutExtension(page_filenames[selectpage][i]) + ".ai";
                if(File.Exists(filename_ai))
                {
                    
                    using (System.IO.StreamReader _file = System.IO.File.OpenText(filename_ai))
                    {
                        using (JsonTextReader reader = new JsonTextReader(_file))
                        {
                            JObject o = (JObject)JToken.ReadFrom(reader);
                            JObject content = JObject.Parse(o["content"].ToString());
                            JObject details = JObject.Parse(content["details"].ToString());
                            if (details.Property("value") != null)
                            {
                                //zm:
                                aiRES.Add(System.IO.Path.GetFileName(page_filenames[selectpage][i]), content["title"].ToString());
                                string key = details["value"].ToString();

                                if (gradesum.ContainsKey(key))
                                {
                                    gradesum[key]++;
                                }
                                else
                                {
                                    gradesum.Add(key, 1);
                                }
                            }
                            else
                            {
                                reader.Close();
                                _file.Close();
                                _file.Dispose();
                                break;
                            }
                            reader.Close();
                            _file.Close();
                            _file.Dispose();
                        }
                    }

                }
            }

            if(gradesum.Count>0)
            {
                gc = new GradeCount();
                gc.aiRES = aiRES;
                gc.gradesum = gradesum;
                gc.gradetitle = image_name[selectpage][3];
                gc.gradename = image_name[selectpage][0] + " - " + image_name[selectpage][2];
                gc.Owner = this;
                gc.ShowInTaskbar = false;
                gc.Show();
            }
            else
            {
                MessageBox.Show("该文件夹下图片还没有进行评级或没有对应参数，请评级后再进行评级检测！");
            }
        }

        private void GradeGradeEvent(List<string> listgrade, Boolean state)
        {
            if(state)
            {
                if(gc!=null)
                {
                    gc.Close();
                    gc = null;
                }
            }
            int canvas_height = 0;
            //判断一行能存放几个pic
            int displaynum = Convert.ToInt32(Math.Floor(this.showpic.Width / (picw[selectpage] * (1 + zoom[selectpage]) + 20)));
            if (displaynum == 0)
            {
                displaynum = 1;
            }
            int ii = 0;
            for (int i = 0; i < dic_pic[selectpage].Count; i++)
            {
                if(listgrade.Contains(dic_pic[selectpage][i].grade_value) && state==false)
                {
                    dic_pic[selectpage][i].Visibility = Visibility.Hidden;
                    ii++;
                    continue;
                }
                dic_pic[selectpage][i].Visibility = Visibility.Visible;
                dic_pic[selectpage][i].Width = picw[selectpage] * (1 + zoom[selectpage]);
                dic_pic[selectpage][i].Height = pich[selectpage] * (1 + zoom[selectpage]);
                dic_pic[selectpage][i].SetValue(Canvas.TopProperty, 5.0 + ((i-ii) / displaynum) * (dic_pic[selectpage][i].Height + 10.0));
                dic_pic[selectpage][i].SetValue(Canvas.LeftProperty, 20.0 + ((i-ii) % displaynum) * (dic_pic[selectpage][i].Width + 20.0));
                dic_pic[selectpage][i].SetValue(Canvas.RightProperty, double.NaN);
                dic_pic[selectpage][i].SetValue(Canvas.BottomProperty, double.NaN);
                canvas_height = Convert.ToInt32(10 + ((i-ii) / displaynum) * (dic_pic[selectpage][i].Height + 10) + dic_pic[selectpage][i].Height);
            }
            (showpic.FindName("can" + selectpage) as Canvas).Height = canvas_height;
            this.showpic.Height = canvas_height;
        }
        #endregion

        #region 视场截取
        private void draw_viewport(object sender, MouseButtonEventArgs e)
        {
            //打开视场截取对话框
            FeildParam fp = new FeildParam();
            fp.Owner = this;
            fp.ShowInTaskbar = false;
            fp.standard = image_name[selectpage][1];
            fp.ShowDialog();
            //取消
            if(fp.DialogResult==false)
            {
                return;
            }
            //确认返回获取参数
            ret_shape = fp.ret_shape;
            ret_dia = fp.ret_dia;
            ret_mul = fp.ret_mul;
            rulerl = 0;
            //创建AI文件夹
            if (!Directory.Exists(image_name[selectpage][6] + "\\AI"))
            {
                Directory.CreateDirectory(image_name[selectpage][6] + "\\AI");
            }

            //开启线程等待返回图片标尺长度的相素长度
            Thread viewfield = new Thread(view_field);
            viewfield.Start();

        }

        private void view_field()
        {
            //调用Python环境命令
            PythonExecutor pythonExecutorRuler = new PythonExecutor(synchronizationContext, @"D:\vi\vi_server\scale_test.py");
            pythonExecutorRuler.ReceivedControlData += this.ReceivedControlRuler;
            
            //画视场
            for (int i = 0; i < dic_pic[selectpage].Count; i++)
            {
                //获取标尺长度
                if (this.rulerl == 0)
                {
                    pythonExecutorRuler.executePy(this.lblhomepage, page_filenames[selectpage][i]);
                    autoResetEvent.WaitOne();
                } 

                this.Dispatcher.Invoke(new Action(() =>
                {
                    double ret_width = (ret_dia * 1000 / ret_mul) * this.rulerl / ret_mul;
                    double radius = (ret_width / 2) / dic_pic[selectpage][i].zoom_key;
                    //这里暂时定为圆
                    if (ret_shape == "Circle")
                    {
                        dic_pic[selectpage][i].cir_rect = "Circle";

                        dic_pic[selectpage][i].circle.RadiusX = radius;
                        dic_pic[selectpage][i].circle.RadiusY = radius;
                        dic_pic[selectpage][i].field.Fill = new SolidColorBrush(Color.FromArgb(0x40, 0xFF, 0x00, 0x00));
                        dic_pic[selectpage][i].fieldr.Fill = new SolidColorBrush(Color.FromArgb(0x40, 0xFF, 0x00, 0x00));
                        dic_pic[selectpage][i].Frozen = false;
                        dic_pic[selectpage][i].circle.Center = new Point(dic_pic[selectpage][i].img.Width / 2, dic_pic[selectpage][i].img.Height / 2);
                        dic_pic[selectpage][i].field.Visibility = Visibility.Visible;
                        dic_pic[selectpage][i].fieldr.Visibility = Visibility.Hidden;
                    }
                    else if (ret_shape == "Rectangle")
                    {
                        dic_pic[selectpage][i].cir_rect = "Rectangle";
                        dic_pic[selectpage][i].rectrr.Rect = new Rect(
                            dic_pic[selectpage][i].img.Width / 2 - radius,
                            dic_pic[selectpage][i].img.Height / 2 - radius,
                            radius * 2, radius * 2);
                        dic_pic[selectpage][i].field.Fill = new SolidColorBrush(Color.FromArgb(0x40, 0xFF, 0x00, 0x00));
                        dic_pic[selectpage][i].fieldr.Fill = new SolidColorBrush(Color.FromArgb(0x40, 0xFF, 0x00, 0x00));
                        dic_pic[selectpage][i].Frozen = false;
                        dic_pic[selectpage][i].field.Visibility = Visibility.Hidden;
                        dic_pic[selectpage][i].fieldr.Visibility = Visibility.Visible;
                    }
                }));
            }
        }
        
        /// <summary>
        /// 回调接收参数，参数固定
        /// </summary>
        /// <param name="o">回调返回结果</param>
        private void ReceivedControlRuler(object o)
        {
            try
            {
                if (o != null)
                {
                    ControlData controlData = o as ControlData;/////
                    if (controlData != null)
                    {
                        //下面示例需要重写，需要定制化，
                        //控件是调用时传入的
                        if (controlData.Control is Label)//是label,在label上显示
                        {
                            Label lbl = controlData.Control as Label;
                            //lbl.Content += controlData.DataString + Environment.NewLine;
                            switch (controlData.CallbackDataType)
                            {
                                //返回数据是执行的脚本指定
                                case CallbackDataType.Command:
                                    //txt.Text += "Command:" + controlData.DataString + Environment.NewLine;
                                    //txt.ScrollToEnd();
                                    break;
                                //返回数据是参数调用接口错误
                                case CallbackDataType.ParameterError:
                                    //txt.Text += controlData.DataString + Environment.NewLine;
                                    //txt.ScrollToEnd();
                                    break;
                                //返回是数据是最终想要的结果
                                case CallbackDataType.ReturnData:
                                    this.rulerl =Convert.ToDouble( controlData.DataString);
                                    autoResetEvent.Set();
                                    break;
                                //其他就是info，是过程中的日志信息、ai调用内部错误信息等
                                default:
                                    //其他的中间过程日志信息先不显示
                                    break;
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Log.Info("出现错误！");
                Log.Info("出错信息为：" + e.Message);
                autoResetEvent.Set();
            }
            finally
            {

            }
        }
        #endregion

        #region 时间返回
        /// <summary>
        /// 截取时间
        /// </summary>
        /// <returns></returns>
        private string splittime(string str)
        {
            string[] strall = str.Split('0');
            if (strall[0] == "")
            {
                return strall[1];
            }
            else
            {
                return str;
            }            
        }

        /// <summary>
        /// 计算耗时
        /// </summary>
        /// <param name="DateTime1"></param>
        /// <param name="DateTime2"></param>
        /// <returns></returns>
        public string TimeDiff(DateTime DateTime1, DateTime DateTime2)
        {
            //string dateDiff = null; //有日期时候用到
            string timeDiff = null;
            try
            {
                TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
                TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
                TimeSpan ts = ts1.Subtract(ts2).Duration();
                // dateDiff = ts.Days.ToString() + "天" + ts.Hours.ToString() + "小时" + ts.Minutes.ToString() + "分钟" + ts.Seconds.ToString() + "秒"; //有日期的时候
                if (ts.Hours.ToString("00") == "00"&& ts.Minutes.ToString("00") == "00")
                {
                    timeDiff = splittime(ts.Seconds.ToString("00"))  + "秒";
                }
                else if (ts.Hours.ToString("00") == "00")
                {
                    timeDiff = splittime(ts.Minutes.ToString("00")) + "分" + splittime(ts.Seconds.ToString("00")) + "秒";
                }
                else
                {
                    timeDiff = splittime(ts.Hours.ToString("00")) + "时" + splittime(ts.Minutes.ToString("00")) + "分" + splittime(ts.Seconds.ToString("00")) + "秒";
                }
               // timeDiff = ts.Hours.ToString("00") + "时" + ts.Minutes.ToString("00") + "分" + ts.Seconds.ToString("00")+"秒";

            }
            catch
            {
            }
            return timeDiff;
        }
        #endregion

        #region 评级时对标题栏按钮的操作
        /// <summary>
        /// 评级时或组织识别时是标头暗亮度度当前 设置变暗为变亮
        /// </summary>
        private void Header_Opacity_ChangeBright()
        {
            this.pagetitle.task.IsEnabled = true;
            this.pagetitle.task.Opacity = 1;
            this.pagetitle.start_grade.IsEnabled = true;
            this.pagetitle.start_grade.Opacity = 1;
            //this.pagetitle.field.IsEnabled = true;
            //this.pagetitle.field.Opacity = 1;
            this.pagetitle.cangradesum.IsEnabled = true;
            this.pagetitle.cangradesum.Opacity = 1;
            this.pagetitle.canfill.IsEnabled = true;
            this.pagetitle.canfill.Opacity = 1;
            //this.pagetitle.out_export.IsEnabled = true;
            //this.pagetitle.out_export.Opacity = 1;
            this.pagetitle.history.IsEnabled = true;
            this.pagetitle.history.Opacity = 1;
        }

        /// <summary>
        /// 评级时或组织识别时是标头暗亮度度当前 设置变暗为变暗
        /// </summary>
        private void Header_Opacity_ChangeDark()
        {
            this.pagetitle.task.IsEnabled = true;
            this.pagetitle.task.Opacity = 1;
            this.pagetitle.start_grade.IsEnabled = false;
            this.pagetitle.start_grade.Opacity = 0.5;
            //this.pagetitle.field.IsEnabled = false;
            //this.pagetitle.field.Opacity = 0.5;
            this.pagetitle.cangradesum.IsEnabled = false;
            this.pagetitle.cangradesum.Opacity = 0.5;
            this.pagetitle.canfill.IsEnabled = true;
            this.pagetitle.canfill.Opacity = 1;
            //this.pagetitle.out_export.IsEnabled = true;
            //this.pagetitle.out_export.Opacity = 1;
            this.pagetitle.history.IsEnabled = true;
            this.pagetitle.history.Opacity = 1;
        }

        /// <summary>
        /// 评级时或组织识别时是所有标题按钮变暗并禁用
        /// </summary>
        private void Header_Opacity_All_ChangeDark()
        {
            this.pagetitle.task.IsEnabled = false;
            this.pagetitle.task.Opacity = 0.5;
            this.pagetitle.start_grade.IsEnabled = false;
            this.pagetitle.start_grade.Opacity = 0.5;
            //this.pagetitle.field.IsEnabled = false;
            //this.pagetitle.field.Opacity = 0.5;
            this.pagetitle.cangradesum.IsEnabled = false;
            this.pagetitle.cangradesum.Opacity = 0.5;
            this.pagetitle.canfill.IsEnabled = false;
            this.pagetitle.canfill.Opacity = 0.5;
            //this.pagetitle.out_export.IsEnabled = false;
            //this.pagetitle.out_export.Opacity = 0.5;
            this.pagetitle.history.IsEnabled = false;
            this.pagetitle.history.Opacity = 0.5;
        }
        #endregion

        #region 进度条取消操作
        /// <summary>
        /// 进度条取消操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void progressbar_cancle(object sender, MouseButtonEventArgs e)
        {
            if (isforced==false)
            {
                MessageBoxResult result = MessageBox.Show("确定要取消当前操作？", "询问", MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (result == MessageBoxResult.Yes)
                {
                    // do something
                    PythonExecutor pythonExecutor = new PythonExecutor(SynchronizationContext.Current);
                    pythonExecutor.stop();
                    ////评级停止，使评级状态置false
                    //grade_state = false;
                    ////允许关闭
                    //pagetitle.isclosed = true;
                    //正在进行AI检测，请稍候...
                    this.pbw.progbar_msg.Content = "正在取消，请稍后...";
                    //禁用进度条取消按钮
                    // this.pbw.btncancle.IsEnabled = false;    
                    isforced = true;
                }
            }
            else
            {
                this.pbw.Visibility = Visibility.Hidden;
                ForcedCancelUC.Visibility = Visibility.Visible;
            }


        }
        #endregion

        #region 确认强制关闭当前检测
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void forcedOK(object sender, MouseButtonEventArgs e)
        {   
            ThreadExitis("python", true);
            //是否强制关闭
            isforced = false;
            //评级停止，使评级状态置false
            grade_state = false;
            //允许关闭
            pagetitle.isclosed = true;
            ForcedCancelUC.Visibility = Visibility.Hidden;
            //正在进行AI检测，请稍候...          
            this.pbw.progbar_msg.Content = "正在进行AI检测，请稍候...";
            Header_Opacity_ChangeBright();
        }
        #endregion

        #region 强行杀死线程
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public bool ThreadExitis(string threadName, bool kill)
        {
            bool bo = false;
            try
            {
                System.Diagnostics.Process[] processList = System.Diagnostics.Process.GetProcesses();
                foreach (System.Diagnostics.Process process in processList)
                {

                    if (process.ProcessName.ToLower() == threadName.ToLower())
                    {
                        if (kill)
                        {
                            bo = false;
                            process.Kill(); //结束进程 
                            //Console.WriteLine("杀死了 " + process.ProcessName);
                        }
                        else
                        {
                            bo = true;
                        }
                    }
                }
            }
            catch(Exception e)
            {
                MessageBox.Show("杀死线程出现问题"+e.Message);
            }  
            return bo;
        }
        #endregion

        #region 取消强制关闭当前检测
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void forcedCancel(object sender, MouseButtonEventArgs e)
        {
            //MessageBox.Show("强制取消");
            this.ForcedCancelUC.Visibility = Visibility.Hidden;
            this.pbw.Visibility = Visibility.Visible;
            //isforced = false;
        }
        #endregion

        #region 进度条最小化
        /// <summary>
        /// 进度条最小化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void progressbar_canvas_min(object sender, MouseButtonEventArgs e)
        {
            this.pbw.Visibility = Visibility.Hidden;
            this.minpbw.Visibility = Visibility.Visible;
        }
        #endregion

        #region 进度条从最小化变成最大化
        /// <summary>
        /// 进度条从最小化变成最大化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void minprogressbar_canvas_max(object sender, MouseButtonEventArgs e)
        {
            this.pbw.Visibility = Visibility.Visible;
            this.minpbw.Visibility = Visibility.Hidden;
        }
        #endregion

        #region 录入下显示对应的所有标签
        /// <summary>
        /// 筛选标签页
        /// </summary>
        /// <param name="testitem"></param>
        private void screen_label(string testitem)
        {
            double count = 0;
            //清除所有标签
            this.pagefirst.showinfo.Children.Clear();
            int index = 0;
            for (int i = 0; i < listhompage.Count; i++)
            {
                //查找包含testitem的标签放入容器中
                if (listpage[listpagename[i]].Tag.ToString() == testitem)
                {
                    listhompage[listpagename[i]].SetValue(Canvas.TopProperty, count);
                    
                    this.pagefirst.showinfo.Children.Add(listhompage[listpagename[i]]);

                    this.pagefirst.showinfo.RegisterName("hp" + listpagename[i], listhompage[listpagename[i]]);
                    this.pagefirst.showinfo.Height = count;
                    index++;

                    //更新录入下显示
                    listhompage[listpagename[i]].homepagecanvas.UpdateLayout();
                    listhompage[listpagename[i]].c_header.UpdateLayout();
                    listhompage[listpagename[i]].c_footer.UpdateLayout();
                    listhompage[listpagename[i]].c_header.Height = listhompage[listpagename[i]].lbltestmechine.ActualHeight + 2;
                    listhompage[listpagename[i]].c_header.SetValue(Canvas.TopProperty, 0.0);
                    listhompage[listpagename[i]].c_header.SetValue(Canvas.LeftProperty, 0.0);
                    listhompage[listpagename[i]].c_header.SetValue(Canvas.RightProperty, double.NaN);
                    listhompage[listpagename[i]].c_header.SetValue(Canvas.BottomProperty, double.NaN);
                    listhompage[listpagename[i]].c_footer.SetValue(Canvas.TopProperty, listhompage[listpagename[i]].lbltestmechine.ActualHeight + 4.0);
                    listhompage[listpagename[i]].c_footer.SetValue(Canvas.LeftProperty, 0.0);
                    listhompage[listpagename[i]].c_footer.SetValue(Canvas.RightProperty, double.NaN);
                    listhompage[listpagename[i]].c_footer.SetValue(Canvas.BottomProperty, double.NaN);
                    listhompage[listpagename[i]].homepagecanvas.Height = listhompage[listpagename[i]].lbltestmechine.ActualHeight + listhompage[listpagename[i]].lblpicpath.ActualHeight + 6;

                    if (selectpage != "首页")
                    {
                        if (image_name[selectpage][0] == "夹杂物")
                        {
                            Label lbl = new Label();
                            lbl.FontSize = 12;
                            lbl.Content = "夹杂物种类：" + image_name[selectpage][11];
                            lbl.Foreground = new SolidColorBrush(Colors.White);
                            lbl.SetValue(Canvas.TopProperty, listhompage[listpagename[i]].homepagecanvas.Height - 2.0);
                            lbl.SetValue(Canvas.LeftProperty, -1.0);
                            lbl.SetValue(Canvas.RightProperty, double.NaN);
                            lbl.SetValue(Canvas.BottomProperty, double.NaN);
                            listhompage[listpagename[i]].homepagecanvas.Height += 20;
                            listhompage[listpagename[i]].homepagecanvas.Children.Add(lbl);
                        }
                    }
                    count = count + listhompage[listpagename[i]].ActualHeight + 5;
                }
            }
        }
        #endregion

        #region 移除蒙板
        /// <summary>
        /// 移除蒙板
        /// </summary>
        public void func()
        {
            this.root.Children.Remove(layer);
        }
        #endregion

        #region 开始检测
        /// <summary>
        /// 开始检测事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void start_grade(object sender, MouseButtonEventArgs e)
        {
            //标题按钮不可用且变暗
            Header_Opacity_ChangeDark();
            //禁用关闭按钮
            pagetitle.isclosed = false;
            //初始化脚本执行器
            PythonExecutor pythonExecutor = new PythonExecutor(SynchronizationContext.Current);
            pythonExecutor.ReceivedControlData += ReceivedControlData;
            //钢钟catagory
            string ZT_H = image_name[selectpage][7];
            //检测项目items
            string G_XZ = image_name[selectpage][8];
            string steel = image_name[selectpage][0];
            string testitems_param = image_name[selectpage][9];//不是魏氏就为空是就是json{'YBG-W': {'w_cls':'wa'}}
            //更改评级状态
            grade_state = true;
            //计时
            time_start_grade = Convert.ToDateTime(DateTime.Now);
            //将picturebox的Frozen置为True，写JSON文件
            if (Directory.Exists(image_name[selectpage][6] + "\\AI"))
            {
                for (int i = 0; i < dic_pic[selectpage].Count; i++)
                {
                    if(dic_pic[selectpage][i].cir_rect=="")
                    {
                        break;
                    }
                    dic_pic[selectpage][i].Frozen = true;
                    //写fld文件
                    String field = System.IO.Path.GetDirectoryName(page_filenames[selectpage][i]) + "\\AI\\";
                    field = field + System.IO.Path.GetFileNameWithoutExtension(page_filenames[selectpage][i]) + ".fld";
                    StringWriter sw = new StringWriter();
                    JsonTextWriter writer = new JsonTextWriter(sw);
                    writer.WriteStartObject();
                    writer.WritePropertyName("viewport");
                    writer.WriteStartObject();
                    writer.WritePropertyName("type");
                    if (dic_pic[selectpage][i].cir_rect == "Circle")
                    {
                        writer.WriteValue("C");
                        writer.WritePropertyName("x");
                        writer.WriteValue((dic_pic[selectpage][i].circle.Center.X - dic_pic[selectpage][i].circle.RadiusX - dic_pic[selectpage][i].rect_left) * dic_pic[selectpage][i].zoom_key);
                        writer.WritePropertyName("y");
                        writer.WriteValue((dic_pic[selectpage][i].circle.Center.Y - dic_pic[selectpage][i].circle.RadiusY - dic_pic[selectpage][i].rect_top) * dic_pic[selectpage][i].zoom_key);
                        writer.WritePropertyName("w");
                        writer.WriteValue((dic_pic[selectpage][i].circle.RadiusX * 2) * dic_pic[selectpage][i].zoom_key);
                        writer.WritePropertyName("h");
                        writer.WriteValue((dic_pic[selectpage][i].circle.RadiusY * 2) * dic_pic[selectpage][i].zoom_key);
                    }
                    else if (dic_pic[selectpage][i].cir_rect == "Rectangle")
                    {
                        writer.WriteValue("R");
                        writer.WritePropertyName("x");
                        writer.WriteValue((dic_pic[selectpage][i].rectrr.Rect.Left - dic_pic[selectpage][i].rect_left) * dic_pic[selectpage][i].zoom_key);
                        writer.WritePropertyName("y");
                        writer.WriteValue((dic_pic[selectpage][i].rectrr.Rect.Top - dic_pic[selectpage][i].rect_top) * dic_pic[selectpage][i].zoom_key);
                        writer.WritePropertyName("w");
                        writer.WriteValue(dic_pic[selectpage][i].rectrr.Rect.Width * dic_pic[selectpage][i].zoom_key);
                        writer.WritePropertyName("h");
                        writer.WriteValue(dic_pic[selectpage][i].rectrr.Rect.Height * dic_pic[selectpage][i].zoom_key);
                    }
                    writer.WriteEndObject();
                    writer.WriteEndObject();

                    StreamWriter wtyeu = new StreamWriter(field);
                    wtyeu.Write(sw);
                    wtyeu.Flush();
                    wtyeu.Close();
                    writer.Close();
                    sw.Close();
                }
            }
            //取出正在评级的selectpage
            grade_selectpage = selectpage;
            //亚共析钢带状                                                   
            if (YGXZDZ == steel)
            {
                this.root.Children.Add(layer);
                DirectionWindow directionWindow = new DirectionWindow();
                directionWindow.Owner = this;
                directionWindow.ShowDialog();
                if (directionWindow.DialogResult == true)
                {
                    //this.pagetitle.IsEnabled = false;
                    //this.cantab.IsEnabled = false;
                    //大进度条
                    this.pbw.Visibility = Visibility.Visible;
                    this.pbw.progbar.Maximum = page_filenames[selectpage].Count;
                    this.pbw.progbar.Value = 0;
                    this.pbw.progbar_num.Content = "0%";
                    this.pbw.show_num.Content = "0/" + page_filenames[selectpage].Count.ToString();
                    //小进度条
                    //this.minpbw.Visibility = Visibility.Visible;
                    this.minpbw.minprogbar.Maximum = page_filenames[selectpage].Count;
                    this.minpbw.minprogbar.Value = 0;
                    this.minpbw.minprogbar_num.Content = "0%";
                    this.minpbw.minshow_num.Content = "0/" + page_filenames[selectpage].Count.ToString();
                    test_index = 0;
                    DZ_direction = directionWindow.directionnum;
                    detectParams = new DetectParams
                    {
                        YGXG_DZ = new YGXG_DZ { direction = DZ_direction == 0 ? "v" : "h" }
                    };

                    pythonExecutor.ibmBzpj(this.pagetitle.lblgrade, ZT_H, G_XZ, detectParams, page_filenames[selectpage]);
                    //Console.WriteLine(DZ_direction);
                    func();
                    return;
                }
                else
                {
                    //this.pagetitle.IsEnabled = true;
                    //this.cantab.IsEnabled = true;
                    func();
                    return;
                }
            }
            else if ("夹杂物" == steel)
            {
                //this.pagetitle.IsEnabled = false;
                //this.cantab.IsEnabled = false;
                //大进度条
                this.pbw.Visibility = Visibility.Visible;
                this.pbw.progbar.Maximum = page_filenames[selectpage].Count;
                this.pbw.progbar.Value = 0;
                this.pbw.progbar_num.Content = "0%";
                this.pbw.show_num.Content = "0/" + page_filenames[selectpage].Count.ToString();
                //小进度条
                //this.minpbw.Visibility = Visibility.Visible;
                this.minpbw.minprogbar.Maximum = page_filenames[selectpage].Count;
                this.minpbw.minprogbar.Value = 0;
                this.minpbw.minprogbar_num.Content = "0%";
                this.minpbw.minshow_num.Content = "0/" + page_filenames[selectpage].Count.ToString();
                test_index = 0;

                string incl_para = "{'YGB-JZW': {'output_cls_names': [";
                for (int i = 0; i < pagefirst.lincl.Count; i++)
                {
                    incl_para += "'" + pagefirst.lincl[i] + "',";
                }
                incl_para = incl_para.Substring(0, incl_para.Length - 1);
                incl_para += "]}}";
                pythonExecutor.ibmBzpj(this.pagetitle.lblgrade, ZT_H, G_XZ, incl_para, page_filenames[selectpage]);

                func();
                return;

            }
            else if ("组织识别" == steel)
            {
                //MessageBox.Show("组织识别");
                //显示进度条禁用一些按钮
                //this.pagetitle.IsEnabled = false;
                //this.cantab.IsEnabled = false;
                this.pbw.Visibility = Visibility.Visible;
                this.pbw.progbar.Maximum = page_filenames[selectpage].Count;
                this.pbw.progbar.Value = 0;
                this.pbw.progbar_num.Content = "0%";
                this.pbw.show_num.Content = "0/" + page_filenames[selectpage].Count.ToString();
                //小进度条
                //this.minpbw.Visibility = Visibility.Visible;
                this.minpbw.minprogbar.Maximum = page_filenames[selectpage].Count;
                this.minpbw.minprogbar.Value = 0;
                this.minpbw.minprogbar_num.Content = "0%";
                this.minpbw.minshow_num.Content = "0/" + page_filenames[selectpage].Count.ToString();

                //序号清零
                test_index = 0;
                //初始化脚本执行器
                //PythonExecutor pythonExecutor = new PythonExecutor(SynchronizationContext.Current);
                //pythonExecutor.ReceivedControlData += ReceivedControlData;
                ////钢钟catagory
                //string ZT_H = image_name[selectpage][7];
                ////检测项目items
                //string G_XZ = image_name[selectpage][8];
                //调用评级检测python接口，第一个参数是返回信息显示的控件
                //第二个是钢种catagory，第三个是检测项目items
                //第四个是要检测的图像列表，全路径列表              
                pythonExecutor.ibmZzsb(this.pagetitle.lblgrade, testitems_param, page_filenames[selectpage]);
                //pythonExecutor.ibmZzsb(this.pagetitle.lblgrade, page_filenames[selectpage]);
                return;
            }
            else
            {
                //大进度条
                this.pbw.Visibility = Visibility.Visible;
                this.pbw.progbar.Maximum = page_filenames[selectpage].Count;
                this.pbw.progbar.Value = 0;
                this.pbw.progbar_num.Content = "0%";
                this.pbw.show_num.Content = "0/" + page_filenames[selectpage].Count.ToString();

                //小进度条
                this.minpbw.minprogbar.Maximum = page_filenames[selectpage].Count;
                this.minpbw.minprogbar.Value = 0;
                this.minpbw.minprogbar_num.Content = "0%";
                this.minpbw.minshow_num.Content = "0/" + page_filenames[selectpage].Count.ToString();
                //序号清零
                test_index = 0;

                //调用评级检测python接口，第一个参数是返回信息显示的控件
                //第二个是钢种catagory，第三个是检测项目items
                //第四个是要检测的图像列表，全路径列表
                pythonExecutor.ibmBzpj(this.pagetitle.lblgrade, ZT_H, G_XZ, testitems_param, page_filenames[selectpage]);
            }
        }
        #endregion

        #region 全屏显示
        /// <summary>
        /// 全屏显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void canfill(object sender, MouseButtonEventArgs e)
        {
            int index = 0;
            for (int i = 0; i < dic_pic[selectpage].Count; i++)
            {
                if (dic_pic[selectpage][i].st == true)
                {
                    index = i;
                    break;
                }
            }
            open_full_screen_window(index, 0);
        }
        #endregion

        #region 显示图像的缩放滑块
        /// <summary>
        /// 缩放滑块
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void zoomchange(object sender, System.Windows.RoutedPropertyChangedEventArgs<double> e)
        {
            zoom[selectpage] = Math.Round(e.NewValue, 2) - 1;
            piczoom();
        }
        #endregion

        #region 窗体最小化
        /// <summary>
        /// 最小化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void window_min_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }
        #endregion

        #region 窗体最大化
        /// <summary>
        /// 最大化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void window_max_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if(this.WindowState==WindowState.Maximized)
            {
                this.WindowState = WindowState.Normal;
            }
            else
            {
                this.WindowState = WindowState.Maximized;
            }
        }
        #endregion

        #region 关闭窗体
        /// <summary>
        /// 关闭窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void window_close_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (grade_state == false)//是否在检测默认false未检测
            {
                Application.Current.Shutdown();
            }
        }
        #endregion

        #region 录入打开文件
        /// <summary>
        /// 打开文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openfiles(object sender, MouseButtonEventArgs e)
        {
            //如果钢种、标准和检测项目有一个为空则退出 
            if (this.pagefirst.steel == "" || this.pagefirst.standard == "" || this.pagefirst.testitems == "")
            {
                return;
            }
            //蒙板
            this.root.Children.Add(layer);
            //弹出录入窗口
            Sample_Information_Enter sample = new Sample_Information_Enter();
            sample.grade_steel = this.pagefirst.steel;
            sample.grade_standard = this.pagefirst.standard;
            sample.test_item = this.pagefirst.testitems;
            sample.Owner = this;
            //弹出窗口不显示在任务栏内
            sample.ShowInTaskbar = false;
            sample.ShowDialog();

            //如果文件夹存在
            if (sample.DialogResult == true && Directory.Exists(sample.txt_Picture_catalog))
            {
                //取当前时分秒作为所有字典内的唯一标识
                string pagename = System.DateTime.Now.ToString("hhmmss");

                //选中标签页
                selectpage = pagename;
                //滚动条位置
                string ScrollPositionNum = "0";
                //存储当前选中显示图片的所有信息
                image_name.Add(pagename, new List<string>());
                image_name[pagename].Add(sample.grade_steel);                   //0:钢种
                image_name[pagename].Add(sample.grade_standard);                //1：标准          
                image_name[pagename].Add(sample.test_item);                     //2：检测项目
                image_name[pagename].Add(sample.comb_Number_prefix);            //3：样品名称
                image_name[pagename].Add(sample.comb_Number_suffix);            //4：后缀
                image_name[pagename].Add(sample.comb_Inspection_instrument);    //5：检测仪器
                image_name[pagename].Add(sample.txt_Picture_catalog);           //6：文件夹
                image_name[pagename].Add(this.pagefirst.catagory);              //7：钢种catagory参数
                image_name[pagename].Add(this.pagefirst.items);                 //8：检测项目参数
                image_name[pagename].Add(this.pagefirst.testitems_param);       //9: param 数据库{'YBG-W': {'w_cls':'wa'}}
                image_name[pagename].Add(ScrollPositionNum);                    //10:记录每个页面滚动条位置初始为0
                string temp = "";
                for(int m=0;m<pagefirst.lincl.Count;m++)
                {
                    temp += pagefirst.lincl[m] + ",";
                }
                temp = temp.Substring(0, temp.Length - 1);
                image_name[pagename].Add(temp);                                  //11:夹杂物种类。
                //录入后将夹杂物的选择项标签删除
                if (pagefirst.Can_Testitems.FindName("inclusion") as Inclusion != null)
                {
                    pagefirst.Can_Testitems.Children.Remove(pagefirst.Can_Testitems.FindName("inclusion") as Inclusion);
                    pagefirst.Can_Testitems.UnregisterName("inclusion");
                }

                //恢复没被选中显示
                foreach (KeyValuePair<string, PageControl> keyvalue in listpage)
                {
                    keyvalue.Value.lblhomepage.Foreground = new SolidColorBrush(Color.FromRgb(0xAA, 0xAA, 0xAA));
                    keyvalue.Value.pagegird.Background = new SolidColorBrush(Color.FromRgb(0x43, 0x4e, 0x61));
                }
                //首页没被选中显示
                lblhomepage.Foreground = new SolidColorBrush(Color.FromRgb(0xAA, 0xAA, 0xAA));
                lblhomepage.Background = new SolidColorBrush(Color.FromRgb(0x43, 0x4e, 0x61));
                //隐藏首页显示图像加载页
                pagefirst.Visibility = Visibility.Hidden;
                svshowimg.Visibility = Visibility.Visible;

                //增加标签页信息
                PageControl pagec = new PageControl();
                pagec.lblhomepage.Content = image_name[pagename][3];
                pagec.Tag = image_name[pagename][2];
                pagec.Width = 140;
                pagec.Height = 37;
                pagec.lblhomepage.Tag = pagename;
                pagec.lblhomepage.ToolTip = image_name[selectpage][3];
                pagec.lblhomepage.MouseMove += new System.Windows.Input.MouseEventHandler(mousemove_itemspage);
                pagec.lblhomepage.MouseLeave += new System.Windows.Input.MouseEventHandler(mouseleave_itemspage);
                pagec.lblhomepage.PreviewMouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(select_page);
                pagec.SetValue(Canvas.TopProperty, 3.0);
                pagec.SetValue(Canvas.LeftProperty, 157.0 + listpage.Count * (lblhomepage.Width + 2));
                pagec.SetValue(Canvas.RightProperty, double.NaN);
                pagec.SetValue(Canvas.BottomProperty, double.NaN);
                pagec.lblhomepage.Foreground = new SolidColorBrush(Color.FromRgb(0xF5, 0x9A, 0x23));
                pagec.pagegird.Background = new SolidColorBrush(Color.FromRgb(0x18, 0x25, 0x3C));
                listpage.Add(selectpage, pagec);

                //检测菜单是否超限
                Show_menu();
                //添加标签名称列表
                listpagename.Add(selectpage);

                //在容器中增加标签页
                cantab.Children.Add(pagec);
                //注册控件的名称
                cantab.RegisterName("c" + selectpage, pagec);

                //当标签存放满后的操作
                if (listpagename.Count > tab_num - 1)
                {
                    pagec.SetValue(Canvas.TopProperty, 3.0);
                    pagec.SetValue(Canvas.LeftProperty, 157.0 + (tab_num - 1) * (140 + 2));
                    pagec.SetValue(Canvas.RightProperty, double.NaN);
                    pagec.SetValue(Canvas.BottomProperty, double.NaN);

                    menu.Items.Clear();
                    deletelabel.Clear();

                    for (int i = 0; i < listpagename.Count; i++)
                    {
                        if (listpage.Count > tab_num)
                        {
                            if (i > (tab_num - 1))
                            {
                                Label label = new Label();
                                label.Content = listpage[listpagename[i - 1]].lblhomepage.Content;//pagename//image_name[pagename][3]
                                                                                                  // label.Name = pagename;
                                label.Tag = listpagename[i - 1];
                                label.Background = new SolidColorBrush(Color.FromRgb(0x43, 0x4e, 0x61));
                                label.Foreground = new SolidColorBrush(Color.FromRgb(0xAA, 0xAA, 0xAA));
                                label.HorizontalContentAlignment = HorizontalAlignment.Center;                            
                                label.VerticalContentAlignment=VerticalAlignment.Center;
                                label.FontSize = 14;
                                label.Height = 37;
                                label.Width = 140;
                                label.PreviewMouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(ClickMneuLabel);
                                deletelabel.Add(listpagename[i - 1]);
                                menu.Items.Add(label);

                            }
                        }
                    }
                }

                //添加首页录入信息
                HomePageEntry hpe = new HomePageEntry();
                hpe.txttestmechine.Text = image_name[pagename][5];
                hpe.txtpicpath.Text = image_name[pagename][6];
                hpe.Width = 235;
                hpe.Cursor = Cursors.Hand;
                hpe.Tag = pagename;
                hpe.PreviewMouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(select_Home_Page_Entry);
                hpe.ToolTip = image_name[pagename][6];
                hpe.SetValue(Canvas.TopProperty, 65.0 * listhompage.Count);
                hpe.SetValue(Canvas.LeftProperty, 0.0);
                hpe.SetValue(Canvas.RightProperty, double.NaN);
                hpe.SetValue(Canvas.BottomProperty, double.NaN);
                listhompage.Add(selectpage, hpe);

                //筛选标签
                screen_label(image_name[selectpage][2]);

                //文件夹结构添加
                page_filenames.Add(selectpage, new List<string>());

                //增加显示图像的canvas
                Canvas canvas = new Canvas();
                canvas.Height = 620;
                canvas.Width = 1320;
                canvas.HorizontalAlignment = HorizontalAlignment.Left;
                canvas.VerticalAlignment = VerticalAlignment.Top;
                for (int i = 0; i < showpic.Children.Count; i++)
                {
                    showpic.Children[i].Visibility = Visibility.Hidden;
                }
                showpic.Children.Add(canvas);
                showpic.RegisterName("can" + selectpage, canvas);
                DirectoryInfo TheFolder = new DirectoryInfo(image_name[pagename][6]);
                dic_pic.Add(selectpage, new List<Picturebox>());
                //初始化显示倍数为0
                zoom.Add(selectpage, 0);
                //文件清零
                //zm:添加文件名列表
                fns.Clear();
                fns_name.Clear();

                //遍历文件
                foreach (FileInfo NextFile in TheFolder.GetFiles())
                {
                    if (System.IO.Path.GetExtension(NextFile.FullName).ToLower() == ".jpg" || System.IO.Path.GetExtension(NextFile.FullName).ToLower() == ".bmp")
                    {
                        //将文件夹下的图像文件添加到文件列表中
                        fns.Add(NextFile.FullName);
                        fns_name.Add(NextFile.ToString());
                    }
                }
                //禁用所有筛选标签页
                Header_Opacity_All_ChangeDark();
                //如果添加图片数量大于0则启动线程
                if (fns.Count > 0)
                {
                    //标签栏禁用
                    cantab.IsEnabled = false;
                    //关闭按钮禁用
                    pagetitle.isclosed = false;
                    //开启加载图片线程
                    Thread th = new Thread(display_img);
                    th.Start();
                }
                
            }
            else if (!Directory.Exists(sample.txt_Picture_catalog))
            {
                //lbf 2020/10/28
                MessageBox.Show(string.Format("[{0}] 不存在!", sample.txt_Picture_catalog), "提示：", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }
        }
        #endregion

        #region 标签页选项卡切换事件
        /// <summary>
        /// 菜单选项卡事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ClickMneuLabel(object sender, MouseButtonEventArgs e)
        {
            Label selectlabel = ((Label)sender);
            String select_page = ((Label)sender).Tag.ToString();
            selectpage = select_page;
            menu.Items.Clear();
            deletelabel.Clear();
            //向菜单选项卡添加菜单多余8个的添加
            for (int i = 0; i < listpagename.Count; i++)
            {

                if (listpage.Count > tab_num)
                {
                    if (i > (tab_num - 2))
                    {
                        Label label = new Label();
                        label.Content = listpage[listpagename[i]].lblhomepage.Content;//pagename//image_name[pagename][3]
                                                                                      // label.Name = pagename;
                        label.Tag = listpagename[i];
                        label.Background = new SolidColorBrush(Color.FromRgb(0x43, 0x4e, 0x61));
                        label.Foreground = new SolidColorBrush(Color.FromRgb(0xAA, 0xAA, 0xAA));
                        label.HorizontalContentAlignment = HorizontalAlignment.Center;
                        label.VerticalContentAlignment = VerticalAlignment.Center;
                        label.FontSize = 14;
                        label.Height = 37;
                        label.Width = 140;
                        label.PreviewMouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(ClickMneuLabel);
                        deletelabel.Add(listpagename[i]);
                        menu.Items.Add(label);
                        // menu.Items.Remove(selectlabel);
                        (cantab.FindName("c" + listpagename[i]) as PageControl).Visibility = Visibility.Hidden;
                        if (listpagename[i] == selectpage)
                        {

                            // menu.Items.Add(menu.Items[i]);
                            (cantab.FindName("c" + listpagename[i]) as PageControl).Visibility = Visibility.Visible;
                        }
                    }

                }

            }
            //移除选中的标签
            for (int i = 0; i < deletelabel.Count; i++)
            {
                if (selectpage == deletelabel[i])
                {
                    deletelabel.RemoveAt(i);
                    menu.Items.RemoveAt(i);
                }
            }


            //恢复没被选中显示
            foreach (KeyValuePair<string, PageControl> keyvalue in listpage)
            {

                keyvalue.Value.lblhomepage.Foreground = new SolidColorBrush(Color.FromRgb(0xAA, 0xAA, 0xAA));
                keyvalue.Value.pagegird.Background = new SolidColorBrush(Color.FromRgb(0x43, 0x4e, 0x61));
                if (keyvalue.Value.lblhomepage.Tag.ToString() == selectpage)
                {
                    listpage[select_page].SetValue(Canvas.TopProperty, 3.0);
                    listpage[select_page].SetValue(Canvas.LeftProperty, 157.0 + (tab_num - 1) * (142));
                    listpage[select_page].SetValue(Canvas.RightProperty, double.NaN);
                    listpage[select_page].SetValue(Canvas.BottomProperty, double.NaN);

                }
            }
            //首页没被选中显示
            lblhomepage.Foreground = new SolidColorBrush(Color.FromRgb(0xAA, 0xAA, 0xAA));
            lblhomepage.Background = new SolidColorBrush(Color.FromRgb(0x43, 0x4e, 0x61));
            //隐藏首页显示图像加载页
            pagefirst.Visibility = Visibility.Hidden;
            svshowimg.Visibility = Visibility.Visible;
            //显示选中标签页
            listpage[select_page].lblhomepage.Foreground = new SolidColorBrush(Color.FromRgb(0xF5, 0x9A, 0x23));
            listpage[select_page].pagegird.Background = new SolidColorBrush(Color.FromRgb(0x18, 0x25, 0x3C));

            //显示被选中标签页的图像
            for (int i = 0; i < showpic.Children.Count; i++)
            {
                showpic.Children[i].Visibility = Visibility.Hidden;
            }
            (showpic.FindName("can" + select_page) as Canvas).Visibility = Visibility.Visible;

            this.subtitle.lblfilecount.Content = page_filenames[selectpage].Count.ToString() + "个文件";
            this.subtitle.lblzoom.Visibility = Visibility.Visible;
            this.subtitle.sldzoom.Visibility = Visibility.Visible;
            this.subtitle.lblpercentge.Visibility = Visibility.Visible;

            this.showpic.Height = (showpic.FindName("can" + selectpage) as Canvas).Height;

            this.subtitle.sldzoom.Value = 1 + zoom[selectpage];

            //判断是否是首页
            homepage_disabled();
        }
        #endregion

        #region 标签超长显示菜单选项
        /// <summary>
        /// 菜单选项卡是否显示
        /// </summary>
        public void Show_menu()
        {
            if (listpage.Count > tab_num)//tab_num=8最原始
            {
                menugrid.Visibility = Visibility.Visible;
            }
            else
            {
                menugrid.Visibility = Visibility.Hidden;
            }

        }
        #endregion

        #region 选中首页录入项
        /// <summary>
        /// 选中首页录入项
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void select_Home_Page_Entry(object sender, MouseButtonEventArgs e)
        {
            String select_page = ((HomePageEntry)sender).Tag.ToString();

            selectpage = select_page;

            //恢复没被选中显示
            foreach (KeyValuePair<string, PageControl> keyvalue in listpage)
            {
                keyvalue.Value.lblhomepage.Foreground = new SolidColorBrush(Color.FromRgb(0xAA, 0xAA, 0xAA));
                keyvalue.Value.pagegird.Background = new SolidColorBrush(Color.FromRgb(0x43, 0x4e, 0x61));

            }
            //首页没被选中显示
            lblhomepage.Foreground = new SolidColorBrush(Color.FromRgb(0xAA, 0xAA, 0xAA));
            lblhomepage.Background = new SolidColorBrush(Color.FromRgb(0x43, 0x4e, 0x61));
            //隐藏首页显示图像加载页
            pagefirst.Visibility = Visibility.Hidden;
            svshowimg.Visibility = Visibility.Visible;

            //显示选中标签页
            listpage[select_page].lblhomepage.Foreground = new SolidColorBrush(Color.FromRgb(0xF5, 0x9A, 0x23));
            listpage[select_page].pagegird.Background = new SolidColorBrush(Color.FromRgb(0x18, 0x25, 0x3C));

            //显示或隐藏第八个
            for (int i = 0; i < listpagename.Count; i++)
            {
                if (listpage.Count > tab_num)
                {
                    //前面的八个都显示出来，否则点击时下面那句话会隐藏第七个
                    (cantab.FindName("c" + listpagename[i]) as PageControl).Visibility = Visibility.Visible;
                    if (i > (tab_num - 1))
                    {
                        (cantab.FindName("c" + listpagename[i]) as PageControl).Visibility = Visibility.Hidden;
                        if (listpagename[i] == selectpage)
                        {
                            listpage[select_page].SetValue(Canvas.TopProperty, 3.0);
                            listpage[select_page].SetValue(Canvas.LeftProperty, 157.0 + (tab_num - 1) * (142));
                            listpage[select_page].SetValue(Canvas.RightProperty, double.NaN);
                            listpage[select_page].SetValue(Canvas.BottomProperty, double.NaN);
                            // menu.Items.Add(menu.Items[i]);
                            (cantab.FindName("c" + listpagename[i]) as PageControl).Visibility = Visibility.Visible;
                        }
                    }

                }
            }
            //把所有选项卡找出来多的第9个开始存入菜单选项卡
            menu.Items.Clear();
            deletelabel.Clear();
            for (int i = 0; i < listpagename.Count; i++)
            {

                if (listpage.Count > tab_num)
                {
                    if (i > (tab_num - 2))
                    {
                        Label label = new Label();
                        label.Content = listpage[listpagename[i]].lblhomepage.Content;//pagename//image_name[pagename][3]
                                                                                      // label.Name = pagename;
                        label.Tag = listpagename[i];
                        label.Background = new SolidColorBrush(Color.FromRgb(0x43, 0x4e, 0x61));
                        label.Foreground = new SolidColorBrush(Color.FromRgb(0xAA, 0xAA, 0xAA));
                        label.HorizontalContentAlignment = HorizontalAlignment.Center;
                        label.VerticalContentAlignment = VerticalAlignment.Center;
                        label.FontSize = 14;
                        label.Height = 37;
                        label.Width = 140;
                        label.PreviewMouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(ClickMneuLabel);
                        deletelabel.Add(listpagename[i]);
                        Console.WriteLine("listpagename[i]" + listpagename[i]);
                        menu.Items.Add(label);
                    }
                }
            }
            //前面添加所有多出的菜单后面移除选中的
            //移除选中的标签
            for (int i = 0; i < deletelabel.Count; i++)
            {
                if (selectpage == deletelabel[i])
                {
                    deletelabel.RemoveAt(i);
                    menu.Items.RemoveAt(i);
                }
            }
            //选中前七个时移除菜单选项卡与选项卡中第八个重复的。
            if (deletelabel.Count > 0 && listpagename.Count > tab_num)
            {

                for (int i = 0; i < listpagename.Count; i++)
                {
                    if (i <= (tab_num - 1))
                    {
                        if (listpagename[i].IndexOf(selectpage) > -1)
                        {
                            for (int i1 = 0; i1 < deletelabel.Count; i1++)
                            {
                                if (listpagename[tab_num - 1] == deletelabel[i1])
                                {
                                    deletelabel.RemoveAt(i1);
                                    menu.Items.RemoveAt(i1);
                                }
                            }
                        }
                    }
                }
            }

            //显示被选中标签页的图像
            for (int i = 0; i < showpic.Children.Count; i++)
            {
                showpic.Children[i].Visibility = Visibility.Hidden;
            }
            (showpic.FindName("can" + select_page) as Canvas).Visibility = Visibility.Visible;

            this.subtitle.lblfilecount.Content = page_filenames[selectpage].Count.ToString() + "个文件";
            this.subtitle.lblzoom.Visibility = Visibility.Visible;
            this.subtitle.sldzoom.Visibility = Visibility.Visible;
            this.subtitle.lblpercentge.Visibility = Visibility.Visible;

            this.showpic.Height = (showpic.FindName("can" + selectpage) as Canvas).Height;

            this.subtitle.sldzoom.Value = 1 + zoom[selectpage];

            //判断是否是首页
            homepage_disabled();
        }
        #endregion

        #region 标签页关闭按钮状态切换
        /// <summary>
        /// 标签页关闭按钮状态切换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mousemove_itemspage(object sender, MouseEventArgs e)
        {
            Point pp = e.GetPosition(e.Source as FrameworkElement);

            String select_page = ((Label)sender).Tag.ToString();

            //该区域为关闭按钮区域
            if (pp.X >= 127 && pp.Y <= 13)
            {
                this.listpage[select_page].imghomepage.Visibility = Visibility.Hidden;
                this.listpage[select_page].imghomepagered.Visibility = Visibility.Visible;
                this.Cursor = Cursors.Hand;
            }
            else
            {
                this.listpage[select_page].imghomepage.Visibility = Visibility.Visible;
                this.listpage[select_page].imghomepagered.Visibility = Visibility.Hidden;
                this.Cursor = Cursors.Arrow;
            }
        }
        #endregion

        #region 鼠标离开标签页关闭按钮时状态恢复
        /// <summary>
        /// 鼠标离开标签页关闭按钮时状态恢复
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mouseleave_itemspage(object sender, MouseEventArgs e)
        {
            String select_page = ((Label)sender).Tag.ToString();
            if (listpage.ContainsKey(select_page))
            {
                this.listpage[select_page].imghomepage.Visibility = Visibility.Visible;
                this.listpage[select_page].imghomepagered.Visibility = Visibility.Hidden;
            }
            this.Cursor = Cursors.Arrow;
        }
        #endregion

        #region 标签页事件处理
        /// <summary>
        /// 由于控件重叠，两个控件都有事件无法解决，这里根据坐标处理事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void select_page(object sender, MouseButtonEventArgs e)
        {
            if (gc != null)
            {
                gc.WindowState = WindowState.Normal;
                gc.Top = (this.Height - gc.Height) / 2;
                gc.Left = (this.Width - gc.Width) / 2;
                gc.Activate();
                return;
            }
            Point pp = Mouse.GetPosition(e.Source as FrameworkElement);
            String select_page = ((Label)sender).Tag.ToString();

            //该区域为关闭按钮区域
            if (pp.X >= 127 && pp.Y <= 13)
            {

                //清空标签页,更改为删除指定类型的孩子，然后重新排列分布
                cantab.Children.Remove(cantab.FindName("c" + select_page) as PageControl);
                //清除显示图像页内容
                showpic.Children.Remove(showpic.FindName("can" + select_page) as Canvas);
                //清除首页录入框
                this.pagefirst.showinfo.Children.Remove(this.pagefirst.showinfo.FindName("hp" + select_page) as HomePageEntry);
                //清除选中文件字典
                page_filenames.Remove(select_page);
                image_name.Remove(select_page);
                zoom.Remove(select_page);
                pich.Remove(select_page);
                picw.Remove(select_page);

                listpage.Remove(select_page);
                listpagename.Remove(select_page);
                listhompage.Remove(select_page);
                Show_menu();
                this.pagefirst.showinfo.Height = listhompage.Count * 65;
               

                //恢复没被选中显示
                if (listpage.Count > 0)
                {
                    menu.Items.Clear();
                    deletelabel.Clear();
                    for (int i = 0; i < listpagename.Count; i++)
                    {
                        if (listpage.Count > tab_num)
                        {
                            if (i > (tab_num - 1))
                            {
                                Label label = new Label();
                                label.Content = listpage[listpagename[i]].lblhomepage.Content;//pagename//image_name[pagename][3]
                                                                                              // label.Name = pagename;
                                label.Tag = listpagename[i];
                                label.Background = new SolidColorBrush(Color.FromRgb(0x43, 0x4e, 0x61));
                                label.Foreground = new SolidColorBrush(Color.FromRgb(0xF5, 0x9A, 0x23));
                                label.HorizontalContentAlignment = HorizontalAlignment.Center;
                                label.VerticalContentAlignment = VerticalAlignment.Center;
                                label.FontSize = 14;
                                label.Height = 37;
                                label.Width = 140;
                                label.PreviewMouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(ClickMneuLabel);
                                deletelabel.Add(listpagename[i]);
                                menu.Items.Add(label);

                            }

                        }

                    }
                    for (int i = 0; i < listpage.Count; i++)
                    {
                        // Console.WriteLine(i + " 有这些" + listpagename[i]);
                        //标签页
                        (showpic.FindName("can" + listpagename[i]) as Canvas).Visibility = Visibility.Hidden;
                        //标签全显示
                        (cantab.FindName("c" + listpagename[i]) as PageControl).Visibility = Visibility.Visible;
                        //隐藏菜单选项卡下方的标签
                        if (i > tab_num-1)
                        {
                            (cantab.FindName("c" + listpagename[i]) as PageControl).Visibility = Visibility.Hidden;
                        }

                        if (selectpage == select_page && i == 0)
                        {
                            listpage[listpagename[i]].lblhomepage.Foreground = new SolidColorBrush(Color.FromRgb(230, 230, 33));
                            listpage[listpagename[i]].pagegird.Background = new SolidColorBrush(Color.FromRgb(0x18, 0x25, 0x3C));

                            selectpage = listpagename[i];
                        }
                        listpage[listpagename[i]].SetValue(Canvas.TopProperty, 3.0);
                        listpage[listpagename[i]].SetValue(Canvas.LeftProperty, 157.0 + i * (lblhomepage.Width + 2));
                        listpage[listpagename[i]].SetValue(Canvas.RightProperty, double.NaN);
                        listpage[listpagename[i]].SetValue(Canvas.BottomProperty, double.NaN);
                        //录入框
                        //listhompage[listpagename[i]].SetValue(Canvas.TopProperty, 65.0 * i);
                        //listhompage[listpagename[i]].SetValue(Canvas.LeftProperty, 0.0);
                        //listhompage[listpagename[i]].SetValue(Canvas.RightProperty, double.NaN);
                        //listhompage[listpagename[i]].SetValue(Canvas.BottomProperty, double.NaN);

                    }

                    if (selectpage != "首页")
                    {
                        (showpic.FindName("can" + selectpage) as Canvas).Visibility = Visibility.Visible;
                        this.showpic.Height = (showpic.FindName("can" + selectpage) as Canvas).Height;

                        //标签页
                        screen_label(listpage[selectpage].Content.ToString());
                    }
                    else
                    {
                        //标签页
                        screen_label(this.pagefirst.testitems);
                    }
                }
                else
                {
                    //首页被选中显示
                    lblhomepage.Foreground = new SolidColorBrush(Color.FromRgb(0xF5, 0x9A, 0x23));
                    lblhomepage.Background = new SolidColorBrush(Color.FromRgb(0x18, 0x25, 0x3C));
                    //显示首页显示图像加载页
                    pagefirst.Visibility = Visibility.Visible;
                    svshowimg.Visibility = Visibility.Hidden;
                    //选中标签页
                    selectpage = "首页";

                    this.subtitle.lblfilecount.Content = "欢迎使用AIRS系统！选择检测项目";
                    this.subtitle.lblzoom.Visibility = Visibility.Hidden;
                    this.subtitle.sldzoom.Visibility = Visibility.Hidden;
                    this.subtitle.lblpercentge.Visibility = Visibility.Hidden;

                }
            }
            //其他区域为选中标签页区域
            else
            {
                //只有当标签页切换了才执行操作
                if (selectpage != select_page)
                {
                    selectpage = select_page;
                    //恢复没被选中显示
                    foreach (KeyValuePair<string, PageControl> keyvalue in listpage)
                    {
                        keyvalue.Value.lblhomepage.Foreground = new SolidColorBrush(Color.FromRgb(0xAA, 0xAA, 0xAA));
                        keyvalue.Value.pagegird.Background = new SolidColorBrush(Color.FromRgb(0x43, 0x4e, 0x61));
                    }
                    //首页没被选中显示
                    lblhomepage.Foreground = new SolidColorBrush(Color.FromRgb(0xAA, 0xAA, 0xAA));
                    lblhomepage.Background = new SolidColorBrush(Color.FromRgb(0x43, 0x4e, 0x61));
                    //隐藏首页显示图像加载页
                    pagefirst.Visibility = Visibility.Hidden;
                    svshowimg.Visibility = Visibility.Visible;
                    //显示选中标签页
                    listpage[select_page].lblhomepage.Foreground = new SolidColorBrush(Color.FromRgb(0xF5, 0x9A, 0x23));
                    listpage[select_page].pagegird.Background = new SolidColorBrush(Color.FromRgb(0x18, 0x25, 0x3C));


                    //显示被选中标签页的图像
                    for (int i = 0; i < showpic.Children.Count; i++)
                    {
                        showpic.Children[i].Visibility = Visibility.Hidden;
                    }
                    (showpic.FindName("can" + select_page) as Canvas).Visibility = Visibility.Visible;

                    this.subtitle.lblfilecount.Content = page_filenames[selectpage].Count.ToString() + "个文件";
                    this.subtitle.lblzoom.Visibility = Visibility.Visible;
                    this.subtitle.sldzoom.Visibility = Visibility.Visible;
                    this.subtitle.lblpercentge.Visibility = Visibility.Visible;

                    this.showpic.Height = (showpic.FindName("can" + selectpage) as Canvas).Height;
                  
                    this.subtitle.sldzoom.Value = 1 + zoom[selectpage];
                    this.svshowimg.ScrollToVerticalOffset(Convert.ToDouble(image_name[selectpage][10]));
                }
            }
            //判断是否是首页
            homepage_disabled();
        }
        #endregion

        #region 清除选中项
        /// <summary>
        /// 清除选中项
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void clearbox(object sender, MouseButtonEventArgs e)
        {
            int index = Convert.ToInt32(((Image)sender).Tag.ToString());

            if (e.ClickCount == 1)
            {
                for (int m = 0; m < dic_pic[selectpage].Count; m++)
                {
                    dic_pic[selectpage][m].box.Visibility = Visibility.Hidden;
                    dic_pic[selectpage][m].st = false;
                }
                dic_pic[selectpage][index].box.Visibility = Visibility.Visible;
                dic_pic[selectpage][index].st = true;
            }
            else if (e.ClickCount == 2)
            {
                open_full_screen_window(index, 0);
            }
        }
        #endregion

        #region 分析过程按钮
        /// <summary>
        /// 分析过程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnanalysis_Click(object sender, RoutedEventArgs e)
        {
            int index = Convert.ToInt32(((Button)sender).Tag.ToString());
            open_full_screen_window(index, 1);
        }
        #endregion

        #region 系统启动
        /// <summary>
        /// 系统启动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            homepage_disabled();
        }
        #endregion

        #region 滚轮事件
        /// <summary>
        /// 滚轮滚动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ScrollViewer_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
        {
            //if (filenames.Count > 0)
            if (selectpage != "首页" && page_filenames[selectpage].Count > 0)
            {        
                //当禁用滚轮时，肯定是按下Ctrl键，这时执行放大或缩小操作 
                if (mousedown)
                {
                    if (e.Delta > 0)
                    {
                        zoom[selectpage] = zoom[selectpage] + 0.05;
                       // zoom[selectpage] = zoom[selectpage] + 2;
                    }
                    else if (e.Delta < 0)
                    {
                        zoom[selectpage] = zoom[selectpage] - 0.05;
                        //zoom[selectpage] = zoom[selectpage] - 2;
                    }
                    //zoom = zoom + e.Delta / 2400.0;
                    if (zoom[selectpage] < -0.9)
                    {
                        zoom[selectpage] = -0.9;
                    }
                    //else if((picw * (1+zoom)) >(this.showpic.Width-20))
                    else if (zoom[selectpage] > 2)
                    {
                        zoom[selectpage] = 2;
                    }
                    this.subtitle.sldzoom.Value = 1 + zoom[selectpage];
                    piczoom();
                }
                else
                {
                    if (e.Delta > 0)
                    {
                        // 向上滚动         
                        svshowimg.LineUp();
                       // svshowimg.PageUp();
                    }
                    if (e.Delta < 0)
                    {
                        // 向下滚动     
                         svshowimg.LineDown();                        
                        // svshowimg.PageDown();
                    }
                }
            }
        }
        #endregion

        #region 图像缩放
        /// <summary>
        /// 图像缩放
        /// </summary>
        private void piczoom()
        {
            int canvas_height = 0;
            //判断一行能存放几个pic
            int displaynum = Convert.ToInt32(Math.Floor(this.showpic.Width / (picw[selectpage] * (1 + zoom[selectpage]) + 20)));
            if (displaynum == 0)
            {
                displaynum = 1;
            }
            for (int i = 0; i < dic_pic[selectpage].Count; i++)
            {
                dic_pic[selectpage][i].Width = picw[selectpage] * (1 + zoom[selectpage]);
                dic_pic[selectpage][i].Height = pich[selectpage] * (1 + zoom[selectpage]);
                dic_pic[selectpage][i].SetValue(Canvas.TopProperty, 5.0 + (i / displaynum) * (dic_pic[selectpage][i].Height + 10.0));
                dic_pic[selectpage][i].SetValue(Canvas.LeftProperty, 20.0 + (i % displaynum) * (dic_pic[selectpage][i].Width + 20.0));
                dic_pic[selectpage][i].SetValue(Canvas.RightProperty, double.NaN);
                dic_pic[selectpage][i].SetValue(Canvas.BottomProperty, double.NaN);
                canvas_height = Convert.ToInt32(10 + (i / displaynum) * (dic_pic[selectpage][i].Height + 10) + dic_pic[selectpage][i].Height);
            }
            (showpic.FindName("can" + selectpage) as Canvas).Height = canvas_height;
            this.showpic.Height = canvas_height;
        }
        #endregion

        #region 按下Ctrl键后不允许滚轮操作
        /// <summary>
        /// 按下Ctrl键后不允许滚轮操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.LeftCtrl || e.Key == Key.RightCtrl)
            {
                mousedown = true;
                svshowimg.VerticalScrollBarVisibility = ScrollBarVisibility.Disabled;
            }
        }
        #endregion

        #region 抬起Ctrl键后允许滚轮操作
        /// <summary>
        /// 抬起Ctrl键后允许滚轮操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_PreviewKeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.LeftCtrl || e.Key == Key.RightCtrl)
            {
                mousedown = false;
                svshowimg.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
            }
        }
        #endregion

        #region 拖动文件，这里暂时不做
        /// <summary>
        /// 拖动文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Drop(object sender, DragEventArgs e)
        {
            //try
            //{
            //    string dropfile = "";
            //    fns.Clear();
            //    if (e.Data.GetDataPresent(System.Windows.DataFormats.FileDrop))
            //    {
            //        int count = ((System.Array)e.Data.GetData(System.Windows.DataFormats.FileDrop)).Length;
            //        for (int i = 0; i < count; i++)
            //        {
            //            dropfile = ((System.Array)e.Data.GetData(System.Windows.DataFormats.FileDrop)).GetValue(i).ToString();
            //            if (System.IO.Path.GetExtension(dropfile) == ".jpg" || System.IO.Path.GetExtension(dropfile) == ".bmp")
            //            {
            //                //如果文件已经包含此文件则路过
            //                if(filenames.IndexOf(dropfile)>-1)
            //                {
            //                    continue;
            //                }
            //                fns.Add(dropfile);
            //            }
            //        }
            //        //如果添加图片数量大于0则启动线程
            //        if (fns.Count > 0)
            //        {
            //            Thread th = new Thread(display_img);
            //            th.Start();
            //        }
            //    }
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show("A handled exception just occurred: " + ex.Message, "Exception Sample", MessageBoxButton.OK, MessageBoxImage.Warning);
            //}
        }
        #endregion

        #region 线程加载图片
        /// <summary>
        /// 线程-->显示图像
        /// </summary>
        private void display_img()
        {
            for (int i = 0; i < fns.Count; i++)
            {
                //先将文件名取出放入filenames中
                page_filenames[selectpage].Add(fns[i]);
                //首先读取文件夹下是否存在AI文件夹
                string _filename = System.IO.Path.GetFileName(fns[i]);
                string aifilename = image_name[selectpage][6] + "\\AI\\" + _filename.Substring(0, _filename.Length - 4) + ".ai";
                //暂存信息
                string buff_json = "";
                string buff_title = "";
                string buff_zoom_key = "";
                string gradevalue = "";
                //如果AI文件存在，则读取参数信息
                if (System.IO.File.Exists(aifilename))
                {
                    using (System.IO.StreamReader _file = System.IO.File.OpenText(aifilename))
                    {
                        using (JsonTextReader reader = new JsonTextReader(_file))
                        {
                            JObject o = (JObject)JToken.ReadFrom(reader);
                            JObject content = JObject.Parse(o["content"].ToString());
                            JObject additional = JObject.Parse(content["additional"].ToString());
                            JObject details = JObject.Parse(content["details"].ToString());
                            if (details.Property("value") != null )
                            {
                                gradevalue = details["value"].ToString();
                            }

                            buff_json = o.ToString();
                            buff_title = content["title"].ToString();
                            buff_zoom_key = additional["zoom_key"].ToString() + "X";
                            reader.Close();
                            _file.Close();
                            _file.Dispose();
                        }
                    }
                }
                //取出对应图片显示
                this.Dispatcher.Invoke(new Action(() =>
                {
                    //如果图片字典中没有选中标签的信息，退出
                    if (!dic_pic.ContainsKey(selectpage))
                    {
                        return;
                    }
                    //加载图片数据
                    Picturebox pic = new Picturebox();
                    pic.img.Tag = i.ToString();
                    pic.btnanalysis.Tag = i.ToString();
                    pic.grade_value = gradevalue;
                    pic.img.PreviewMouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(clearbox);
                    pic.img.PreviewMouseRightButtonDown += new System.Windows.Input.MouseButtonEventHandler(clearbox);
                    //右键菜单
                    ContextMenu cm = new ContextMenu();
                    MenuItem Edit = new MenuItem();//菜单项 
                    Edit.Header = "全屏查看(F)";
                    Edit.Tag = i.ToString();
                    Edit.Click += new RoutedEventHandler(full_screen);
                    cm.Items.Add(Edit);
                    Edit = new MenuItem();//菜单项 
                    Edit.Header = "定位原图(L)";
                    Edit.Tag = i.ToString();
                    Edit.Click += new RoutedEventHandler(location_img);
                    cm.Items.Add(Edit);
                    pic.img.ContextMenu = cm;
                    pic.field.ContextMenu = cm;
                    pic.fieldr.ContextMenu = cm;

                    pic.btnanalysis.Click += new RoutedEventHandler(btnanalysis_Click);
                    pic.img.ToolTip = fns[i];
                    pic.Tag = buff_json;
                    //zm:修改界面显示为文件全名
                    //pic.lblpicmsg.Content = ((dic_pic[selectpage].Count + 1).ToString() + image_name[selectpage][4] + " " + buff_title + " " + buff_zoom_key).Trim();
                    pic.lblpicmsg.Content = (fns_name[i].ToString() + image_name[selectpage][4] + " " + buff_title + " " + buff_zoom_key).Trim();
            
                    //载入图像
                    Uri uri = new Uri(fns[i]);
                    BitmapImage bi = new BitmapImage();
                    bi.BeginInit();
                    bi.CacheOption = BitmapCacheOption.OnLoad;
                    bi.UriSource = uri;
                    bi.EndInit();
                    pic.img.Source = bi;

                    //计算缩放比
                    int iw = bi.PixelWidth;
                    int ih = bi.PixelHeight;
                    pic._PixelWidth = iw;
                    pic._PixelHeight = ih;
                    double vw = pic.img.Width;
                    double vh = pic.img.Height;
                    double propw = iw / vw;
                    double proph = ih / vh;
                    if(propw>proph)
                    {
                        pic.zoom_key = propw;
                        pic.rect_top = (vh - ih / propw) / 2;
                        pic.rect_left = 0;
                    }
                    else
                    {
                        pic.zoom_key = proph;
                        pic.rect_top = 0;
                        pic.rect_left = (vw - iw / proph) / 2;
                    }
                    
                    //检测是否有视场文件
                    String field = image_name[selectpage][6] + "\\AI\\";
                    field = field + System.IO.Path.GetFileNameWithoutExtension(fns[i]) + ".fld";
                    if (File.Exists(field))
                    {
                        StreamReader file = new StreamReader(field);
                        using (JsonTextReader reader = new JsonTextReader(file))
                        {
                            JObject o = (JObject)JToken.ReadFrom(reader);
                            JObject param = JObject.Parse(o["viewport"].ToString());
                            string c_r = param["type"].ToString();
                            if (c_r.ToString()=="C")
                            {
                                double r = Convert.ToDouble(param["w"].ToString()) / 2;
                                double x = Convert.ToDouble(param["x"].ToString()) + r;
                                double y = Convert.ToDouble(param["y"].ToString()) + r;
                                pic.circle.RadiusX = r / pic.zoom_key;
                                pic.circle.RadiusY = r / pic.zoom_key;
                                pic.circle.Center = new Point(x / pic.zoom_key + pic.rect_left, y / pic.zoom_key + pic.rect_top);
                                pic.field.Fill = new SolidColorBrush(Color.FromArgb(0x80, 0xFF, 0xFF, 0xFF));
                                pic.fieldr.Fill = new SolidColorBrush(Color.FromArgb(0x80, 0xFF, 0xFF, 0xFF));
                                pic.field.Visibility = Visibility.Visible;
                                pic.fieldr.Visibility = Visibility.Hidden;
                            }
                            else
                            {
                                double _left = Convert.ToDouble(param["x"].ToString());
                                double _top = Convert.ToDouble(param["y"].ToString());
                                double _width = Convert.ToDouble(param["w"].ToString());
                                double _height = Convert.ToDouble(param["h"].ToString());
                                pic.rectrr.Rect = new Rect(_left / pic.zoom_key + pic.rect_left, _top / pic.zoom_key + pic.rect_top, _width / pic.zoom_key, _height / pic.zoom_key);
                                pic.field.Fill = new SolidColorBrush(Color.FromArgb(0x80, 0xFF, 0xFF, 0xFF));
                                pic.fieldr.Fill = new SolidColorBrush(Color.FromArgb(0x80, 0xFF, 0xFF, 0xFF));
                                pic.field.Visibility = Visibility.Hidden;
                                pic.fieldr.Visibility = Visibility.Visible;
                            }
                            
                            reader.Close();
                            file.Close();
                            file.Dispose();
                        }
                        pic.Frozen = true;
                    }
                    
                    //取第一张图的长和宽做为基础缩放
                    if (dic_pic[selectpage].Count == 0)
                    {
                        pich.Add(selectpage, pic.Height);
                        picw.Add(selectpage, pic.Width);
                    }
                    else
                    {
                        pic.Height = pich[selectpage] * (1 + zoom[selectpage]);
                        pic.Width = picw[selectpage] * (1 + zoom[selectpage]);
                    }
                    //查看是否有ai文件参数，没有则将按钮隐藏
                    if (buff_title == "")
                    {
                        pic.btnanalysis.Visibility = Visibility.Hidden;
                    }
                    else
                    {
                        pic.btnanalysis.Visibility = Visibility.Visible;
                    }
                    //取一行能放多少张图片
                    int displaynum = Convert.ToInt32(Math.Floor(this.showpic.Width / (picw[selectpage] * (1 + zoom[selectpage]) + 20)));
                    pic.SetValue(Canvas.TopProperty, 5.0 + (dic_pic[selectpage].Count / displaynum) * (pich[selectpage] * (1 + zoom[selectpage]) + 10.0));
                    pic.SetValue(Canvas.LeftProperty, 20.0 + (dic_pic[selectpage].Count % displaynum) * (picw[selectpage] * (1 + zoom[selectpage]) + 20.0));
                    pic.SetValue(Canvas.RightProperty, double.NaN);
                    pic.SetValue(Canvas.BottomProperty, double.NaN);

                    canvas_height = Convert.ToInt32(10 + (dic_pic[selectpage].Count / displaynum) * (pich[selectpage] * (1 + zoom[selectpage]) + 10) + pich[selectpage] * (1 + zoom[selectpage]));

                    dic_pic[selectpage].Add(pic);
                    (showpic.FindName("can" + selectpage) as Canvas).Children.Add(pic);
                    this.subtitle.lblfilecount.Content = (i+1) +"/"+ fns.Count.ToString() + "个文件";//有一个文件图片更新一个

                }));
            }

            //加载完图片后操作
            this.showpic.Dispatcher.Invoke(new Action(() => {
                (showpic.FindName("can" + selectpage) as Canvas).Height = canvas_height;
                this.showpic.Height = canvas_height;
                this.subtitle.lblzoom.Visibility = Visibility.Visible;
                this.subtitle.sldzoom.Visibility = Visibility.Visible;
                this.subtitle.lblpercentge.Visibility = Visibility.Visible;
                this.subtitle.sldzoom.Value = 1 + zoom[selectpage];
                this.subtitle.lblfilecount.Visibility = Visibility.Visible;
                //更新文件数
                this.subtitle.lblfilecount.Content = page_filenames[selectpage].Count.ToString() + "个文件";

                //让滚动条滚动到顶部
                //this.svshowimg.ScrollToVerticalOffset(0);
                this.svshowimg.ScrollToVerticalOffset(Convert.ToDouble(image_name[selectpage][10]));
                cantab.IsEnabled = true;
                //关闭按钮可用
                pagetitle.isclosed = true;
                //启用所有标签页
                Header_Opacity_ChangeBright();
            }));
        }
        #endregion

        #region 滚轮变化
        /// <summary>
        /// 滚轮滚动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ScrollViewer_Changed(object sender, ScrollChangedEventArgs e)
        {
            if (svshowimg.CanContentScroll == true)
            {
                if (selectpage != "首页"&&listpage.Count>0)
                {
                    image_name[selectpage][10] = e.VerticalOffset.ToString();
                }     
            }
        }
        #endregion

        #region 图像右键全屏
        /// <summary>
        /// 图像右键全屏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void full_screen(object sender, RoutedEventArgs e)
        {
            int index = Convert.ToInt32(((MenuItem)sender).Tag);
            open_full_screen_window(index, 0);
        }
        #endregion

        #region 调用全屏并传参
        /// <summary>
        /// 调用全屏并传参
        /// </summary>
        /// <param name="index"></param>
        /// <param name="analysis"></param>
        private void open_full_screen_window(int index, int analysis)
        {
            Full_Screen_View ff = new Full_Screen_View();
            ff.Owner = this;
            ff.ShowInTaskbar = false;

            ff.selectindex = index;
            for (int i = 0; i < dic_pic[selectpage].Count; i++)
            {
                ff.ImgAnalysisList.Add(dic_pic[selectpage][i].lblpicmsg.Content.ToString());
            }
            ff.imglist.Add("imgList", page_filenames[selectpage]);
            ff.feild_change = new Boolean[page_filenames[selectpage].Count];
            ff.ProcessOrInitial = analysis;
            ff.ProcessFileName = "AI";

            ff.ShowDialog();

            full_return_index = ff.cureent;

            for (int m = 0; m < dic_pic[selectpage].Count; m++)
            {
                dic_pic[selectpage][m].box.Visibility = Visibility.Hidden;
                dic_pic[selectpage][m].st = false;

                //如果视场更改则重新加载
                //if(ff.feild_change[m])
                //{
                //    ////计算缩放比
                //    //double iw = dic_pic[selectpage][m]._PixelWidth;
                //    //double ih = dic_pic[selectpage][m]._PixelHeight;
                //    //double vw = dic_pic[selectpage][m].img.Width;
                //    //double vh = dic_pic[selectpage][m].img.Height;
                //    //double propw = iw / vw;
                //    //double proph = ih / vh;
                //    //if (propw > proph)
                //    //{
                //    //    dic_pic[selectpage][m].zoom_key = propw;
                //    //    dic_pic[selectpage][m].rect_top = (vh - ih / propw) / 2;
                //    //    dic_pic[selectpage][m].rect_left = 0;
                //    //}
                //    //else
                //    //{
                //    //    pic.zoom_key = proph;
                //    //    pic.rect_top = 0;
                //    //    pic.rect_left = (vw - iw / proph) / 2;
                //    //}
                //    String field = image_name[selectpage][6] + "\\AI\\";
                //    field = field + System.IO.Path.GetFileNameWithoutExtension(page_filenames[selectpage][m]) + ".fld";
                //    StreamReader file = new StreamReader(field);
                //    using (JsonTextReader reader = new JsonTextReader(file))
                //    {
                //        JObject o = (JObject)JToken.ReadFrom(reader);
                //        JToken c_r = o["Circle_Rect"];
                //        if (c_r.ToString() == "Circle")
                //        {
                //            JObject circle = JObject.Parse(o["Circle"].ToString());
                //            double r = Convert.ToDouble(circle["Radius"].ToString());
                //            double x = Convert.ToDouble(circle["Center_X"].ToString());
                //            double y = Convert.ToDouble(circle["Center_Y"].ToString());
                //            dic_pic[selectpage][m].circle.RadiusX = r / dic_pic[selectpage][m].zoom_key;
                //            dic_pic[selectpage][m].circle.RadiusY = r / dic_pic[selectpage][m].zoom_key;
                //            dic_pic[selectpage][m].circle.Center = new Point(x / dic_pic[selectpage][m].zoom_key + dic_pic[selectpage][m].rect_left, y / dic_pic[selectpage][m].zoom_key + dic_pic[selectpage][m].rect_top);
                //            dic_pic[selectpage][m].field.Visibility = Visibility.Visible;
                //            dic_pic[selectpage][m].fieldr.Visibility = Visibility.Hidden;
                //        }
                //        else
                //        {
                //            JObject recta = JObject.Parse(o["Rectangle"].ToString());
                //            double _left = Convert.ToDouble(recta["Left"].ToString());
                //            double _top = Convert.ToDouble(recta["Top"].ToString());
                //            double _width = Convert.ToDouble(recta["Width"].ToString());
                //            double _height = Convert.ToDouble(recta["Height"].ToString());
                //            dic_pic[selectpage][m].rectrr.Rect = new Rect(_left / dic_pic[selectpage][m].zoom_key + dic_pic[selectpage][m].rect_left, _top / dic_pic[selectpage][m].zoom_key + dic_pic[selectpage][m].rect_top, _width / dic_pic[selectpage][m].zoom_key, _height / dic_pic[selectpage][m].zoom_key);
                //            dic_pic[selectpage][m].field.Visibility = Visibility.Hidden;
                //            dic_pic[selectpage][m].fieldr.Visibility = Visibility.Visible;
                //        }

                //        reader.Close();
                //        file.Close();
                //        file.Dispose();
                //    }
                //}
            }
            dic_pic[selectpage][full_return_index].box.Visibility = Visibility.Visible;
            dic_pic[selectpage][full_return_index].st = true;

            // 获取要定位之前 ScrollViewer 目前的滚动位置
            var currentScrollPosition = svshowimg.VerticalOffset;
            var point = new Point(0, currentScrollPosition);

            // 计算出目标位置并滚动
            var targetPosition = dic_pic[selectpage][full_return_index].TransformToVisual(svshowimg).Transform(point);
            svshowimg.ScrollToVerticalOffset(targetPosition.Y);
        }
        #endregion

        #region 图像定位
        /// <summary>
        /// 图像定位：打开文件夹并选择指定文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void location_img(object sender, RoutedEventArgs e)
        {   
            int index = Convert.ToInt32(((MenuItem)sender).Tag);
            Common.locateFile(page_filenames[selectpage][index]);
        }
        #endregion

        #region 定位原图
        /// <summary>
        /// 定位原图
        /// </summary>
        /// <param name="fileFullName"></param>
        public void OpenFolderAndSelectFile(String fileFullName)
        {
            System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("Explorer.exe");
            psi.Arguments = "/e,/select," + fileFullName; 
            System.Diagnostics.Process.Start(psi);
        }
        #endregion

        #region 输出日志
        /// <summary>
        /// 输出日志
        /// </summary>
        /// <param name="strLog"></param>
        public static void WriteLog(string strLog)
        {
            string sFilePath = Directory.GetCurrentDirectory() + DateTime.Now.ToString("yyyyMM");
            string sFileName = "rizhi" + DateTime.Now.ToString("dd") + ".log";
            sFileName = sFilePath + "\\" + sFileName; //文件的绝对路径
            if (!Directory.Exists(sFilePath))//验证路径是否存在
            {
                Directory.CreateDirectory(sFilePath);
                //不存在则创建
            }
            FileStream fs;
            StreamWriter sw;
            if (File.Exists(sFileName))
            //验证文件是否存在，有则追加，无则创建
            {
                fs = new FileStream(sFileName, FileMode.Append, FileAccess.Write);
            }
            else
            {
                fs = new FileStream(sFileName, FileMode.Create, FileAccess.Write);
            }
            sw = new StreamWriter(fs);
            sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + "   ---   " + strLog);
            sw.Close();
            fs.Close();
        }
        #endregion

        #region 关闭完成弹出窗体
        /// <summary>
        /// 关闭完成弹出窗体（UserControl）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void completetest_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.CompleteTestWindow.Visibility = Visibility.Hidden;
        }
        #endregion

        #region 选中首页
        /// <summary>
        /// 选中首页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lblhomepage_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if(gc!=null)
            {
                gc.WindowState = WindowState.Normal;
                gc.Top = (this.Height - gc.Height) / 2;
                gc.Left = (this.Width - gc.Width) / 2;
                gc.Activate();
                return;
            }
            if (selectpage == "首页")
            {
                return;
            }

            //更新首页显示信息
            this.pagefirst.update_pagefirst_show(image_name[selectpage][0], image_name[selectpage][1], image_name[selectpage][2]);
            screen_label(image_name[selectpage][2]);

            //将其他页显示恢复
            foreach (KeyValuePair<string, PageControl> keyvalue in listpage)
            {
                keyvalue.Value.lblhomepage.Foreground = new SolidColorBrush(Color.FromRgb(0xAA, 0xAA, 0xAA));
                keyvalue.Value.pagegird.Background = new SolidColorBrush(Color.FromRgb(0x43, 0x4e, 0x61));
            }
            //首页被选中显示
            lblhomepage.Foreground = new SolidColorBrush(Color.FromRgb(0xF5, 0x9A, 0x23));
            lblhomepage.Background = new SolidColorBrush(Color.FromRgb(0x18, 0x25, 0x3C));
            //隐藏首页显示图像加载页
            pagefirst.Visibility = Visibility.Visible;
            svshowimg.Visibility = Visibility.Hidden;

            this.subtitle.lblfilecount.Content = "欢迎使用AIRS系统！选择检测项目";
            this.subtitle.lblzoom.Visibility = Visibility.Hidden;
            this.subtitle.sldzoom.Visibility = Visibility.Hidden;
            this.subtitle.lblpercentge.Visibility = Visibility.Hidden;

            selectpage = "首页";

            homepage_disabled();
        }
        #endregion

        #region 切换账号

        /// <summary>
        /// 切换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lblchange_cut(object sender, MouseButtonEventArgs e)
        {
            this.root.Children.Add(layer);
            LoginWindow lw = new LoginWindow();
            lw.BtnLogin.Content = "切换";
            lw.Owner = this;
            lw.ShowInTaskbar = false;
            lw.ShowDialog();
            //DialogHelper.ShowDialog(lw);
            if (lw.DialogResult == false)
            {
                //Application.Current.Shutdown();
                lw.Close();
                func();
                return;
            }
            lname = lw.loginname;
            password = lw.password;
            //this.pagetitle.lbltestp.Content = lname.Length == 0 ? "匿名" : lname;
            //this.pagetitle.lblcompound.Content = lw.entryclerk.Length == 0 ? "匿名" : lw.entryclerk;
            //entryclerk = lw.entryclerk;
            func();
            SetAuth();
        }
        #endregion


        #region 生成报告单击事件
        /// <summary>
        /// 生成报告单击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void out_report(object sender, MouseButtonEventArgs e)
        {
            this.root.Children.Add(layer);//蒙版
            HistoryGrade hitory = new HistoryGrade(1);
            hitory.Owner = this;

            hitory.pbw.Checked_Project.Content = image_name[selectpage][3];//检测项目
            hitory.pbw.basis.Content = "";//主要依据，主要标准，技术文件
            hitory.pbw.equipment.Content = "";//设备
            hitory.ShowDialog();
            //image_name.Add(pagename, new List<string>());
            //image_name[pagename].Add(sample.grade_steel);                   //0:钢种
            //image_name[pagename].Add(sample.grade_standard);                //1：标准          
            //image_name[pagename].Add(sample.test_item);                     //2：检测项目
            //image_name[pagename].Add(sample.comb_Number_prefix);            //3：样品名称
            //image_name[pagename].Add(sample.comb_Number_suffix);            //4：后缀
            //image_name[pagename].Add(sample.comb_Inspection_instrument);    //5：检测仪器
            //image_name[pagename].Add(sample.txt_Picture_catalog);           //6：文件夹
            //image_name[pagename].Add(this.pagefirst.catagory);              //7：钢种catagory参数
            //image_name[pagename].Add(this.pagefirst.items);                 //8：检测项目参数
            //image_name[pagename].Add(this.pagefirst.testitems_param);       //9: param 数据库{'YBG-W': {'w_cls':'wa'}}
            //image_name[pagename].Add(ScrollPositionNum);                    //10:记录每个页面滚动条位置初始为0

            hitory.Close();//关闭窗体

            func();//关闭蒙版
        } 
        #endregion

        #region 历史评级单击事件
        /// <summary>
        /// 历史评级单击事件
        /// </summary>
        private void history_down(object sender, MouseButtonEventArgs e)
        {
            this.root.Children.Add(layer);//蒙版
            HistoryGrade hitory = new HistoryGrade(0);
            hitory.Owner = this;
            hitory.ShowDialog();

            hitory.Close();//关闭窗体

            func();//关闭蒙版

        } 
        #endregion

        #region 修改密码

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lblmdfpwd_uppassword(object sender, MouseButtonEventArgs e)
        {

            this.root.Children.Add(layer);
            SetPwdWindow pwd = new SetPwdWindow();
            pwd.password = password;
            pwd.username = lname;
            pwd.Owner = this;
            pwd.ShowDialog();
            if (pwd.DialogResult == true)
            {
                func();
                MessageBox.Show("修改密码成功!");
                return;
            }
            func();
        }
        #endregion

        #region 标签切换时，更改标题栏内按钮状态
        /// <summary>
        /// 选择首页时上方按钮不可用
        /// </summary>
        private void homepage_disabled()
        {
            if (selectpage == "首页")
            {
                Header_Opacity_All_ChangeDark();
            }
            else
            {
                if(grade_state)
                {
                    Header_Opacity_ChangeDark();
                }
                else
                {
                    Header_Opacity_ChangeBright();
                }
            }
        }
        #endregion

        #region 窗体加载完成后执行事件
        /// <summary>
        /// 窗体加载完成后执行事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_ContentRendered(object sender, EventArgs e)
        {
            LoginWindow lw = new LoginWindow();
            lw.Owner = this;
            lw.ShowInTaskbar = false;
            lw.ShowDialog();
            //DialogHelper.ShowDialog(lw);
            if (lw.DialogResult == false)
            {
                Application.Current.Shutdown();
            }

            lname = lw.loginname;
            password = lw.password;
            //entryclerk = lw.entryclerk;
            //this.pagetitle.lbltestp.Content = lname;
            //this.pagetitle.lblcompound.Content = lw.entryclerk;

            //this.pagetitle.lbltestp.Content = lname.Length == 0 ? "匿名" : lname;
            //this.pagetitle.lblcompound.Content = lw.entryclerk.Length == 0 ? "匿名" : lw.entryclerk;
            SetAuth();
            //if (lname.Equals("admin"))
            //{
            //    //管理员
            //    this.Hide();
            //    AdminWindow am = new AdminWindow();
            //    am.Owner = this;
            //    am.Show();
            //}
        }
        #endregion

        /// <summary>
        /// 设置 用户/管理员 所属页面
        /// </summary>
        private void SetAuth()
        {
            if (lname.Equals("admin"))
            {
                //管理员
                this.pagefirst.Visibility = Visibility.Hidden;
                this.pageuser.Visibility = Visibility.Visible;
                this.lblhomepage.Content = "用户信息";
                this.pagetitle.task.Visibility = Visibility.Hidden;
                this.pagetitle.start_grade.Visibility = Visibility.Hidden;
                //this.pagetitle.field.Visibility = Visibility.Hidden;
                //this.pagetitle.canfill.Visibility = Visibility.Hidden;
                this.pagetitle.history.Visibility = Visibility.Hidden;
                //this.pagetitle.out_export.Visibility = Visibility.Hidden;
                this.pagetitle.cangradesum.Visibility = Visibility.Hidden;
            }
            else
            {
                //普通人员
                this.pagefirst.Visibility = Visibility.Visible;
                this.pageuser.Visibility = Visibility.Hidden;
                this.lblhomepage.Content = "任务";
                this.pagetitle.task.Visibility = Visibility.Visible;
                this.pagetitle.start_grade.Visibility = Visibility.Visible;
                //this.pagetitle.field.Visibility = Visibility.Visible;
                //this.pagetitle.canfill.Visibility = Visibility.Visible;
                this.pagetitle.history.Visibility = Visibility.Visible;
                //this.pagetitle.out_export.Visibility = Visibility.Visible;
                this.pagetitle.cangradesum.Visibility = Visibility.Visible;
            }
        }

        #region 评级检测，返回结果 
        /// <summary>
        /// 回调接收参数，参数固定
        /// </summary>
        /// <param name="o">回调返回结果</param>
        private void ReceivedControlData(object o)
        {
 
            try
            {
                if (o != null)
                {
                    ControlData controlData = o as ControlData;
                    
                    if (controlData != null)
                    {
                        //下面示例需要重写，需要定制化，
                        //控件是调用时传入的
                        if (controlData.Control is Label)//是label,在label上显示
                        {
                            Label lbl = controlData.Control as Label;
                            //lbl.Content += controlData.DataString + Environment.NewLine;
                            switch (controlData.CallbackDataType)
                            {
                                //返回数据是执行的脚本指定
                                case CallbackDataType.Command:
                                    //txt.Text += "Command:" + controlData.DataString + Environment.NewLine;
                                    //txt.ScrollToEnd();
                                    break;
                                //返回数据是参数调用接口错误
                                case CallbackDataType.ParameterError:
                                    //txt.Text += controlData.DataString + Environment.NewLine;
                                    //txt.ScrollToEnd();
                                    test_index++;
                                    if (test_index == page_filenames[grade_selectpage].Count)
                                    {
                                        //pagetitle.IsEnabled = true;
                                        //评级状态
                                        grade_state = false;
                                        
                                        pagetitle.start_grade.IsEnabled = true;
              
                                        //this.cantab.IsEnabled = true;
                                        this.pbw.Visibility = Visibility.Hidden;
                                        Log.Info("发生错误隐藏进度条");
                                        //评级结束，将数据写入表中
                                        conn = new SQLiteConnection();
                                        connstr = new SQLiteConnectionStringBuilder();
                                        connstr.DataSource = path + "\\datas.db";
                                        conn.ConnectionString = connstr.ToString();
                                        conn.Open();

                                        SQLiteCommand cmd = conn.CreateCommand();
                                        cmd.CommandText = "insert into t_grade values('" + System.DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "','" +
                                            image_name[grade_selectpage][2] + "','" + image_name[grade_selectpage][8] + "','" + image_name[grade_selectpage][0] + "','" +
                                            image_name[grade_selectpage][7] + "','" + image_name[grade_selectpage][1] + "','" + image_name[grade_selectpage][5] +
                                            "','" + image_name[grade_selectpage][3] + " " + image_name[grade_selectpage][4] + "','" + image_name[grade_selectpage][6] + "','','','" +
                                            page_filenames[grade_selectpage].Count.ToString() + "','" + test_index.ToString() + "','0','','')";
                                        cmd.ExecuteNonQuery();
                                        conn.Close();
                                        conn.Dispose();

                                    }
                                    break;
                                //返回是数据是最终想要的结果
                                case CallbackDataType.ReturnData:
                                    test_index++;
                                    Log.Info("开始接收数据");
                                    JObject jsonObj = null;
                                    jsonObj = JObject.Parse(controlData.DataString);
                                    JObject content = JObject.Parse(jsonObj["content"].ToString());
                                    JObject additional = JObject.Parse(content["additional"].ToString());
                                    JObject details = JObject.Parse(content["details"].ToString());
                                    if (details.Property("value") != null && details.Property("value").ToString() != "")
                                    {
                                        dic_pic[grade_selectpage][controlData.Index].grade_value = details["value"].ToString();
                                    }
                                    //增加前缀和后缀
                                    jsonObj.Add("prefix", image_name[grade_selectpage][3]);
                                    jsonObj.Add("suffix", image_name[grade_selectpage][4]);
                                    Log.Info("写入结果开始：");
                                    Log.Info("文件名：" + System.IO.Path.GetFileName(page_filenames[grade_selectpage][controlData.Index]));//计入日志返回整个结果
                                    Log.Info("返回结果为：" + jsonObj.ToString());//计入日志返回整个结果
                                    Log.Info("写入结果结束");

                                    //test_index++;
                                    //返回文件路径
                                    string rename_fullname = "";
                                    if (additional["image_path"] != null && additional["image_path"].ToString() != "")
                                    {
                                        Log.Info("写入image_path开始：");
                                        Log.Info("文件名： " + System.IO.Path.GetFileName(page_filenames[grade_selectpage][controlData.Index]));//计入日志返回结果图片路径+名称

                                        rename_fullname = additional["image_path"].ToString();
                                        Log.Info("image_path为： " + additional["image_path"].ToString());//计入日志返回结果图片路径+名称
                                        Log.Info("写入image_path结束");
                                        //返回文件路径
                                        // string rename_fullname = additional["image_path"].ToString();
                                        //当前文件名称
                                        //string filename = System.IO.Path.GetFileName(page_filenames[grade_selectpage][test_index]);
                                        string filename = System.IO.Path.GetFileName(page_filenames[grade_selectpage][controlData.Index]);

                                        //写入文件路径
                                        string pathname = image_name[grade_selectpage][6] + "\\AI\\";
                                        Log.Info("移动文件开始： ");
                                        if (!System.IO.Directory.Exists(pathname))
                                        {
                                            System.IO.Directory.CreateDirectory(pathname);
                                        }
                                        Log.Info("文件名： " + filename);
                                        //先移动文件再删除
                                        if (System.IO.File.Exists(rename_fullname))
                                        {
                                            Log.Info("文件将从： " + rename_fullname + "移动到： " + pathname + filename);
                                            System.IO.File.Copy(rename_fullname, pathname + filename, true);
                                            Log.Info("移动完成。 文件从： " + rename_fullname + " 移动到了： " + pathname + filename);
                                            Log.Info("将要删除： " + rename_fullname + "文件");
                                            System.IO.File.Delete(rename_fullname);
                                            Log.Info("删除完成： " + rename_fullname + "文件");
                                            Log.Info("移动文件结束 ");
                                        }
                                        //将JSON串的文件路径更改
                                        additional["image_path"] = pathname + filename;
                                        content["additional"] = additional;
                                        jsonObj["content"] = content;
                                        //写文件
                                        Log.Info("生成AI文件即将开始：");
                                        Log.Info("文件名: " + filename);
                                        filename = pathname + filename;

                                        filename = filename.Substring(0, filename.Length - 4) + ".ai";

                                        Log.Info("马上开始生成AI文件");
                                        using (System.IO.StreamWriter file = new System.IO.StreamWriter(filename, false))
                                        {
                                            Log.Info("生成的AI文件为： " + filename);
                                            Log.Info("开始向AI文件写入数据");
                                            Log.Info("正在向AI文件写入结果数据，AI文件路径与名称为： " + filename);
                                            file.WriteLine(jsonObj.ToString());// 直接追加文件末尾，换行 
                                            file.Close();
                                            Log.Info("向AI文件写入了： " + jsonObj.ToString());
                                            Log.Info("AI文件写入结束");
                                        }


                                        ///  dic_pic[grade_selectpage][test_index].Tag
                                        dic_pic[grade_selectpage][controlData.Index].Tag = jsonObj.ToString();
                                        dic_pic[grade_selectpage][controlData.Index].btnanalysis.Visibility = Visibility.Visible;//显示分析过程字样

                                        dic_pic[grade_selectpage][controlData.Index].field.Fill = new SolidColorBrush(Color.FromArgb(0x80, 0xFF, 0xFF, 0xFF));
                                        dic_pic[grade_selectpage][controlData.Index].fieldr.Fill = new SolidColorBrush(Color.FromArgb(0x80, 0xFF, 0xFF, 0xFF));

                                        dic_pic[grade_selectpage][controlData.Index].Frozen = true;


                                        //未识别的隐藏显示改为未识别参考下面的东西
                                        //  dic_pic[grade_selectpage][controlData.Index].btnanalysis.Visibility = Visibility.Hidden;

                                        //dic_pic[grade_selectpage][test_index].lblpicmsg.Content= dic_pic[grade_selectpage][test_index].lblpicmsg.Content.ToString()+" " + content["title"] + " " + additional["zoom_key"];

                                        //zm:修改界面显示，显示为文件名称
                                        //显示标题与放大倍数
                                        if (additional["zoom_key"].ToString() == "" || additional["zoom_key"] == null)
                                        {
                                            dic_pic[grade_selectpage][controlData.Index].lblpicmsg.Content = System.IO.Path.GetFileName(page_filenames[grade_selectpage][controlData.Index]) +
                                            " " + content["title"] + " " + additional["zoom_key"];
                                            //dic_pic[grade_selectpage][controlData.Index].lblpicmsg.Content = (controlData.Index + 1).ToString() + image_name[grade_selectpage][4] +
                                            //" " + content["title"] + " " + additional["zoom_key"];
                                        }
                                        else
                                        {
                                            dic_pic[grade_selectpage][controlData.Index].lblpicmsg.Content = System.IO.Path.GetFileName(page_filenames[grade_selectpage][controlData.Index]) +
                                            " " + content["title"] + " " + additional["zoom_key"] + "X";

                                            //dic_pic[grade_selectpage][controlData.Index].lblpicmsg.Content = (controlData.Index + 1).ToString() + image_name[grade_selectpage][4] +
                                            //" " + content["title"] + " " + additional["zoom_key"] + "X";
                                        }
                                        


                                        #region 添加或修改数据库  
                                        //写入数据库
                                        if (test_index == page_filenames[grade_selectpage].Count)
                                        {
                                            if (GetDatByPath(image_name[grade_selectpage][4]) > 0)
                                            {
                                                //修改数据
                                                Log.Info("更新数据库开始");
                                                //pagetitle.IsEnabled = true;//标题
                                                //this.cantab.IsEnabled = true;//菜单选项卡
                                                //this.pbw.Visibility = Visibility.Hidden; //进度隐藏
                                                grade_state = false;
                                                pagetitle.start_grade.IsEnabled = true;
                                                //评级结束，将数据写入表中
                                                conn = new SQLiteConnection();
                                                connstr = new SQLiteConnectionStringBuilder();
                                                connstr.DataSource = path + "\\datas.db";
                                                conn.ConnectionString = connstr.ToString();
                                                conn.Open();
                                                Log.Info("未向数据库更新时数据为");
                                                Log.Info("评级时间：--");
                                                Log.Info("评级项目：" + image_name[grade_selectpage][2]);
                                                Log.Info("items：" + image_name[grade_selectpage][8]);
                                                Log.Info("钢种：" + image_name[grade_selectpage][0]);
                                                Log.Info("catagory：" + image_name[grade_selectpage][7]);
                                                Log.Info("评级标准：" + image_name[grade_selectpage][1]);
                                                Log.Info("检测仪器：" + image_name[grade_selectpage][5]);
                                                Log.Info("编号规则：" + image_name[grade_selectpage][3] + " " + image_name[grade_selectpage][4]);
                                                Log.Info("图像目录：" + image_name[grade_selectpage][6]);
                                                Log.Info("操作员：--");
                                                Log.Info("复核员：--");
                                                Log.Info("图像数量：" + page_filenames[grade_selectpage].Count.ToString());
                                                Log.Info("完成数量：" + test_index.ToString());
                                                Log.Info("生成报告状态：--");
                                                Log.Info("生成报告时间：--");
                                                Log.Info("生成报告人：--");


                                                SQLiteCommand cmd = conn.CreateCommand();

                                                cmd.CommandText = "UPDATE t_grade SET \"评级时间\"='"+ DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") +"' " +
                                                    ", \"评级项目\"='"+ image_name[grade_selectpage][2] + "' , items = '"+ image_name[grade_selectpage][8] + "', \"钢种\" = '"+ image_name[grade_selectpage][0] + "'" +
                                                    ", catagory = '"+ image_name[grade_selectpage][7] + "' , \"评级标准\" = '"+ image_name[grade_selectpage][1] + "' " +
                                                    ", \"检测仪器\"='"+ image_name[grade_selectpage][5] + "' , \"编号规则\" = '"+ image_name[grade_selectpage][3] + " " + image_name[grade_selectpage][4] + "' " +
                                                    ", \"操作员\"='' AND \"复合员\" = '' " +
                                                    ", \"图像数量\"='"+ page_filenames[grade_selectpage].Count.ToString() + "' , \"完成数量\" = '"+ test_index.ToString() + "' " +
                                                    ", \"生成报告状态\"='0' , \"生成报告时间\" = ''" +
                                                    " , \"生成报告人\" = '' WHERE \"图像目录\" = '"+image_name[grade_selectpage][6]+"'";
                                                cmd.ExecuteNonQuery();
                                                Log.Info("向数据库更新数据完成：");
                                                Log.Info("向数据库更新了以下数据：");

                                                Log.Info("未向数据库更新时数据为");
                                                Log.Info("评级时间：--");
                                                Log.Info("评级项目：" + image_name[grade_selectpage][2]);
                                                Log.Info("items：" + image_name[grade_selectpage][8]);
                                                Log.Info("钢种：" + image_name[grade_selectpage][0]);
                                                Log.Info("catagory：" + image_name[grade_selectpage][7]);
                                                Log.Info("评级标准：" + image_name[grade_selectpage][1]);
                                                Log.Info("检测仪器：" + image_name[grade_selectpage][5]);
                                                Log.Info("编号规则：" + image_name[grade_selectpage][3] + " " + image_name[grade_selectpage][4]);
                                                Log.Info("图像目录：" + image_name[grade_selectpage][6]);
                                                Log.Info("操作员：--");
                                                Log.Info("复核员：--");
                                                Log.Info("图像数量：" + page_filenames[grade_selectpage].Count.ToString());
                                                Log.Info("完成数量：" + test_index.ToString());
                                                Log.Info("生成报告状态：--");
                                                Log.Info("生成报告时间：--");
                                                Log.Info("生成报告人：--");
                                                conn.Close();
                                                conn.Dispose();
                                                Log.Info("更新数据库结束");
                                            }
                                            else
                                            {
                                                //添加数据
                                                Log.Info("写入数据库开始");
                                                //pagetitle.IsEnabled = true;//标题
                                                //this.cantab.IsEnabled = true;//菜单选项卡
                                                //this.pbw.Visibility = Visibility.Hidden; //进度隐藏
                                                grade_state = false;
                                                pagetitle.start_grade.IsEnabled = true;
                                                //评级结束，将数据写入表中
                                                conn = new SQLiteConnection();
                                                connstr = new SQLiteConnectionStringBuilder();
                                                connstr.DataSource = path + "\\datas.db";
                                                conn.ConnectionString = connstr.ToString();
                                                conn.Open();
                                                Log.Info("未向数据库插入时数据为");
                                                Log.Info("评级时间：--");
                                                Log.Info("评级项目：" + image_name[grade_selectpage][2]);
                                                Log.Info("items：" + image_name[grade_selectpage][8]);
                                                Log.Info("钢种：" + image_name[grade_selectpage][0]);
                                                Log.Info("catagory：" + image_name[grade_selectpage][7]);
                                                Log.Info("评级标准：" + image_name[grade_selectpage][1]);
                                                Log.Info("检测仪器：" + image_name[grade_selectpage][5]);
                                                Log.Info("编号规则：" + image_name[grade_selectpage][3] + " " + image_name[grade_selectpage][4]);
                                                Log.Info("图像目录：" + image_name[grade_selectpage][6]);
                                                Log.Info("操作员：--");
                                                Log.Info("复核员：--");
                                                Log.Info("图像数量：" + page_filenames[grade_selectpage].Count.ToString());
                                                Log.Info("完成数量：" + test_index.ToString());
                                                Log.Info("生成报告状态：--");
                                                Log.Info("生成报告时间：--");
                                                Log.Info("生成报告人：--");


                                                SQLiteCommand cmd = conn.CreateCommand();
                                                cmd.CommandText = "insert into t_grade values('" + System.DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "','" +
                                                    image_name[grade_selectpage][2] + "','" + image_name[grade_selectpage][8] + "','" + image_name[grade_selectpage][0] + "','" +
                                                    image_name[grade_selectpage][7] + "','" + image_name[grade_selectpage][1] + "','" + image_name[grade_selectpage][5] +
                                                    "','" + image_name[grade_selectpage][3] + " " + image_name[grade_selectpage][4] + "','" + image_name[grade_selectpage][6] + "','','','" +
                                                    page_filenames[grade_selectpage].Count.ToString() + "','" + test_index.ToString() + "','0','','')";
                                                cmd.ExecuteNonQuery();
                                                Log.Info("向数据库插入数据完成：");
                                                Log.Info("向数据库插入了以下数据：");

                                                Log.Info("未向数据库插入时数据为");
                                                Log.Info("评级时间：--");
                                                Log.Info("评级项目：" + image_name[grade_selectpage][2]);
                                                Log.Info("items：" + image_name[grade_selectpage][8]);
                                                Log.Info("钢种：" + image_name[grade_selectpage][0]);
                                                Log.Info("catagory：" + image_name[grade_selectpage][7]);
                                                Log.Info("评级标准：" + image_name[grade_selectpage][1]);
                                                Log.Info("检测仪器：" + image_name[grade_selectpage][5]);
                                                Log.Info("编号规则：" + image_name[grade_selectpage][3] + " " + image_name[grade_selectpage][4]);
                                                Log.Info("图像目录：" + image_name[grade_selectpage][6]);
                                                Log.Info("操作员：--");
                                                Log.Info("复核员：--");
                                                Log.Info("图像数量：" + page_filenames[grade_selectpage].Count.ToString());
                                                Log.Info("完成数量：" + test_index.ToString());
                                                Log.Info("生成报告状态：--");
                                                Log.Info("生成报告时间：--");
                                                Log.Info("生成报告人：--");

                                                conn.Close();
                                                conn.Dispose();
                                                Log.Info("写入数据库结束");
                                            }
                                        }
                                        #endregion
                                        dic_pic[grade_selectpage][controlData.Index].btnanalysis.Visibility = Visibility.Visible;//显示分析过程字样
                                        dic_pic[grade_selectpage][controlData.Index].btnanalysis.Content = "分析过程";
                                        dic_pic[grade_selectpage][controlData.Index].btnanalysis.IsEnabled = true;
                                        dic_pic[grade_selectpage][controlData.Index].btnanalysis.Background = new SolidColorBrush(Color.FromRgb(255, 165, 0));
                                    }
                                    else
                                    {
                                        dic_pic[grade_selectpage][controlData.Index].btnanalysis.Visibility = Visibility.Visible;//显示分析过程字样
                                        dic_pic[grade_selectpage][controlData.Index].btnanalysis.Content = "未能分析";
                                        dic_pic[grade_selectpage][controlData.Index].btnanalysis.IsEnabled = false;
                                        dic_pic[grade_selectpage][controlData.Index].btnanalysis.Background = new SolidColorBrush(Color.FromRgb(255, 165, 0));
                                    }

                                    Log.Info("接收数据次数test_index" + test_index + " 次");
                                    //进度，这是大进度条
                                    this.pbw.progbar.Value = test_index;//进度条的value
                                    double percent = (double)test_index / (double)page_filenames[grade_selectpage].Count;//算百分比
                                    this.pbw.progbar_num.Content = percent.ToString("P0");
                                    string shownum = test_index + "/" + page_filenames[grade_selectpage].Count;//(1000/1000)当前处理多少文件
                                    this.pbw.show_num.Content = shownum;
                                    //缩小后的进度条
                                    this.minpbw.minprogbar.Value = test_index;//进度条的value                              
                                    this.minpbw.minprogbar_num.Content = percent.ToString("P0");
                                    this.minpbw.minshow_num.Content = shownum;

                                    //如果接收结果与图片个数相同
                                    if (test_index == page_filenames[grade_selectpage].Count)
                                    { 
                                        this.cantab.IsEnabled = true;//菜单选项卡
                                        grade_state = false;
                                        Header_Opacity_ChangeBright();
                                        pagetitle.isclosed = true;
                                        this.pbw.Visibility = Visibility.Hidden;//进度隐藏
                                        this.minpbw.Visibility = Visibility.Hidden;//进度隐藏
                                        this.CompleteTestWindow.Visibility = Visibility.Visible;//显示完成对话框
                                        this.completetest.use_time.Content = TimeDiff(time_start_grade, Convert.ToDateTime(DateTime.Now));
                                        this.completetest.image_number.Content = page_filenames[grade_selectpage].Count + " 张图片检测完成";
                                    }
                                    Log.Info("接收数据结束。");
                                    break;
                                case CallbackDataType.Progress:
                                    string AI_progress = controlData.DataString; 
                                    //string[] sArray = AI_progress.Split(new char[1] { ':' });
                                    string str = AI_progress.Substring(AI_progress.LastIndexOf(":") + 1);
                                   
                                    if (page_filenames[grade_selectpage].Count - 1 ==Convert.ToInt32(str))
                                    {
                                       
                                        //评级停止，使评级状态置false
                                        grade_state = false;
                                        //允许关闭
                                        pagetitle.isclosed = true;
                                        //是否强制关闭当前检测
                                        isforced = false;
                                        //启用进度条取消按钮
                                        this.pbw.btncancle.IsEnabled = true;
                                        //正在进行AI检测，请稍候...
                                        this.pbw.progbar_msg.Content = "正在进行AI检测，请稍候...";
                                        //隐藏进度条
                                        this.pbw.Visibility = Visibility.Hidden;
                                        this.minpbw.Visibility = Visibility.Hidden;//进度隐藏
                                        this.ForcedCancelUC.Visibility = Visibility.Hidden;
                                        //标题按钮变亮
                                        Header_Opacity_ChangeBright();                  
                                    }
                                    break;
                                //其他就是info，是过程中的日志信息、ai调用内部错误信息等
                                default:
                                    //其他的中间过程日志信息先不显示
                                    break;
                            }
                        }

                        //if (controlData.Control is TextBox)//是textbox，在textbox上显示
                        //{
                        //    TextBox txt = controlData.Control as TextBox;
                        //    switch (controlData.CallbackDataType)
                        //    {
                        //        //返回数据是执行的脚本指定
                        //        case CallbackDataType.Command:
                        //            txt.Text += "Command:" + controlData.DataString + Environment.NewLine;
                        //            txt.ScrollToEnd();
                        //            break;
                        //        //返回数据是参数调用接口错误
                        //        case CallbackDataType.ParameterError:
                        //            txt.Text += controlData.DataString + Environment.NewLine;
                        //            txt.ScrollToEnd();
                        //            break;
                        //        //返回是数据是最终想要的结果
                        //        case CallbackDataType.ReturnData:
                        //            txt.Text += controlData.DataString + Environment.NewLine;
                        //            txt.ScrollToEnd();
                        //            break;
                        //        //其他就是info，是过程中的日志信息、ai调用内部错误信息等
                        //        default:
                        //            //其他的中间过程日志信息先不显示
                        //            break;
                        //    }
                        //}

                    }
                }
            }
            catch (Exception e)
            {
                Log.Info("出现错误！");
                Log.Info("出错信息为：" + e.Message);
                //System.Windows.MessageBox.Show(e.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {

                //try
                //{
                //    test_index++;
                //    ///应该是这
                //    this.pbw.progbar.Value = test_index;
                //    double percent = (double)test_index / (double)page_filenames[selectpage].Count;
                //    //ll后加的
                //    string shownum = "(" + test_index + "/" + page_filenames[selectpage].Count + ")";
                //    this.pbw.show_num.Content = shownum;
                //    this.pbw.progbar_num.Content = percent.ToString("P0");


                //}
                //catch (Exception ex)
                //{
                //    System.Windows.MessageBox.Show(ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                //}

            }

        }
        #endregion

        #region 根据图像目录查询数据
        /// <summary>
        /// 
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private int GetDatByPath(string strpath)
        {
            int count = 0;
            try
            {
                conn = new SQLiteConnection();
                connstr = new SQLiteConnectionStringBuilder();
                connstr.DataSource = path + "\\datas.db";
                conn.ConnectionString = connstr.ToString();
                conn.Open();
                SQLiteDataAdapter da = new SQLiteDataAdapter("SELECT count(*) AS count FROM t_grade WHERE \"图像目录\"='"+ strpath + "'", conn);
                DataTable ds = new DataTable();
                da.Fill(ds);
                count = Convert.ToInt32(ds.Rows[0][0]);
            }
            catch (Exception ex)
            {

            }
            finally
            {
                conn.Close();
                conn.Dispose();
            }
            return count;
        }
        #endregion

        #region 窗体移动
        /// <summary>
        /// 窗体移动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                this.DragMove();
            }
        }
        #endregion

        #region 屏蔽右键菜单右键弹出
        /// <summary>
        /// 屏蔽右键菜单右键弹出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Cmd_Initialized(object sender, EventArgs e)
        {
            this.cmd.ContextMenu = null;
        }
        #endregion

        #region 菜单选项卡 鼠标移除后发生
        /// <summary>
        /// 菜单选项卡 鼠标移除后发生
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuMouseLeave(object sender, MouseEventArgs e)
        {
            Uri uri = new Uri("img/down.png", UriKind.Relative);
            BitmapImage img = new BitmapImage(uri);
            img_menu.Source = img;
        }
        #endregion

        #region 菜单选项卡 鼠标移动发生
        /// <summary>
        /// 菜单选项卡 鼠标移动发生
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuMouseMove(object sender, MouseEventArgs e)
        {
            Uri uri = new Uri("img/down2.png", UriKind.Relative);
            BitmapImage img = new BitmapImage(uri);
            img_menu.Source = img;
        }
        #endregion

        #region 获取窗体宽度
        /// <summary>
        /// //获取窗体宽度
        /// </summary>
        /// <returns></returns>
        private int MainWindow_Width()
        {
            int width = 0;
            width = (int)(this.cantab.Width - (157 + 57)) / 142;
            //Console.WriteLine("窗体宽" + this.cantab.Width + " " + width.ToString());
            return width;
            //int width = 0;
            //width = (int)(this.Width - (157 + 57)) / 142;
            //Console.WriteLine("窗体宽"+ this.Width+" "+width.ToString());
            //return width;
        }
        #endregion

        #region 窗体变化获取大小
        /// <summary>
        /// 窗体变化获取大小
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainWindow_Resize(object sender, System.EventArgs e)
        {
             tab_num= MainWindow_Width(); 
        }
        #endregion

        private void pagetitle_Loaded()
        {

        }
    }
}
