using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ICSharpCode.Core;
using Mesnac.Basic;
using System.Text.RegularExpressions;

using Mesnac.ActionService;

namespace Mesnac.Gui.Edit.Dialog
{
    public partial class FrmEventAction : Form
    {
        private List<Mesnac.Controls.Base.DesignAction> _currentActionList = new List<Controls.Base.DesignAction>();        //当前控件的操作列表

        public FrmEventAction()
        {
            InitializeComponent();

            this.InitData(string.Empty);
            this.InitUIMethod();
        }

        /// <summary>
        /// 初始化界面元素
        /// </summary>
        public void InitUIMethod()
        {
            this.Text = StringParser.Parse(ResourceService.GetString("Mesnac_Dialog_FrmEventAction_Text"));         //事件操作选择器
            this.label1.Text = StringParser.Parse(ResourceService.GetString("Mesnac_Dialog_FrmEventAction_label1"));    //当前选择
            this.lblRemarkTitle.Text = StringParser.Parse(ResourceService.GetString("Mesnac_Dialog_FrmEventAction_lblRemarkTitle"));    //备注信息
            this.btnOk.Text = StringParser.Parse(ResourceService.GetString("Mesnac_Dialog_btnOK"));         //确定
            this.btnCancel.Text = StringParser.Parse(ResourceService.GetString("Mesnac_Dialog_btnCancel")); //取消
            this.btnClear.Text = StringParser.Parse(ResourceService.GetString("Mesnac_Dialog_btnClear"));   //清除
        }

        public void InitData(string filter)
        {
            Mesnac.ActionService.Service.Instance.IniDesignAction(Mesnac.Gui.Edit.Global.AppConfigHandler.Instance.CurrentProjectWizardName + "/");
            TreeNode root = new TreeNode();
            root.Text = StringParser.Parse(ResourceService.GetString("Mesnac_Dialog_FrmEventAction_treeView1_rootText")); //"操作树";
            this.IniTree(root, Mesnac.ActionService.Service.Instance.DesignActionTree, filter, false);
            this.treeView1.Nodes.Clear();
            this.treeView1.Nodes.Add(root);
            if (String.IsNullOrEmpty(filter))
            {
                this.treeView1.CollapseAll();
                root.Expand();
            }
            else
            {
                this.treeView1.ExpandAll();
            }

            //this.treeView1.CheckBoxes = true;
        }

        bool GetLevel(DesignActionNode cur, string Filter)
        {
            bool returnbool=false;
            Regex chinese = new Regex(@"[\u4e00-\u9fa5]");
            if (chinese.IsMatch(Filter))
            {
                if (cur.Children.Count != 0 && !cur.Name.Contains(Filter))
                {
                    foreach (DesignActionNode actionnode in cur.Children)
                    {
                        //if (actionnode.ActionNode.Where(t => t.Name.Contains(Filter)).FirstOrDefault() != null)
                        //    return true;
                        if (GetLevel(actionnode, Filter))
                            return true;
                    }
                }
                else
                {
                    if (cur.Name.Contains(Filter) || cur.ActionNode.Where(t => t.Name.Contains(Filter)).FirstOrDefault() != null)
                        return true;
                    else
                        return false;
                }
            }
            else
            {
                if (cur.Children.Count != 0 && GetChineseSpell(cur.Name).IndexOf(Filter,StringComparison.OrdinalIgnoreCase)<0)
                {
                    foreach (DesignActionNode actionnode in cur.Children)
                    {
                        //if (actionnode.ActionNode.Where(t => t.Name.Contains(Filter)).FirstOrDefault() != null)
                        //    return true;
                        if (GetLevel(actionnode, Filter))
                            return true;
                    }
                }
                else
                {
                    if (GetChineseSpell(cur.Name).IndexOf(Filter, StringComparison.OrdinalIgnoreCase) >=0 || cur.ActionNode.Where(t =>GetChineseSpell(t.Name).ToLower().Contains(Filter.ToLower())).FirstOrDefault() != null)
                        return true;
                    else
                        return false;
                }
            }
            return returnbool;
        }

        private void IniTree(TreeNode node, DesignActionNode cur,string filter,bool isComplete)
        {
            Regex chinese = new Regex(@"[\u4e00-\u9fa5]");
            foreach (DesignAction actionnode in cur.ActionNode)
            {
                if (!Convert.ToBoolean(node.Tag))
                {
                    if (!isComplete)
                    {
                        if (chinese.IsMatch(filter))
                        {
                            if (!actionnode.Name.Contains(filter))
                                continue;
                        }
                        else
                        {
                            if (GetChineseSpell(actionnode.Name).IndexOf(filter,StringComparison.OrdinalIgnoreCase)<0)
                                continue;
                        }
                    }
                }
                TreeNode child = new TreeNode();
                child.Name = actionnode.GUID;
                child.ToolTipText = actionnode.Remark;
                child.Text = actionnode.Name;
                node.Nodes.Add(child);
            }
            foreach (DesignActionNode actionnode in cur.Children)
            {
                if (!Convert.ToBoolean(node.Tag))
                {
                    //if (actionnode.Children.Count == 0)
                    //{
                    //    if (!actionnode.Name.Contains(Filter) && actionnode.ActionNode.Where(t => t.Name.Contains(Filter)).FirstOrDefault() == null)
                    //        continue;
                    //}
                    if (!GetLevel(actionnode, filter))
                        continue;
                }
                TreeNode child = new TreeNode();
                child.Name = string.Empty;
                child.ToolTipText = actionnode.Name;
                child.Text = actionnode.Name;
                if (chinese.IsMatch(filter))
                {
                    child.Tag = Convert.ToBoolean(node.Tag) ? true : actionnode.Name.Contains(filter);
                    node.Nodes.Add(child);
                    IniTree(child, actionnode, filter, actionnode.Name.Contains(filter) ? true : false);
                }
                else
                {
                    child.Tag = Convert.ToBoolean(node.Tag) ? true : GetChineseSpell(actionnode.Name).IndexOf(filter,StringComparison.OrdinalIgnoreCase)>=0;
                    node.Nodes.Add(child);
                    IniTree(child, actionnode, filter, GetChineseSpell(actionnode.Name).IndexOf(filter, StringComparison.OrdinalIgnoreCase) >= 0 ? true : false);
                }
            }
        }
        /// <summary>
        /// 操作列表
        /// </summary>
        public string StrActionList
        {
            get { return this.txtCurrent.Text; }
            set { this.txtCurrent.Text = value; }
        }

        /// <summary>
        /// 操作列表
        /// </summary>
        public List<Mesnac.Controls.Base.DesignAction> ActionList
        {
            get { return this._currentActionList; }
            set 
            { 
                this._currentActionList = value;
                if (this._currentActionList != null && this._currentActionList.Count > 0)
                {
                    foreach (Mesnac.Controls.Base.DesignAction action in this._currentActionList)
                    {
                        TreeNode node = this.treeView1.GetFirstNodeByNodeName(action.GUID);
                        if (node != null)
                        {
                            //node.Checked = true;
                            //node. = true;
                            this.treeView1.CollapseAll();
                            this.treeView1.SelectedNode = node;
                            node.Expand();
                            this.treeView1.Focus();
                            return;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 生成操作列表
        /// </summary>
        /// <param name="tn"></param>
        public void GenerateActionList(TreeNode tn)
        {
            if (tn.IsSelected && !String.IsNullOrEmpty(tn.Name))
            {
                this._currentActionList.Add(new Controls.Base.DesignAction() { GUID=tn.Name, Name = tn.Text, Remark = tn.ToolTipText });
            }
            foreach (TreeNode node in tn.Nodes)
            {
                this.GenerateActionList(node);
            }
        }

        TreeNode ShowAllNodes(TreeNodeCollection nodes)
        {
            TreeNode tn = null;
            foreach (TreeNode node in nodes)
            {
                if (node.IsSelected)
                    tn = node;
                if (node.Nodes.Count > 0)
                {
                    ShowAllNodes(node.Nodes);
                }
            }
            return tn;
        }


       /// <summary>
       /// 选择树节点
       /// </summary>
       /// <param name="sender"></param>
       /// <param name="e"></param>
        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            TreeNode tn = this.treeView1.SelectedNode;
            if (tn != null && !string.IsNullOrEmpty(tn.Name))
            {
                txtCurrent.Text = tn.Parent.Parent.Text + "-" + tn.Parent.Text + "-" + tn.Text;
                this.lblRemark.Text = String.Format("{0}", tn.ToolTipText);
            }
            else
            {
                txtCurrent.Text = "";
                this.lblRemark.Text = String.Empty;
            }
            this.treeView1.Focus();
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            this._currentActionList.Clear();
            this.GenerateActionList(this.treeView1.Nodes[0]);
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
        }
        /// <summary>
        /// 筛选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtFilter_TextChanged(object sender, EventArgs e)
        {
            InitData(txtFilter.Text);
            if (this._currentActionList != null && this._currentActionList.Count > 0)
            {
                foreach (Mesnac.Controls.Base.DesignAction action in this._currentActionList)
                {
                    TreeNode node = this.treeView1.GetFirstNodeByNodeName(action.GUID);
                    if (node != null)
                    {
                        this.treeView1.CollapseAll();
                        this.treeView1.SelectedNode = node;
                        node.Expand();
                        this.treeView1.Focus();
                    }
                }
            }
        }

        private void FrmEventAction_Activated(object sender, EventArgs e)
        {
            this.treeView1.Focus();
            if (String.IsNullOrEmpty(this.txtFilter.Text))
            {
                if (this.treeView1.Nodes.Count > 0)
                {
                    this.treeView1.Nodes[0].Expand();
                }
            }
        }
        /// <summary>
        /// 获取首字母
        /// </summary>
        /// <param name="strText"></param>
        /// <returns></returns>
         private  string GetChineseSpell(string strText)
        {
            int len = strText.Length;
            string myStr = "";
            for (int i = 0; i < len; i++)
            { myStr += getSpell(strText.Substring(i, 1)); }
            return myStr;
        }

        private string getSpell(string cnChar)
        {
            byte[] arrCN = System.Text.Encoding.Default.GetBytes(cnChar);
            if (arrCN.Length > 1)
            {
                int area = (short)arrCN[0];
                int pos = (short)arrCN[1];
                int code = (area << 8) + pos; 
                int[] areacode = { 45217, 45253, 45761, 46318, 46826, 47010, 47297, 47614, 48119, 48119, 49062, 49324, 49896, 50371, 50614, 50622, 50906, 51387, 51446, 52218, 52698, 52698, 52698, 52980, 53689, 54481 };
                for (int i = 0; i < 26; i++)
                {
                    int max = 55290;
                    if (i != 25)
                        max = areacode[i + 1];
                    if (areacode[i] <= code && code < max)
                    {
                        return System.Text.Encoding.Default.GetString(new byte[] { (byte)(65 + i) });
                    }
                } 
                return "";
            }
            else 
                return cnChar;
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            this._currentActionList.Clear();
            //this.GenerateActionList(this.treeView1.Nodes[0]);
            this.txtCurrent.Text = String.Empty;
            this.lblRemark.Text = String.Empty;
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
        }
    }
}