using ICSharpCode.TextEditor.Document;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
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 WeifenLuo.WinFormsUI.Docking;

namespace 开发辅助工具.Tools
{
    public partial class FrmJson : DockContent
    {
        public FrmJson()
        {
            InitializeComponent();
            textEditorControl1.Document.FoldingManager.FoldingStrategy = new JackWangCUMT.WinForm.MingFolding();
        }
        private void LoadTreeList(TreeNodeCollection nodes,JObject jo)
        {
            foreach (var item in jo)
            {
                if (item.Value.HasValues)
                {
                    var node = nodes.Add(item.Key.ToString());
                    node.Tag = new JsonInfo() { name = item.Key.ToString(), value = item.Value.ToString() };
                    try
                    {
                        JArray jar = JArray.Parse(item.Value.ToString());
                        if (jar != null)
                        {
                            for (int i = 0; i < jar.Count; i++)
                            {
                                var node1 = node.Nodes.Add(i.ToString());
                                node.Tag = new JsonInfo() { name = item.Key.ToString(), value = item.Value.ToString() };
                                LoadTreeList(node1.Nodes, (JObject)JsonConvert.DeserializeObject(jar[i].ToString()));
                                //TreeNode new_child = new TreeNode();
                                //new_child.Text = jar[i].ToString();
                                //node.Nodes.Add(new_child);
                            }
                        }
                    }
                    catch(Exception)
                    { LoadTreeList(node.Nodes, (JObject)JsonConvert.DeserializeObject(item.Value.ToString())); }
                    
                    //JArray jar = JArray.Parse(item.Value.ToString());
                    //if (jar.Count != 0)
                    {
                        
                        //for (int i = 0; i < jar.Count; i++)
                        //{
                        //    TreeNode new_child = new TreeNode();
                        //    new_child.Text = jar[i].ToString();
                        //    nodes.Add(new_child);
                        //}
                    }
                }
                else
                {
                    var node = nodes.Add(item.ToString());
                    node.Tag = new JsonInfo() { name = item.Key.ToString(), value = item.Value.ToString() };
                }
            }
        }
        private void BtnFormat_Click(object sender, EventArgs e)
        {
            string json_text = textEditorControl1.Text;
            treeView1.Nodes.Clear();
            //if (Manager.Json.IsJson(json_text))
            {     
                try
                {
                    textEditorControl1.Document.TextContent = Manager.Json.ConvertJsonString(json_text);
                    textEditorControl1.Refresh();
                    JObject jo = null;
                    if (Manager.Json.IsArray(json_text))
                    {
                        var node2 = treeView1.Nodes.Add("0");
                        JArray jar = JArray.Parse(json_text);
                        ScanArray(node2.Nodes, jar);
                    }
                    else
                    {
                        jo = (JObject)JsonConvert.DeserializeObject(json_text);
                        Scan(treeView1.Nodes, jo);
                    }
                    void Scan(TreeNodeCollection nodes, JObject _jo)
                    {
                        IEnumerable<JProperty> properties = _jo.Properties();
                        foreach (JProperty item in properties)
                        {
                            if (item.Value.Type == JTokenType.Array)
                            {
                                var node2 = nodes.Add(item.Name);
                                node2.Tag = new JsonInfo() { name = item.Name, value = item.Value.ToString() };
                                JArray jar = JArray.Parse(item.Value.ToString());
                                ScanArray(node2.Nodes, jar);
                            }
                            else if (item.Value.Type == JTokenType.Object)
                            {
                                var node2 = nodes.Add(item.Name);
                                node2.Tag = new JsonInfo() { name = item.Name, value = item.Value.ToString() };
                                Scan(node2.Nodes, (JObject)JsonConvert.DeserializeObject(item.Value.ToString()));
                            }
                            else {
                                var node = nodes.Add(item.Name + ":" + item.Value + "|" + item.Value.Type.ToString());
                                node.Tag = new JsonInfo() { name = item.Name, value = item.Value.ToString() };
                            }
                            //Console.WriteLine(item.Name + ":" + item.Value);
                        }
                        //var values = _jo.Values<JProperty>();
                        //foreach (var item in values)
                        //{
                        //    var va = item.Value<JProperty>().Children.Children<JProperty>();
                        //    var node = nodes.Add(item.ToString());
                        //    //if(item.HasValues)
                        //    //Scan(node.Nodes,(JObject)JsonConvert.DeserializeObject(item.ToString()));
                        //}
                    }
                    void ScanArray(TreeNodeCollection nodes, JArray jar)
                    {
                        if (jar != null)
                        {
                            for (int i = 0; i < jar.Count; i++)
                            {
                                var node3 = nodes.Add(i.ToString());
                                if (jar[i].Type == JTokenType.Object)
                                {
                                    Scan(node3.Nodes, (JObject)jar[i]);
                                }
                                else
                                {
                                    node3.Nodes.Add(jar[i].ToString());
                                    node3.Tag = new JsonInfo() { name = jar[i].ToString() };
                                }
                            }
                        }
                    }
                    //if (Manager.Json.IsArray(json_text))
                    //{
                    //    JArray jar = JArray.Parse(json_text);
                    //    if (jar != null)
                    //    {
                    //        for (int i = 0; i < jar.Count; i++)
                    //        {
                    //            var node1 = treeView1.Nodes.Add(i.ToString());
                    //            LoadTreeList(node1.Nodes, (JObject)JsonConvert.DeserializeObject(jar[i].ToString()));
                    //            //TreeNode new_child = new TreeNode();
                    //            //new_child.Text = jar[i].ToString();
                    //            //node.Nodes.Add(new_child);
                    //        }
                    //    }
                    //}
                    //else
                    //{
                    //    jo = (JObject)JsonConvert.DeserializeObject(json_text);
                    //}
                    //LoadTreeList(treeView1.Nodes,jo);
                    //for (int i = 0; i < jo.Count; i++)
                    //{
                    //    treeView1.Nodes.Add(jo..ToString());
                    //}
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            //else
            //{
            //    MessageBox.Show("无效的Json内容", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    textEditorControl1.Document.TextContent = json_text;
            //    textEditorControl1.Refresh();
            //}
        }
        public void LoadJson(string json_text)
        {
            textEditorControl1.Document.TextContent = json_text;
            textEditorControl1.Refresh();
            BtnFormat.PerformClick();
        }
        private void 复制键名ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode == null) { return; }
            JsonInfo item = (JsonInfo)treeView1.SelectedNode.Tag;
            ryCommon.RyFiles.CopyToClip(item.name);
        }

        private void 复制键值ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode == null) { return; }
            if (treeView1.SelectedNode.Tag == null) { return; }
            JsonInfo item = (JsonInfo)treeView1.SelectedNode.Tag;
            ryCommon.RyFiles.CopyToClip(item.value);
        }

        private void BtnPasteJson_Click(object sender, EventArgs e)
        {
            textEditorControl1.BeginUpdate();
            textEditorControl1.Document.TextContent = Clipboard.GetText();
            textEditorControl1.Refresh();
            textEditorControl1.EndUpdate();
            BtnFormat.PerformClick();
        }

        private void BtnCopyJson_Click(object sender, EventArgs e)
        {
            ryCommon.RyFiles.CopyToClip(textEditorControl1.Text);
        }

        private void FrmJson_Load(object sender, EventArgs e)
        {
            textEditorControl1.Document.HighlightingStrategy = HighlightingStrategyFactory.CreateHighlightingStrategy("JSON");
        }

        private void TreeView1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)//判断你点的是不是右键
            {
                Point ClickPoint = new Point(e.X, e.Y);
                TreeNode CurrentNode = treeView1.GetNodeAt(ClickPoint);
                if (CurrentNode != null)//判断你点的是不是一个节点
                {
                    treeView1.SelectedNode = CurrentNode;//选中这个节点
                }
            }
        }

        private void 展开ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            treeView1.ExpandAll();
        }

        private void 折叠ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            treeView1.CollapseAll();
        }

        private void CopyJsonByCHS_Click(object sender, EventArgs e)
        {
            try
            {
                JObject jo = (JObject)JsonConvert.DeserializeObject(textEditorControl1.Text);
                var aa = Newtonsoft.Json.JsonConvert.SerializeObject(jo, new Newtonsoft.Json.JsonSerializerSettings() { StringEscapeHandling = Newtonsoft.Json.StringEscapeHandling.EscapeNonAscii });
                ryCommon.RyFiles.CopyToClip(aa);
            }
            catch(Exception ex) {
                MessageBox.Show(ex.Message, "出错", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void textEditorControl1_TextChanged(object sender, EventArgs e)
        {
            textEditorControl1.Document.FoldingManager.UpdateFoldings(null, null);
        }
    }
    public class JsonInfo
    {
        public string name = "";
        public string value = "";
    }
}
