using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Fuel.Application
{
    public class EntityHelper
    {
        public readonly IFreeSql _fsql;

        public EntityHelper(IFreeSql fsql)
        {
            _fsql = fsql;
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="predicate"></param>
        /// <returns></returns>
        public async Task<List<T>> GetEntitiesAsync<T>(Expression<Func<T, bool>> predicate) where T : class
        {
            try
            {
                // 查询满足条件的实体
                return await _fsql.Select<T>().Where(predicate).ToListAsync();
            }
            catch (Exception ex)
            {
            }
            return new List<T>();
        }
        /// <summary>
        /// 插入
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<T> InsertEntityAsync<T>(T entity) where T : class
        {
            try
            {
                // 插入数据
                _fsql.Insert(entity).ExecuteAffrows();

                // 获取插入后的主键值
                object insertedIdObj = _fsql.Ado.ExecuteScalar("SELECT LAST_INSERT_ID();");
                int insertedId = Convert.ToInt32(insertedIdObj);

                // 查询插入后的数据
                return await GetInsertedEntityAsync<T>(insertedId);
            }
            catch (Exception ex)
            {

            }
            return null;
        }
        private async Task<T> GetInsertedEntityAsync<T>(int insertedId) where T : class
        {
            // 获取实体类型
            Type entityType = typeof(T);

            // 获取 Id 属性
            PropertyInfo idProperty = entityType.GetProperty("Id");

            if (idProperty == null)
            {
                throw new InvalidOperationException($"Entity type {entityType.Name} does not have an 'Id' property.");
            }

            // 构建查询条件
            var parameter = Expression.Parameter(entityType, "n");
            var propertyAccess = Expression.MakeMemberAccess(parameter, idProperty);
            var constantValue = Expression.Constant(insertedId, typeof(int));
            var equality = Expression.Equal(propertyAccess, constantValue);
            var lambda = Expression.Lambda<Func<T, bool>>(equality, parameter);

            // 查询插入后的数据
            return await _fsql.Select<T>().Where(lambda).FirstAsync();
        }
    }
}
