using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;

namespace ReportService.Database
{
    /// <summary>
    /// 报表服务数据库
    /// </summary>
    public partial class RSDbContext:DbContext
    {
        public RSDbContext(DbContextOptions options) : base(options) {
        }

    }

    public static class RSDbContextExend
    {
        /// <summary>
        /// 执行sql查询，返回json格式数据集
        /// </summary>
        /// <param name="db">执行sql语句的数据库上下文</param>
        /// <param name="sql">要执行的sql语句</param>
        /// <returns>Json格式sql语句执行结果</returns>
        public static string SqlJsonQuery(this DbContext db,string sql) => db.Database.SqlJsonQuery(sql);

        /// <summary>
        /// 执行sql查询，返回json格式数据集
        /// </summary>
        /// <param name="db">执行sql语句的数据库上下文</param>
        /// <param name="sql">要执行的sql语句</param>
        /// <returns>Json格式sql语句执行结果</returns>
        public static string SqlJsonQuery(this DatabaseFacade db,string sql) {
            var connection = db.GetDbConnection();
            using(var cmd = connection.CreateCommand()) {
                cmd.CommandText = sql;
                cmd.CommandType = System.Data.CommandType.Text;
                connection.Open();
                var dr = cmd.ExecuteReader();
                var result = new StringBuilder();
                if(!dr.CanGetColumnSchema())
                    return "";
                while(dr.Read()) {
                    var item = new StringBuilder();
                    var columnSchema = dr.GetColumnSchema();
                    for(var i = 0;i < columnSchema.Count;i++) {
                        var name = dr.GetName(i);
                        var value = dr.IsDBNull(i) ? null : dr.GetValue(i);
                        item.Append($"\"{name}\":\"{value}\",");
                    }
                    result.Append($"{{{item.ToString().TrimEnd(',')}}},");
                }
                connection.Close();
                return "[" + result.ToString().TrimEnd(',') + "]";
            }
        }
    }
}
