using Ewide.Core.Util;
using Ewide.EntityFramework.Core;
using Furion;
using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Ewide.Web.Core.Service
{
    [ApiDescriptionSettings(Name = "DBHandler", Order = 3)]
    public class DBqueryService : IDynamicApiController, ITransient
    {
        private readonly DefaultDbContext _db;

        public DBqueryService(DefaultDbContext db)
        {
            _db = db;
        }
        [HttpGet("/DBreader/detail")]
        [AllowAnonymous]
        public async Task XMLDoneAsync()
        {
#if DEBUG
            XmlSerializerUtil xmlHandler = new XmlSerializerUtil();
            //xmlHandler.WriteDataSeed();
            //拿到数据保存到 XML文件
            Dictionary<string, object> dicDataBase = await GetDataBase();
            foreach (KeyValuePair<string, object> item in dicDataBase)
            {
                xmlHandler.WriteXML(item.Value.GetType(), item.Value, item.Key);
            }
#endif
        }
        /// <summary>
        /// 读取数据库的所有表 并拿到数据
        /// </summary>
        /// <returns></returns>
        private async Task<Dictionary<string, object>> GetDataBase()
        {
            Dictionary<string, object> dicDataBase = new Dictionary<string, object>();
            var defaultConnection = App.Configuration["ConnectionStrings:DefaultConnection"];
            //获取 所有继承 IEntity 接口的表
            IEnumerable<IEntityType> entityTypedb = _db.Model.GetEntityTypes().Where(x => typeof(IEntity).IsAssignableFrom(x.ClrType)).ToList();

            foreach (IEntityType item in entityTypedb)
            {
                MethodInfo mi = _db.GetType().GetMethods().FirstOrDefault(s => s.Name == "Set");
                MethodInfo miConstructed = mi.MakeGenericMethod(item.ClrType);
                object objList = miConstructed.Invoke(_db, null);
                var objsource = item.ClrType.MakeList(objList);
                dicDataBase.Add(item.ClrType.Name, objsource);
            }
            await _db.Database.CloseConnectionAsync();
            return dicDataBase;
        }
    }
}
