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

namespace WebAPIBase.NetCore.BusinessCore
{
    public sealed class SqlManager
    {
        private SqlManager()
        {
        }

        public static SqlStruct GetSqlStruct(string className, string sqlStringName)
        {
            return GetSqlStruct(className, className, sqlStringName);
        }

        public static SqlStruct GetSqlStruct(string className, string tableName, string sqlStringName)
        {
            try
            {
                XmlDocument xmlDoc = XmlDefineFileManage.GetXmlDoc(className);
                SqlStruct sqlStruct = new SqlStruct();
                XmlNode documentElement = xmlDoc.DocumentElement;
                XmlNode xmlNode = documentElement.SelectSingleNode("Table[Name='" + tableName + "']");
                if (xmlNode == null)
                {
                    throw new ApplicationException("没有找到表: " + tableName);
                }
                XmlNode xmlNode2 = xmlNode.SelectSingleNode("Sql[Name='" + sqlStringName + "']");
                if (xmlNode2 == null)
                {
                    throw new ApplicationException("没有找到定义的字符串:  " + tableName + "---" + sqlStringName);
                }
                sqlStruct.SqlString = xmlNode2.SelectSingleNode("String").InnerText;
                sqlStruct.CommandType = xmlNode2.SelectSingleNode("CommandType").InnerText;
                XmlNodeList xmlNodeList = xmlNode2.SelectNodes("Param");
                int count = xmlNodeList.Count;
                sqlStruct.ParamsList = new string[count];
                sqlStruct.ColumnsList = new string[count];
                sqlStruct.SqlDbTypeList = new string[count];
                if (count != 0)
                {
                    for (int i = 0; i < count; i++)
                    {
                        sqlStruct.ParamsList[i] = xmlNodeList[i].SelectSingleNode("Name").InnerText;
                        sqlStruct.ColumnsList[i] = xmlNodeList[i].SelectSingleNode("Column").InnerText;
                        sqlStruct.SqlDbTypeList[i] = xmlNodeList[i].SelectSingleNode("SqlDbType").InnerText;
                    }
                }
                XmlNodeList xmlNodeList2 = xmlNode2.SelectNodes("Order");
                int count2 = xmlNodeList2.Count;
                sqlStruct.OrderNameList = new string[count2];
                sqlStruct.OrderSortList = new string[count2];
                for (int j = 0; j < count2; j++)
                {
                    sqlStruct.OrderNameList[j] = xmlNodeList2[j].SelectSingleNode("Name").InnerText;
                    sqlStruct.OrderSortList[j] = xmlNodeList2[j].SelectSingleNode("Sort").InnerText;
                }
                return sqlStruct;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
