using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ICSSoft.ASKDataProject
{
    public class JSON
    {
        /// <summary>
        /// DataSet转Json字符串，"主-子-子"结构
        /// 需要建立主子表关系，第一张表为主表,第二张表为子表，第三张表为子件表
        /// 会排除关联列
        /// </summary>
        /// <param name="dataSet"></param>
        /// <param name="RelationName">关系名称</param>
        /// <returns></returns>
        public static string DataSetToJson(DataSet dataSet, string RelationName, string column, string RelationName2, string column2)
        {
            //if (!dataSet.Tables[0].Columns.Contains(column))
            //{

            //}
            DataRelation dataRelation = new DataRelation(RelationName, dataSet.Tables[0].Columns[column], dataSet.Tables[1].Columns[column]);
            DataRelation dataRelation2 = new DataRelation(RelationName2, dataSet.Tables[1].Columns[column2], dataSet.Tables[2].Columns[column2]);
            dataSet.Relations.Add(dataRelation);
            dataSet.Relations.Add(dataRelation2);

            StringBuilder jsonString = new StringBuilder();
            //foreach (DataTable table in dataSet.Tables)
            //{
            DataTable table = dataSet.Tables[0];
            DataTable table2 = dataSet.Tables[1];

            jsonString.Append("[");
            DataRowCollection drc = table.Rows;
            for (int i = 0; i < drc.Count; i++)
            {
                DataRow dataRow = drc[i];
                jsonString.Append("{");
                for (int j = 0; j < table.Columns.Count; j++)
                {
                    string strKey = table.Columns[j].ColumnName;
                    if (dataSet.Relations[RelationName].ParentColumns.Select(a => a.Caption).Contains(strKey))
                        continue;
                    string strValue = dataRow[j].ToString();
                    Type type = table.Columns[j].DataType;
                    jsonString.Append("\"" + strKey + "\":");
                    strValue = StringFormat(strValue, type);
                    if (j < table.Columns.Count - 1)
                    {
                        jsonString.Append(strValue + ",");
                    }
                    else
                    {
                        jsonString.Append(strValue);
                    }
                }
                jsonString.Append(",\"" + RelationName + "\":");
                DataRow[] drs = dataRow.GetChildRows(RelationName);
                jsonString.Append("[");
                foreach (DataRow dr in drs)
                {
                    DataTable dt = dr.Table;
                    jsonString.Append("{");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        string strKey = dt.Columns[j].ColumnName;
                        if (dataSet.Relations[RelationName].ChildColumns.Select(a => a.Caption).Contains(strKey))
                            continue;
                        string strValue = dr[j].ToString();
                        Type type = dt.Columns[j].DataType;
                        jsonString.Append("\"" + strKey + "\":");
                        strValue = StringFormat(strValue, type);
                        if (j < dt.Columns.Count - 1)
                        {
                            jsonString.Append(strValue + ",");
                        }
                        else
                        {
                            jsonString.Append(strValue);
                        }
                    }

                    ////子件表
                    jsonString.Append(",\"" + RelationName2 + "\":");
                    //DataRowCollection drc2 = table2.Rows;
                    //for (int j = 0; j < drc2.Count; j++)
                    //{
                    //    DataRow dataRow2 = drc2[j];
                    DataRow[] drss = dr.GetChildRows(RelationName2);//取不到值
                    jsonString.Append("[");
                    foreach (DataRow drSec in drss)
                    {
                        DataTable dtSec = drSec.Table;
                        jsonString.Append("{");
                        for (int k = 0; k < dtSec.Columns.Count; k++)
                        {
                            string strKey = dtSec.Columns[k].ColumnName;
                            if (dataSet.Relations[RelationName2].ChildColumns.Select(a => a.Caption).Contains(strKey))
                                continue;
                            string strValue = drSec[k].ToString();
                            Type type = dtSec.Columns[k].DataType;
                            jsonString.Append("\"" + strKey + "\":");
                            strValue = StringFormat(strValue, type);
                            if (k < dtSec.Columns.Count - 1)
                            {
                                jsonString.Append(strValue + ",");
                            }
                            else
                            {
                                jsonString.Append(strValue);
                            }
                        }
                        jsonString.Append("},");
                    }
                    if (drss.Length > 0)
                        jsonString.Remove(jsonString.Length - 1, 1);
                    jsonString.Append("]");//detailss的后方括号

                    jsonString.Append("},");
                }
                if (drs.Length > 0)
                    jsonString.Remove(jsonString.Length - 1, 1);
                jsonString.Append("]");

                jsonString.Append("},");
            }
            jsonString.Remove(jsonString.Length - 1, 1);
            jsonString.Append("]");
            //}
            string res = jsonString.ToString();
            return res;
        }


        /// <summary>
        /// DataSet转Json字符串，主子结构
        /// 需要建立主子表关系，第一张表为主表
        /// 会排除关联列
        /// </summary>
        /// <param name="dataSet"></param>
        /// <param name="RelationName">关系名称</param>
        /// <returns></returns>
        public static string DataSetToJson(DataSet dataSet, string RelationName, string column)
        {
            //if (!dataSet.Tables[0].Columns.Contains(column))
            //{

            //}
            DataRelation dataRelation = new DataRelation(RelationName, dataSet.Tables[0].Columns[column], dataSet.Tables[1].Columns[column]);
            dataSet.Relations.Add(dataRelation);

            StringBuilder jsonString = new StringBuilder();
            //foreach (DataTable table in dataSet.Tables)
            //{
            DataTable table = dataSet.Tables[0];

            jsonString.Append("[");
            DataRowCollection drc = table.Rows;
            for (int i = 0; i < drc.Count; i++)
            {
                DataRow dataRow = drc[i];
                jsonString.Append("{");
                for (int j = 0; j < table.Columns.Count; j++)
                {
                    string strKey = table.Columns[j].ColumnName;
                    if (dataSet.Relations[RelationName].ParentColumns.Select(a => a.Caption).Contains(strKey))
                        continue;
                    string strValue = dataRow[j].ToString();
                    Type type = table.Columns[j].DataType;
                    jsonString.Append("\"" + strKey + "\":");
                    strValue = StringFormat(strValue, type);
                    if (j < table.Columns.Count - 1)
                    {
                        jsonString.Append(strValue + ",");
                    }
                    else
                    {
                        jsonString.Append(strValue);
                    }
                }
                jsonString.Append(",\"" + RelationName + "\":");
                DataRow[] drs = dataRow.GetChildRows(RelationName);
                jsonString.Append("[");
                foreach (DataRow dr in drs)
                {
                    DataTable dt = dr.Table;
                    jsonString.Append("{");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        string strKey = dt.Columns[j].ColumnName;
                        if (dataSet.Relations[RelationName].ChildColumns.Select(a => a.Caption).Contains(strKey))
                            continue;
                        string strValue = dr[j].ToString();
                        Type type = dt.Columns[j].DataType;
                        jsonString.Append("\"" + strKey + "\":");
                        strValue = StringFormat(strValue, type);
                        if (j < dt.Columns.Count - 1)
                        {
                            jsonString.Append(strValue + ",");
                        }
                        else
                        {
                            jsonString.Append(strValue);
                        }
                    }
                    jsonString.Append("},");
                }
                if (drs.Length > 0)
                    jsonString.Remove(jsonString.Length - 1, 1);
                jsonString.Append("]");

                jsonString.Append("},");
            }
            jsonString.Remove(jsonString.Length - 1, 1);
            jsonString.Append("]");
            //}
            string res = jsonString.ToString();
            return res;
        }
        /// <summary>
        /// 格式化字符型、日期型、布尔型
        /// </summary>
        /// <param name="str"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        private static string StringFormat(string str, Type type)
        {
            if (type == typeof(string))
            {
                str = String2Json(str);
                str = "\"" + str + "\"";
            }
            else if (type == typeof(DateTime))
            {
                str = "\"" + str + "\"";
            }
            else if (type == typeof(bool))
            {
                str = str.ToLower();
            }
            else if (type != typeof(string) && string.IsNullOrEmpty(str))
            {
                str = "\"" + str + "\"";
            }
            return str;
        }
        /// <summary>
        /// 过滤特殊字符
        /// </summary>
        /// <param name="s">字符串</param>
        /// <returns>json字符串</returns>
        private static string String2Json(String s)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < s.Length; i++)
            {
                char c = s.ToCharArray()[i];
                switch (c)
                {
                    case '\"':
                        sb.Append("\\\""); break;
                    case '\\':
                        sb.Append("\\\\"); break;
                    case '/':
                        sb.Append("\\/"); break;
                    case '\b':
                        sb.Append("\\b"); break;
                    case '\f':
                        sb.Append("\\f"); break;
                    case '\n':
                        sb.Append("\\n"); break;
                    case '\r':
                        sb.Append("\\r"); break;
                    case '\t':
                        sb.Append("\\t"); break;
                    default:
                        sb.Append(c); break;
                }
            }
            return sb.ToString();
        }
    }
}
