hutongqing
2024-12-10 8d341db9d2d5699d527c88c935f0c4ce255a57a4
´úÂë¹ÜÀí/WMS/WIDESEA_WMSServer/WIDESEA_Core/BaseServices/ServiceBase.cs
@@ -1,21 +1,25 @@
using Magicodes.ExporterAndImporter.Core;
using AutoMapper.Execution;
using Magicodes.ExporterAndImporter.Core;
using Magicodes.ExporterAndImporter.Core.Models;
using Magicodes.ExporterAndImporter.Excel;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Text;
using SqlSugar;
using System.Drawing.Drawing2D;
using System.Dynamic;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Metadata;
using WIDESEA_Core.BaseRepository;
using WIDESEA_Core.Const;
using WIDESEA_Core.DB.Models;
using WIDESEA_Core.Enums;
using WIDESEA_Core.Helper;
using WIDESEA_Core.HostedService;
using WIDESEA_Core.Utilities;
using static OfficeOpenXml.ExcelErrorValue;
using ICacheService = WIDESEA_Core.Caches.ICacheService;
namespace WIDESEA_Core.BaseServices
{
@@ -50,15 +54,187 @@
        public virtual PageGridData<TEntity> GetPageData(PageDataOptions options)
        {
            string wheres = options.ValidatePageOptions(TProperties);
            //Expression<Func<TEntity, bool>> test = ValidatePageOptions(options, _propertyInfo);
            //获取排序字段
            Dictionary<string, OrderByType> orderbyDic = options.GetPageDataSort(TProperties);
            PageGridData<TEntity> pageGridData = new PageGridData<TEntity>();
            pageGridData = BaseDal.QueryPage(wheres, options.Page, options.Rows, orderbyDic);
            string dataWheres = GetDataRole(typeof(TEntity));
            if (!string.IsNullOrEmpty(wheres))
            {
                dataWheres += " and ";
            }
            pageGridData = BaseDal.QueryPage(dataWheres + wheres, options.Page, options.Rows, orderbyDic);
            //int count = 0;
            //ISugarQueryable<TEntity> sugarQueryable = BaseDal.Db.Queryable<TEntity>().Where(dataWheres);
            //ValidatePageOptions(options, _propertyInfo, ref sugarQueryable);
            //List<TEntity> rows = sugarQueryable.ToPageList(options.Page, options.Rows, ref count);
            //PageGridData<TEntity> pageGridData = new PageGridData<TEntity>()
            //{
            //    Rows = rows,
            //    Total = count,
            //};
            return pageGridData;
        }
        void ValidatePageOptions(PageDataOptions options, PropertyInfo[] entityProperties, ref ISugarQueryable<TEntity> sugarQueryable)
        {
            string where = string.Empty;
            List<SearchParameters> searchParametersList = new List<SearchParameters>();
            if (options.Filter != null && options.Filter.Count > 0)
            {
                searchParametersList.AddRange(options.Filter);
            }
            else if (!string.IsNullOrEmpty(options.Wheres))
            {
                try
                {
                    searchParametersList = options.Wheres.DeserializeObject<List<SearchParameters>>();
                    options.Filter = searchParametersList;
                }
                catch { }
            }
            for (int i = 0; i < searchParametersList.Count; i++)
            {
                if (string.IsNullOrEmpty(searchParametersList[i].Value))
                {
                    continue;
                }
                PropertyInfo? property = entityProperties.Where(c => c.Name.ToUpper() == searchParametersList[i].Name.ToUpper()).FirstOrDefault();
                if (property == null) continue;
                List<(bool, string, object)> results = property.ValidationValueForDbType(searchParametersList[i].Value.Split(',')).ToList();
                if (results == null || results.Count() == 0)
                {
                    continue;
                }
                for (int j = 0; j < results.Count(); j++)
                {
                    LinqExpressionType expressionType = searchParametersList[i].DisplayType.GetLinqCondition();
                    Expression<Func<TEntity, bool>> expression = GetWhereExpression(property.Name, results[j].Item3, null, expressionType);
                    sugarQueryable = sugarQueryable.Where(expression);
                }
            }
        }
        private Expression<Func<TEntity, bool>> GetWhereExpression(string propertyName, object propertyValue, ParameterExpression parameter, LinqExpressionType expressionType)
        {
            Type proType = typeof(TEntity).GetProperty(propertyName).PropertyType;
            ConstantExpression constant = proType.ToString() == "System.String"
               ? Expression.Constant(propertyValue) : Expression.Constant(propertyValue.ToString().ChangeType(proType));
            // DateTime只选择了日期的时候自动在结束日期加一天,修复DateTime类型使用日期区间查询无法查询到结束日期的问题
            if ((proType == typeof(DateTime) || proType == typeof(DateTime?)) && expressionType == LinqExpressionType.LessThanOrEqual && propertyValue.ToString().Length == 10)
            {
                constant = Expression.Constant(Convert.ToDateTime(propertyValue.ToString()).AddDays(1));
            }
            parameter = parameter ?? Expression.Parameter(typeof(TEntity), "x");
            //创建节点的属性p=>p.name å±žæ€§name
            MemberExpression memberProperty = Expression.PropertyOrField(parameter, propertyName);
            UnaryExpression member = Expression.Convert(memberProperty, constant.Type);
            Expression<Func<TEntity, bool>> expression = p => false;
            switch (expressionType)
            {
                //p=>p.propertyName == propertyValue
                case LinqExpressionType.Equal:
                    expression = Expression.Lambda<Func<TEntity, bool>>(Expression.Equal(member, constant), parameter);
                    break;
                //p=>p.propertyName != propertyValue
                case LinqExpressionType.NotEqual:
                    expression = Expression.Lambda<Func<TEntity, bool>>(Expression.NotEqual(member, constant), parameter);
                    break;
                //   p => p.propertyName > propertyValue
                case LinqExpressionType.GreaterThan:
                    expression = Expression.Lambda<Func<TEntity, bool>>(Expression.GreaterThan(member, constant), parameter);
                    break;
                //   p => p.propertyName < propertyValue
                case LinqExpressionType.LessThan:
                    expression = Expression.Lambda<Func<TEntity, bool>>(Expression.LessThan(member, constant), parameter);
                    break;
                // p => p.propertyName >= propertyValue
                case LinqExpressionType.ThanOrEqual:
                    expression = Expression.Lambda<Func<TEntity, bool>>(Expression.GreaterThanOrEqual(member, constant), parameter);
                    break;
                // p => p.propertyName <= propertyValue
                case LinqExpressionType.LessThanOrEqual:
                    expression = Expression.Lambda<Func<TEntity, bool>>(Expression.LessThanOrEqual(member, constant), parameter);
                    break;
                //   p => p.propertyName.Contains(propertyValue)
                // p => !p.propertyName.Contains(propertyValue)
                case LinqExpressionType.Contains:
                case LinqExpressionType.NotContains:
                    MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
                    constant = Expression.Constant(propertyValue, typeof(string));
                    if (expressionType == LinqExpressionType.Contains)
                    {
                        expression = Expression.Lambda<Func<TEntity, bool>>(Expression.Call(member, method, constant), parameter);
                    }
                    else
                    {
                        expression = Expression.Lambda<Func<TEntity, bool>>(Expression.Not(Expression.Call(member, method, constant)), parameter);
                    }
                    break;
                default:
                    //
                    expression = p => false;
                    break;
            }
            return expression;
        }
        private string GetDataRole(Type type)
        {
            try
            {
                UserRole? userRole = PermissionDataHostService.UserRoles.FirstOrDefault(x => x.UserId == App.User.UserId);
                if (userRole == null)
                    throw new Exception($"无权限");
                if (type.IsAssignableFrom(typeof(BaseWarehouseEntity)) || type.GetProperty(nameof(BaseWarehouseEntity.WarehouseId)) != null)
                {
                    if (userRole.WarehouseIds.Count > 0)
                    {
                        return $"{nameof(BaseWarehouseEntity.WarehouseId)} in ({userRole.WarehouseIds.Serialize().Replace("[", "").Replace("]", "")})";
                    }
                    else
                        return $"1 != 1";
                }
                else
                {
                    return "";
                }
                //UserRole? userRole = PermissionDataHostService.UserRoles.FirstOrDefault(x => x.UserId == App.User.UserId);
                //if (userRole == null)
                //    throw new Exception($"无权限");
                //if (userRole.AuthorityScope == (int)AuthorityScopeEnum.CurrentRole)
                //{
                //    List<int> userId = PermissionDataHostService.UserRoles.Where(x => x.RoleId == userRole.RoleId).Select(x => x.UserId).ToList();
                //    return $"creater in ({userId.Serialize()})";
                //}
                //else if (userRole.AuthorityScope == (int)AuthorityScopeEnum.OnlySelf)
                //{
                //    return $"creater = '{userRole.UserName}'";
                //}
                //else if (userRole.AuthorityScope == (int)AuthorityScopeEnum.None)
                //{
                //    return $"1 != 1";
                //}
                //return "";
            }
            catch (Exception ex)
            {
                throw new Exception($"无权限,{ex.Message}");
            }
        }
        public virtual object GetDetailPage(PageDataOptions pageData)
        {
            Type t = typeof(TEntity);