using DrawGraph;
using DrawGraphManagement.MyUserControl;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
namespace DrawGraphManagement
{
    public partial class AreaManageForm : Form
    {
        PackObjBase bb = null;
        PackObjBase selectPoB = null;
        //string outFlat = "||";
        //string asFileName = "";
        private TreeNode selectNode = null; //选中的结点
        private PrintDocument pDoc;
        protected PackObjManager poManager = null;
        private AreaManageBase areaManage = null;
        public PageStatus pageStatus = PageStatus.Create;
        //private bool isAddNodeDown = true; //增加节点时是否是一层一层往下加,为真时是多层级的,为假是一层
        private int borderWidth = 600;
        private int borderHeight = 800;
        private bool isViewBackImg = true;
        public AreaManageForm()
        {
            InitializeComponent();
            poManager = new PackObjManager();
            btnOk.DialogResult = DialogResult.OK;
        }
        /// 
        /// 范围管理器构造方法
        /// 
        /// 范围管理器
        /// 默认使用自己的组件
        public AreaManageForm(AreaManageBase _areaMange, PageStatus _pageStatus = PageStatus.Create, int _borderWidth = 600, int _borderHeight = 800)
        {
            InitializeComponent();
            btnOk.DialogResult = DialogResult.OK;
            areaManage = _areaMange;
            poManager = areaManage.PackManage;
            pageStatus = _pageStatus;
            borderWidth = _borderWidth;
            borderHeight = _borderHeight;
            CommandManage.GetInstance.AreaManage = areaManage;
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            if (areaManage == null)
            {
                MessageBox.Show("区域管理器不能为空");
                return;
            }
            this.deleteMenuItem.Enabled = true;
            //需要放在最前面,他会清理画板
            ControlDatabind(false);
            //画板加载背景图片
            loadBackImage();
            AutoSizeF();
            if (pageStatus == PageStatus.Create)
            {
                bb = new BorderPackObj(zedGraphControl1, poManager); ;
                if (bb != null)
                {
                    ((BorderPackObj)bb).SetWidth = borderWidth;
                    ((BorderPackObj)bb).SetHeight = borderHeight;
                    poManager.ListPob.Add(bb);
                    InsertPackObjTree(bb);
                    bb.Changed += new PackObjBase.ChangedEventHandler(Bpo_Changed);
                }
                try
                {
                    pDoc = new PrintDocument();
                    pDoc.DefaultPageSettings.Landscape = true;
                    pDoc.OriginAtMargins = true;
                    pDoc.DefaultPageSettings.PrinterResolution.Kind = PrinterResolutionKind.High;
                    pDoc.DefaultPageSettings.Margins = new Margins(8, 8, 4, 4);
                    pDoc.PrintPage += new PrintPageEventHandler(pDoc_PrintPage);
                }
                catch (Exception  )
                {
                }
            }
            if (pageStatus == PageStatus.Edit)
            {
                foreach (PackObjBase pob in poManager.ListPob)
                {
                    if (pob is AbleEditPackObj)
                    {
                        AbleEditPackObj a = pob as AbleEditPackObj;
                        a.IsViewBoard = EIsBool.True;
                    }
                }
                ReLoad();
            }
            //areaManage.PackManage.ListPob.FindAll(s => s.PackTag.EndsWith("26".Replace('.', '_')))[0].Draw();
        }
        //画板加载背景图片
        private void loadBackImage()
        {
            if (isViewBackImg)
            {
                //加载北京图片
                Image img = null;
                try
                {
                    img = Image.FromFile(@"Resources/template/" + areaManage.Name + ".jpg");
                }
                catch (Exception  )
                {
                }
                if (img != null)
                {
                    zedGraphControl1.BackgroundImage = img;
                    zedGraphControl1.GraphPane.Fill.Color = Color.Transparent;
                    zedGraphControl1.MasterPane.Fill.IsVisible = false;
                    zedGraphControl1.GraphPane.Chart.Fill.IsVisible = false;
                }
            }
            else {
                zedGraphControl1.BackgroundImage = null;
            }
        }
        private void AutoSizeF()
        {
            #region 设置界面自适应
            //在此处可随时设置板子的属性,横向的
            //if (borderWidth > borderHeight)
            //{
            //    borderHeight = zedGraphControl1.Parent.Height - 54;
            //    borderWidth = Convert.ToInt32(borderHeight * 1.414) + 2;
            //}
            //else
            //{
            //    borderWidth = zedGraphControl1.Parent.Width - 54;
            //    borderHeight = Convert.ToInt32(borderWidth * 1.414) + 2;
            //}
            zedGraphControl1.Width = borderWidth;
            zedGraphControl1.Height = borderHeight;
            PackObjBase pack = poManager.ListPob.FirstOrDefault(s => s is BorderPackObj);
            if(pack != null) {
                ((BorderPackObj)pack).SetWidth = borderWidth;
                ((BorderPackObj)pack).SetHeight = borderHeight;
            }
            areaManage.setPrint(false);
            zedGraphControl1.Refresh();
            #endregion
        }
        /// 
        /// 修改指定树结点的包控件内容
        /// 
        private void ModPackObjTree(TreeNodeCollection tnc, PackObjBase pob)
        {
            if (selectPoB == null) return;
            foreach (TreeNode tn in tnc)
            {
                try {
                    if (tn.Name == pob.PackName)
                    {
                        tn.Name = pob.PackName;
                        tn.Tag = pob;
                        tn.Text = pob.Descript;
                        break;
                    }
                    else if (tn.Nodes.Count > 0)
                    {
                        ModPackObjTree(tn.Nodes, pob);
                    }
                } catch (Exception  ) { 
                }
            }
        }
        /// 
        /// 插入指定树结点的包控件内容
        /// 
        /// 
        private void InsertPackObjTree(PackObjBase pob, bool isSelMySelft = true)
        {
            TreeNode tnSub = new TreeNode();
            pob.IsSelect = false;
            tnSub.Name = pob.PackName;
            tnSub.Tag = pob;
            tnSub.Text = pob.Descript;
            if (treeView1.SelectedNode == null)
            {
                //如果是白板对象直接加在顶层
                if (pob is BorderPackObj)
                {
                    treeView1.Nodes.Add(tnSub);
                    pob.SetParent = null;
                }
                else {
                    treeView1.SelectedNode = treeView1.Nodes[0];
                    treeView1.SelectedNode.Nodes.Add(tnSub);
                    PackObjBase ppob = (PackObjBase)treeView1.SelectedNode.Tag;
                    if (ppob != null) pob.SetParent = ppob;
                }
            }
            else
            {
                treeView1.SelectedNode.Nodes.Add(tnSub);
                PackObjBase ppob = (PackObjBase)treeView1.SelectedNode.Tag;
                if (ppob != null) pob.SetParent = ppob;
            }
            //只有在多层级时才会把当前处理的结点做为选中结点,这下会生成多层级结点
            if (isSelMySelft)
            {
                treeView1.SelectedNode = tnSub;
            }
            else
            {
                treeView1.SelectedNode = tnSub.Parent;
                selectNode = tnSub.Parent;
            }
            TreeNodeMouseClickEventArgs e = new TreeNodeMouseClickEventArgs(tnSub, 0, 0, 0, 0);
            DrawPackObject(pob);
            if (isSelMySelft)
            {
                selectPoB = pob;
            }
            else
            {
                selectPoB = pob.SetParent;
            }
            //treeView1_NodeMouseClick(null, e);
        }
        DrawGraphManagement.MyUserControl.UCBase uc = null;
        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            TreeNode tn = e.Node;
            selectNode = tn;
            PackObjBase pob = (PackObjBase)tn.Tag;
            DrawPackObject(pob);
        }
        private void DrawPackObject(PackObjBase pob)
        {
            if (pob != null)
            {
                if (selectPoB != null && !pob.Equals(selectPoB))
                {
                    selectPoB.IsSelect = false;
                    selectPoB.Draw();
                }
                
                if (selectPoB == null || !pob.Equals(selectPoB))
                {
                    pob.IsSelect = true;
                    selectPoB = pob;
                }
                //得先画才能显示属性
                pob.Draw();
                //设置属性
                SetPropertyPanle(pob);
            }
        }
        /// 
        /// 设置属性面板的显示
        /// 
        /// 
        private void SetPropertyPanle(PackObjBase pob)
        {
            Type type = pob.GetType();
            PropertyInfo[] infos = type.GetProperties();
            toolTip1.RemoveAll();
            panel3.Controls.Clear();
            Panel panel = null;
            Panel sumPanel = new Panel();
            sumPanel.AutoSize = true;
            sumPanel.Dock = DockStyle.Top;
            foreach (PropertyInfo info in infos)
            {
                Attribute[] attribs = Attribute.GetCustomAttributes(info);
                Attribute attrib = attribs.FirstOrDefault(s => s is NoCreatControlAttributs);
                //如果增加了NoCreatControlAttributs这个属性的属性则不生成控件
                if (attrib != null) continue;
                if (info.PropertyType == typeof(String) || info.PropertyType == typeof(uint) || info.PropertyType == typeof(int) || info.PropertyType == typeof(DateTime) || info.PropertyType == typeof(float) || info.PropertyType == typeof(double) || info.PropertyType == typeof(bool))
                {
                    uc = new DrawGraphManagement.MyUserControl.UCAttrib(selectPoB);
                    uc.SetToolTip = toolTip1;
                    panel = uc.GreatPropertyPanel(info);
                }
                else if (info.PropertyType == typeof(Color))
                {
                    uc = new DrawGraphManagement.MyUserControl.UCColor(selectPoB);
                    uc.SetToolTip = toolTip1;
                    uc.colorDialog1 = colorDialog1;
                    panel = uc.GreatPropertyPanel(info);
                }
                else if (info.PropertyType.IsEnum)
                {
                    uc = new DrawGraphManagement.MyUserControl.UCSelect(selectPoB);
                    uc.datasource = System.Enum.GetNames(info.PropertyType);
                    uc.SetToolTip = toolTip1;
                    panel = uc.GreatPropertyPanel(info);
                }
                if (panel != null)
                {
                    sumPanel.Controls.Add(panel);
                    ModPackObjTree(treeView1.Nodes, selectPoB);
                }
                uc.ChangeValue += new UCBase.ChangeValueEventHandler(UC_ChangeValue);
            }
            this.panel3.Controls.Add(sumPanel);
        }
        public void UC_ChangeValue(PackObjBase sender, EventArgs e)
        {
            uc.ChangeValue -= new UCBase.ChangeValueEventHandler(UC_ChangeValue);
            if (sender == null) return;
        }
        public void labColor_Click(object sender, EventArgs e)
        {
            if (selectPoB == null) return;
            System.Windows.Forms.Label lab = (sender as System.Windows.Forms.Label);
            try
            {
                Color col = ((BoxPackObj)selectPoB).FillColor;
                if (colorDialog1.ShowDialog() == DialogResult.OK)
                {
                    col = colorDialog1.Color;
                    ((BoxPackObj)selectPoB).FillColor = col;
                    lab.BackColor = col;
                }
            }
            catch (Exception)
            {
            }
            finally
            {
                ModPackObjTree(treeView1.Nodes, selectPoB);
                if (selectPoB != null)
                {
                    selectPoB.Draw();
                }
            }
        }
        float moveSpanX = 0;
        float moveSpanY = 0;
        MovePackObjCommand moveCmd = null;
        private bool zedGraphControl1_MouseDownEvent(ZedGraphControl sender, MouseEventArgs e)
        {
            moveSpanX = (float)(Convert.ToDouble(e.X) / Convert.ToDouble(zedGraphControl1.Width));
            moveSpanY = (float)(Convert.ToDouble(e.Y) / Convert.ToDouble(zedGraphControl1.Height));
            float x = (float)(Convert.ToDouble(e.X) / Convert.ToDouble(zedGraphControl1.Width));
            float y = (float)(Convert.ToDouble(e.Y) / Convert.ToDouble(zedGraphControl1.Height));
            if (e.Button == MouseButtons.Left)
            {
                CommandManage.GetInstance.MouseLeftDown = true;
                if (CommandManage.GetInstance.CtrlDown)
                {
                    if (selectPoB != null)
                    {
                        moveCmd = new MovePackObjCommand(areaManage, selectPoB);
                        moveCmd.PreExecute();
                    }
                }
            }
            if (e.Button == MouseButtons.Right)
            {
                zedGraphControl1.ContextMenuStrip.Items.Clear();
                List packs = areaManage.PackManage.ListPob.FindAll(s => s is TextPackObj);
                bool isHaveSelect = false;
                PackObjBase selPobT = null;
                foreach (PackObjBase pack in packs)
                {
                    if (pack.InScope((float)x, (float)y))
                    {
                        ToolStripItem mi = new ToolStripMenuItem();
                        int lent = 6;
                        if (pack.PackText.Length <= lent) lent = pack.PackText.Length;
                        mi.Text = pack.PackText.Substring(0, lent);
                        mi.Click -= new EventHandler(contextMenuStrip3_ItemClick);
                        mi.Click += new EventHandler(contextMenuStrip3_ItemClick);
                        mi.Tag = pack;
                        zedGraphControl1.ContextMenuStrip.Items.Add(mi);
                        selPobT = pack;
                        isHaveSelect = true;
                    }
                }
                if (!isHaveSelect)
                {
                    PackObjBase pack = areaManage.PackManage.ListPob.FirstOrDefault(s => s is BorderPackObj);
                    if (pack != null)
                    {
                        ToolStripItem mi = new ToolStripMenuItem();
                        //int lent = 6;
                        mi.Text = "白板对象";
                        mi.Click -= new EventHandler(contextMenuStrip3_ItemClick);
                        mi.Click += new EventHandler(contextMenuStrip3_ItemClick);
                        mi.Tag = pack;
                        zedGraphControl1.ContextMenuStrip.Items.Add(mi);
                    }
                }
            }
            return default(bool);
        }
        private void contextMenuStrip3_ItemClick(object sender, EventArgs e)
        {
            ToolStripItem item = (ToolStripItem)sender;
            PackObjBase pack = item.Tag as PackObjBase;
            if (pack != null) {
                DrawPackObject(pack);
                ClearSelectColor(treeView1.Nodes);
                //右键选中后右侧树结点标红
                TreeColorRed(treeView1.Nodes, pack.Descript ,false);
                treePropertyList.ExpandAll();
            }
        }
        private bool zedGraphControl1_MouseMoveEvent(ZedGraphControl sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                if (CommandManage.GetInstance.CtrlDown && CommandManage.GetInstance.MouseLeftDown) {
                    if (selectPoB != null && moveCmd != null) {
                        float pointTX = (float)(Convert.ToDouble(e.X) / Convert.ToDouble(zedGraphControl1.Width));
                        float pointTY = (float)(Convert.ToDouble(e.Y) / Convert.ToDouble(zedGraphControl1.Height));
                        moveSpanX = pointTX - moveSpanX - poManager.X;
                        moveSpanY = pointTY - moveSpanY - poManager.Y;
                        moveCmd.Execute(moveSpanX, moveSpanY);
                        moveSpanX = selectPoB.X;
                        moveSpanY = selectPoB.Y;
                    }
                }
			}
            return default(bool);
        }
        private bool zedGraphControl1_MouseUpEvent(ZedGraphControl sender, MouseEventArgs e)
        {
            double x = Convert.ToDouble(Convert.ToDouble(e.X) / Convert.ToDouble(zedGraphControl1.Width));
            double y = Convert.ToDouble(Convert.ToDouble(e.Y) / Convert.ToDouble(zedGraphControl1.Height));
            int scrollX = 0;
            int scrollY = 0;
            scrollX = panelzgc.HorizontalScroll.Value;
            scrollY = panelzgc.VerticalScroll.Value;
            txtXAisx.Text = x.ToString();// + "--" + scrollX.ToString();
            txtYAisx.Text = y.ToString(); //"--" + scrollY.ToString();
			if (e.Button == MouseButtons.Left)
            {
                if (CommandManage.GetInstance.CtrlDown && CommandManage.GetInstance.MouseLeftDown)
                {
                    CommandManage.GetInstance.MouseLeftDown = false;
                    if (moveCmd != null)
                    {
                        moveCmd.LastExecute();
                        CommandManage.GetInstance.AddCommand(moveCmd);
                        if (selectPoB != null)
                        {
                            string propertyName = "X,Y,EndX,EndY";
                            SetSpecificPropertyValues(propertyName);
                        }
                    }
                }
            }
            return default(bool);
        }
        /// 
        /// 设置属性面板中特定的值
        /// 
        /// 
        private void SetSpecificPropertyValues(string _propertyName)
        {
            string[] pros = _propertyName.Split(',');
            foreach (string propertyName in pros)
            {
                Control[] conls = panel3.Controls.Find("textBox" + propertyName, true);
                if (conls.Length > 0)
                {
                    Type Ts = selectPoB.GetType();
                    object o = Ts.GetProperty(propertyName).GetValue(selectPoB, null);
                    string Value = Convert.ToString(o);
                    conls[0].Text = Value;
                }
            }
        }
        /// 
        /// 画直线
        /// 
        /// 
        /// 
        private void PackObjBtn_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            if (btn != null && btn.Tag != null)
            {
                PackObjBase bpo = BoardUtil.PackObjFactory(btn.Tag.ToString(), zedGraphControl1, poManager);
                if (bpo != null)
                {
                    poManager.ListPob.Add(bpo);
                    InsertPackObjTree(bpo);
                }
            }
        }
        /// 
        /// 按顺序画组件
        /// 
        /// 
        /// 
        private void button1_Click(object sender, EventArgs e)
        {
            poManager.DrawPackObj();
        }
        /// 
        /// 保存文件
        /// 
        /// 
        /// 
        private void button2_Click(object sender, EventArgs e)
        {
            bool reVal = false;
            reVal = areaManage.Save();
            if (reVal)
            {
                MessageBox.Show(poManager.MsgStr);
            }
            else
            {
                MessageBox.Show(poManager.MsgStr);
            }
        }
        /// 
        /// 打开模板
        /// 
        /// 
        /// 
        private void button3_Click(object sender, EventArgs e)
        {
            //poManager = new PackObjManager(zedGraphControl1);
            //poManager.AllClear();
            //selectPoB = null;
            //if (uc is DrawGraphManagement.MyUserControl.UCAttrib)
            //    (uc as DrawGraphManagement.MyUserControl.UCAttrib).Clear();
            //OpenFileDialog ofd = new OpenFileDialog();
            //ofd.Filter = "(*.pom)|*.pom|(*.khd)|*.KHD|(*.*)|*.*";
            //ofd.RestoreDirectory = true;
            //if (ofd.ShowDialog() == DialogResult.OK)
            //{
            //    try
            //    {
            //        asFileName = ofd.FileName;
            //        //管理器加载
            //        poManager.LoadContent(ofd.FileName);
            //        treeView1.Nodes.Clear();
            //        InsertPackObjToTree(poManager.ListPob);
            //    }
            //    catch (Exception exp)
            //    {
            //        MessageBox.Show(exp.Message);
            //    }
            //    ControlDatabind();
            //}
        }
        private void ControlDatabind(bool isDataSource = true)
        {
            txtManagerX.DataBindings.Clear();
            txtManagerX.DataBindings.Add("text", poManager, "X");
            txtManagerY.DataBindings.Clear();
            txtManagerY.DataBindings.Add("text", poManager, "Y");
            txtManageName.DataBindings.Clear();
            txtManageName.DataBindings.Add("text", areaManage, "Name");
            txtClassName.DataBindings.Clear();
            txtClassName.DataBindings.Add("text", areaManage, "ClassName");
            if (areaManage.DllName == "") areaManage.DllName = "DrawGraph.dll";
            txtDllName.DataBindings.Clear();
            txtDllName.DataBindings.Add("text", areaManage, "DllName");
            if (areaManage.NameSpace == "") areaManage.NameSpace = "DrawGraph.";
            txtNameSpace.DataBindings.Clear();
            txtNameSpace.DataBindings.Add("text", areaManage, "NameSpace");
            if (areaManage.InstanceName == "") areaManage.InstanceName = "OperationRecord";
            txtInstanceName.DataBindings.Clear();
            txtInstanceName.DataBindings.Add("text", areaManage, "InstanceName");
            BoardUtil.ZedControlClear(zedGraphControl1);
            if (isDataSource)
                //绑定treePropertyList控件,手术类属性列表
                BindPropertyList(areaManage.OpeRecord);
            else
                BindEntityList();
        }
        private void BindEntityList()
        {
            List Entitys = new List();
            Assembly _Assembyle = Assembly.LoadFile(AppDomain.CurrentDomain.BaseDirectory + "DrawGraph.dll");//你的loadfile
            Type[] _TypeList = _Assembyle.GetTypes();
            for (int i = 0; i != _TypeList.Length; i++)
            {
                if (_TypeList[i].Namespace == "DrawGraphManagementArea.DocumentEntity")
                {
                    Entitys.Add(_TypeList[i].Name);
                }
            }
            txtInstanceName.DataSource = Entitys;
        }
        /// 
        /// 绑定treePropertyList控件,手术类属性列表
        /// 
        private void BindPropertyList(Object classObj, string objName = "OperationRecord")
        {
            treePropertyList.Nodes.Clear();
            PropertyObject proObj = new PropertyObject();
            proObj.Key = objName;
            proObj.Description = "类名";
            List propertyList = BoardFormUtil.GetPropertyList(classObj);
            proObj.SubPropertyList = propertyList;
            TreeNode tnSub = new TreeNode();
            tnSub.Name = proObj.ViewTreeNode;
            tnSub.Text = proObj.ViewTreeNode;
            tnSub.Tag = proObj;
            treePropertyList.Nodes.Add(tnSub);
            BindPropertyListSubNode(propertyList, tnSub.Nodes);
        }
        /// 
        /// 绑定treePropertyList控件的子结点
        /// 
        /// 
        /// 
        private void BindPropertyListSubNode(List propertyList, TreeNodeCollection nodes)
        {
            foreach (PropertyObject propert in propertyList)
            {
                TreeNode tnSub = new TreeNode();
                tnSub.Name = propert.ViewTreeNode;
                tnSub.Text = propert.ViewTreeNode;
                tnSub.Tag = propert;
                if (propert.SubPropertyList.Count > 0)
                {
                    BindPropertyListSubNode(propert.SubPropertyList, tnSub.Nodes);
                }
                nodes.Add(tnSub);
            }
        }
        private void InsertPackObjToTree(List pobs)
        {
            List subPobs = pobs.FindAll((c) => { return c.ParentName == ""; });
            foreach (PackObjBase pob in subPobs)
            {
                //先插入父节点为空的内容到根节点
                InsertListPobObjToTree(pob);
                //插入此结点下的所有子节点
                InsertSubPackObjToTree(pobs, pob);
            }
        }
        private void InsertSubPackObjToTree(List pobs, PackObjBase parentPob)
        {
            List subPobs = pobs.FindAll((c) => { return c.ParentName == parentPob.PackName; });
            if (subPobs.Count > 0)
            {
                foreach (PackObjBase pob in subPobs)
                {
                    pob.SetParent = parentPob;
                    InsertListPobObjToTree(pob);
                    //回调查找自己下面是否有子对象
                    InsertSubPackObjToTree(pobs, pob);
                }
            }
        }
        private void InsertListPobObjToTree(PackObjBase pob)
        {
            pob.Changed += new PackObjBase.ChangedEventHandler(Bpo_Changed);
            TreeNode tnSub = new TreeNode();
            pob.IsSelect = false;
            tnSub.Name = pob.PackName;
            tnSub.Tag = pob;
            tnSub.Text = pob.Descript;
            if (pob.SetParent == null)
            {
                treeView1.Nodes.Add(tnSub);
            }
            else
            {
                TreeNode[] tns = treeView1.Nodes.Find(pob.SetParent.PackName, true);
                if (tns.Length > 0)
                {
                    tns[0].Nodes.Add(tnSub);
                }
            }
            pob.Draw();
        }
        private void MenuItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem btn = (ToolStripMenuItem)sender;
            if (btn != null && btn.Tag != null)
            {
                string tag = btn.Tag.ToString();
                switch (tag)
                {
                    case "ChartPackObj":
                        this.CreateTreeItem(tag);
                        
                        this.CreateTreeItem(x1轴ToolStripMenuItem.Tag.ToString());
                        this.CreateTreeItem(x2轴ToolStripMenuItem.Tag.ToString(), true);
                        this.CreateTreeItem(y1轴ToolStripMenuItem.Tag.ToString(), true);
                        this.CreateTreeItem(y2轴ToolStripMenuItem.Tag.ToString(), true);
                        break;
                    default:
                        this.CreateTreeItem(tag);
                        break;
                }
            }
        }
        /// 
        /// 可建立绑定数据源的结点
        /// 
        /// 
        /// 
        /// 
        /// 
        private void CreateTreeItem(string tag, string dataSourceName = "", string tagDesc = "", string viewText = "", bool isSelMySelf = true)
        {
            PackObjBase bpo = BoardUtil.PackObjFactory(tag, zedGraphControl1, poManager);
            //#region 增加初始默认值
            if (bpo is LinePackObj || bpo is BoxPackObj || bpo is DottedLinePackObj || bpo is DottedLinesPackObj || bpo is LinesPackObj || bpo is RectangleFramePackObj)
            {
                bpo.EndX = 0.1f;
                bpo.EndY = 0.1f;
            }
            if (bpo is AbleEditPackObj) {
                AbleEditPackObj a = bpo as AbleEditPackObj;
                a.IsViewBoard = EIsBool.True;
            }
            //#endregion
            if (bpo != null)
            {
                if (dataSourceName != "")
                {
                    bpo.DataSourceName = dataSourceName;
                    bpo.CreatePackTag();
                }
                if (tagDesc != "")
                {
                    bpo.Descript = tagDesc;
                }
                if (viewText != "")
                {
                    bpo.PackText = viewText;
                }
                if (bpo is TextPackObj) {
                    TextPackObj tpb = (bpo as TextPackObj);
                    float d = 0;
                    if (float.TryParse(txtFontSize.Text,out d))
                    {
                        tpb.FontSize = d;
                    }
                }
                bool reVal = poManager.ListPobsAdd(bpo);
                if (reVal)
                {
                    InsertPackObjTree(bpo, isSelMySelf);
                    bpo.Changed += new PackObjBase.ChangedEventHandler(Bpo_Changed);
                }
                else
                {
                    MessageBox.Show("创建组件不能重复");
                }
            }
        }
        /// 
        /// 建立普通非绑定数据源的结点
        /// 
        /// 
        /// 
        private void CreateTreeItem(string tag, bool hasBrother)
        {
            PackObjBase bpo = BoardUtil.PackObjFactory(tag, zedGraphControl1, poManager);
            if (bpo != null)
            {
                if (hasBrother)
                    treeView1.SelectedNode = treeView1.SelectedNode.Parent;
                poManager.ListPob.Add(bpo);
                InsertPackObjTree(bpo);
                bpo.Changed += new PackObjBase.ChangedEventHandler(Bpo_Changed);
            }
        }
        private void Bpo_Changed(PackObjBase pob)
        {
            ModPackObjTree(treeView1.Nodes, pob);
        }
        private void Form1_KeyUp(object sender, KeyEventArgs e)
        {
            if ((e.Control) && e.KeyCode == Keys.S)
            {
                SaveFileForKey();
            }
            if ((e.Control) && e.KeyCode == Keys.Z) {
                bool val = CommandManage.GetInstance.CtrlZCommand();
                if (val)
                {
                    ReLoad();
                }
            }
            if ((e.Control) && e.KeyCode == Keys.Y)
            {
                bool val = CommandManage.GetInstance.CtrlYCommand();
                if (val)
                {
                    ReLoad();
                }
            }else if (e.Control && e.KeyCode == Keys.Left)
            {
                TreeNode tn = treeView1.SelectedNode;
                if (tn != null)
                {
                    PackObjBase pob = (PackObjBase)tn.Tag;
                    if (pob != null)
                    {
                        float moveSpanX = float.Parse(txtMoveValue.Text.Trim());
                        float moveSpanY = 0f;
                        MovePackObjCommand cmd = new MovePackObjCommand(areaManage, pob);
                        cmd.Execute(-moveSpanX, moveSpanY);
                        string propertyName = "X,Y,EndX,EndY";
                        SetSpecificPropertyValues(propertyName);
                    }
                }
            }
            else if (e.Control && e.KeyCode == Keys.Right)
            {
                TreeNode tn = treeView1.SelectedNode;
                if (tn != null)
                {
                    PackObjBase pob = (PackObjBase)tn.Tag;
                    if (pob != null)
                    {
                        float moveSpanX = float.Parse(txtMoveValue.Text.Trim());
                        float moveSpanY = 0f;
                        MovePackObjCommand cmd = new MovePackObjCommand(areaManage, pob);
                        cmd.Execute(moveSpanX, moveSpanY);
                        string propertyName = "X,Y,EndX,EndY";
                        SetSpecificPropertyValues(propertyName);
                    }
                }
            }
            else if (e.Control && e.KeyCode == Keys.Up)
            {
                TreeNode tn = treeView1.SelectedNode;
                if (tn != null)
                {
                    PackObjBase pob = (PackObjBase)tn.Tag;
                    if (pob != null)
                    {
                        float moveSpanY = float.Parse(txtMoveValue.Text.Trim());
                        float moveSpanX = 0f;
                        MovePackObjCommand cmd = new MovePackObjCommand(areaManage, pob);
                        cmd.Execute(moveSpanX, -moveSpanY);
                        string propertyName = "X,Y,EndX,EndY";
                        SetSpecificPropertyValues(propertyName);
                    }
                }
            }
            else if (e.Control && e.KeyCode == Keys.Down)
            {
                TreeNode tn = treeView1.SelectedNode;
                if (tn != null)
                {
                    PackObjBase pob = (PackObjBase)tn.Tag;
                    if (pob != null)
                    {
                        float moveSpanY = float.Parse(txtMoveValue.Text.Trim());
                        float moveSpanX = 0f;
                        MovePackObjCommand cmd = new MovePackObjCommand(areaManage, pob);
                        cmd.Execute(moveSpanX, moveSpanY);
                        string propertyName = "X,Y,EndX,EndY";
                        SetSpecificPropertyValues(propertyName);
                    }
                }
            }
            CommandManage.GetInstance.CtrlDown = false;
        }
        private void ReLoad()
        {
            selectPoB = null;
            zedGraphControl1.MasterPane.GraphObjList.Clear();
            treeView1.Nodes.Clear();
            panel3.Controls.Clear();
            poManager.SetZedControl(zedGraphControl1);
            InsertPackObjToTree(poManager.ListPob);
            treeView1.ExpandAll();
            zedGraphControl1.Refresh();
        }
        private void zedGraphControl1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control)
            {
                CommandManage.GetInstance.CtrlDown = true;
            }
        }
        /// 
        /// 使用Ctrl + S组合键保存
        /// 
        private void SaveFileForKey()
        {
            poManager.SaveFile("", areaManage.Id);
        }
        private void 打印ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            pDoc.PrintPage += new PrintPageEventHandler(pDoc_PrintPage);
            System.Windows.Forms.PrintDialog pDlg = new System.Windows.Forms.PrintDialog();
            pDlg.Document = pDoc;
            if (pDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                pDoc.Print();
            }
        }
        private void pDoc_PrintPage(object sender, PrintPageEventArgs e)
        {
            try
            {
                pDoc.PrintPage -= new PrintPageEventHandler(pDoc_PrintPage);
                Image img = zedGraphControl1.GetImage();
                //e.Graphics.DrawImage(img,20f,0f,800f,1160f);
                e.Graphics.DrawImage(img, 20f, 0f);
            }
            catch (Exception ex)
            {
                Console.Write(ex.ToString());
            }
        }
        private void treeView1_MouseDown(object sender, MouseEventArgs e)
        {
            if (tabControl1.SelectedIndex == 0)
            {
                if (e.Button == MouseButtons.Right)
                {
                    Point ClickPoint = new Point(e.X, e.Y);
                    TreeNode current = treeView1.GetNodeAt(ClickPoint);
                    if (current != null)//判断你点的是不是一个节点
                    {
                        treeView1.SelectedNode = current;//选中这个节点
                    }
                }
            }
        }
        /// 
        /// 临时节点集合:用于临时存储剪切或者复制下的节点信息
        /// 
        PackObjTree packObjTree = new PackObjTree();
        /// 
        /// 树结构的操作方式:剪切或者拷贝
        /// 
        bool isCopy = false;
        private void cutMenuItem_Click(object sender, EventArgs e)
        {
            CutForKey();
        }
        /// 
        /// 剪切节点操作
        /// 
        private void CutForKey()
        {
            TreeNode node = treeView1.SelectedNode;
            packObjTree = InitPackObjTree(node);
            RemoveNode(node);
            //this.pasteMenuItem.Enabled = true;
            isCopy = false;
        }
        private void copyMenuItem_Click(object sender, EventArgs e)
        {
            CopyForKey();
        }
        /// 
        /// 复制操作
        /// 
        private void CopyForKey()
        {
            TreeNode node = treeView1.SelectedNode;
            packObjTree = InitPackObjTree(node);
            //this.pasteMenuItem.Enabled = true;
            isCopy = true;
        }
        private void pasteMenuItem_Click(object sender, EventArgs e)
        {
            PasteForKey();
        }
        /// 
        /// 粘贴操作
        /// 
        private void PasteForKey()
        {
            //this.pasteMenuItem.Enabled = isCopy;
            if (isCopy)
            {
                PackObjBase pob = packObjTree.Current.CloneParse();
                if (pob != null)
                {
                    poManager.ListPob.Add(pob);
                    InsertPackObjTree(pob);
                    pob.Changed += new PackObjBase.ChangedEventHandler(Bpo_Changed);
                }
            }
            if (!isCopy)
                packObjTree = null;
        }
        private void deleteMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("是否要确认删除?", "删除确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dr == DialogResult.OK)
            {
                TreeNode node = treeView1.SelectedNode;
                RemoveNode(node);
            }
        }
        /// 
        /// 构造临时节点树
        /// 
        /// 需要添加的节点
        private PackObjTree InitPackObjTree(TreeNode node)
        {
            PackObjTree pobTree = new PackObjTree();
            if (node != null)
            {
                PackObjBase pob = (PackObjBase)node.Tag;
                pobTree.Current = pob;
                pobTree.ParentPob = pob.SetParent;
                if (node.Nodes != null && node.Nodes.Count > 0)
                {
                    foreach (TreeNode tempNode in node.Nodes)
                    {
                        pobTree.SonPobs.Add(InitPackObjTree(tempNode));
                    }
                }
            }
            return pobTree;
        }
        /// 
        /// 移除指定节点及子节点
        /// 
        /// 需要移除的节点
        private void RemoveNode(TreeNode node)
        {
                if (node != null)
                {
                    PackObjBase pob = (PackObjBase)node.Tag;
                    if (pob != null)
                    {
                        DelPackObj(node, pob);
                    }
                    List nodeCol = new List();
                    foreach (TreeNode tempNode in node.Nodes)
                    {
                        nodeCol.Add(tempNode);
                    }
                    if (node.Nodes != null && node.Nodes.Count > 0)
                    {
                        foreach (TreeNode tempNode in nodeCol)
                        {
                            RemoveNode(tempNode);
                        }
                    }
                }
        }
        private void treeView1_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                TreeNode tn = treeView1.SelectedNode;
                if (tn != null)
                {
                    PackObjBase pob = (PackObjBase)tn.Tag;
                    if (pob != null)
                    {
                        DialogResult dr = MessageBox.Show("是否要确认删除?", "删除确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                        if (dr == DialogResult.OK)
                        {
                            RemoveNode(tn);
                        }
                    }
                }
            }
            else if ((e.Control) && e.KeyCode == Keys.S)
            {
                //SaveFileForKey();
            }
            else if ((e.Control) && e.KeyCode == Keys.C)
            {
                //CopyForKey();
            }
            else if ((e.Control) && e.KeyCode == Keys.X)
            {
                //CutForKey();
            }
            else if ((e.Control) && e.KeyCode == Keys.V)
            {
                //if (packObjTree != null)
                //    PasteForKey();
            }
        }
        private void DelPackObj(TreeNode tn, PackObjBase pob)
        {
            MovePackObjCommand cmd = new MovePackObjCommand(CommandManage.GetInstance.AreaManage, pob);
            cmd.PreExecute();
            bool reBool = poManager.RemovePob(pob);
            if (reBool)
            {
                //如果执行成功保存命令
                cmd.LastExecute();
                CommandManage.GetInstance.AddCommand(cmd);
                //执行其他操作;
                pob.Clear();
                selectPoB = null;
                zedGraphControl1.Refresh();
                panel3.Controls.Clear();
                if (tn != null)
                {
                    TreeNodeCollection tns = tn.Nodes;
                    TreeNode tnParent = tn.Parent;
                    treeView1.Nodes.Remove(tn);
                    if (tns.Count > 0)
                    {
                        foreach (TreeNode tnTemp in tns)
                        {
                            tnParent.Nodes.Add(tnTemp);
                        }
                    }
                }
            }
        }
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            TreeNode selNode = treePropertyList.SelectedNode;
            if (selNode != null)
            {
                PropertyObject property = (PropertyObject)selNode.Tag;
                if (property != null)
                {
                    ToolStripMenuItem item = sender as ToolStripMenuItem;
                    if (item != null)
                    {
                        PackObjBase pack = areaManage.PackManage.ListPob.FirstOrDefault(s => s.DataSourceName == property.ViewDesignTag());
                        bool isAdd = true;
                        if (pack != null) {
                            
                            DialogResult result = MessageBox.Show("要增加的数据绑定组件,已经存在,且结点是:"+ pack.Descript, "是否增加", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                            if (result == DialogResult.Yes)
                            {
                                isAdd = true;
                            }
                            else {
                                isAdd = false;
                            }
                        }
                        if (isAdd)
                        {
                            if (selectNode != null)
                            {
                                treeView1.SelectedNode = selectNode;
                            }
                            //自动增加一组带描述,下划线及文本对象的组件。
                            //设置成有层级关系的
                            //isAddNodeDown = true;
                            this.CreateTreeItem("TextPackObj", "", property.Key + "文本", property.Key);
                            this.CreateTreeItem(item.Tag.ToString(), property.ViewDesignTag(), property.Key,"", false);
                            //完成后换成无层级模式。
                            //isAddNodeDown = false;
                        }
                    }
                    else
                    {
                        MessageBox.Show("创建组件时TAG不能为空");
                    }
                }
            }
        }
        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //if (tabControl1.SelectedIndex == 0)
            //{
            //    isAddNodeDown = true;
            //}
            //else
            //{
            //    isAddNodeDown = false;
            //}
        }
        private void button1_Click_1(object sender, EventArgs e)
        {
            string objName = txtInstanceName.Text.Trim();
            Object obj = BoardFormUtil.GetObjectFactory