dengjunjie
2025-03-12 f43b7df8400f4fcffc9f19dca0888d61e2b33d5f
项目代码/WMS/WIDESEA_WMSServer/WIDESEA_Core/BaseServices/ServiceBase.cs
@@ -2,7 +2,9 @@
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;
@@ -13,6 +15,7 @@
using WIDESEA_Core.Enums;
using WIDESEA_Core.Helper;
using WIDESEA_Core.Utilities;
using static OfficeOpenXml.ExcelErrorValue;
namespace WIDESEA_Core.BaseServices
{
@@ -31,7 +34,7 @@
        public ISqlSugarClient Db => BaseDal.Db;
        private PropertyInfo[] _propertyInfo { get; set; } = null;
        private PropertyInfo[] TProperties
        public PropertyInfo[] TProperties
        {
            get
            {
@@ -46,52 +49,19 @@
        public virtual PageGridData<TEntity> GetPageData(PageDataOptions options)
        {
            string wheres = ValidatePageOptions(options);
            string wheres = options.ValidatePageOptions(TProperties);
            //鑾峰彇鎺掑簭瀛楁
            Dictionary<string, OrderByType> orderbyDic = GetPageDataSort(options, TProperties);
            Dictionary<string, OrderByType> orderbyDic = options.GetPageDataSort(TProperties);
            PageGridData<TEntity> pageGridData = new PageGridData<TEntity>();
            //if (QueryRelativeExpression != null)
            //{
            //    queryable = QueryRelativeExpression.Invoke(queryable);
            //}
            //if (options.Export)
            //{
            //    queryable = queryable.GetIQueryableOrderBy(orderbyDic);
            //    if (Limit > 0)
            //    {
            //        queryable = queryable.Take(Limit);
            //    }
            //    pageGridData.rows = queryable.ToList();
            //}
            //else
            //{
            //    pageGridData.rows = repository.IQueryablePage(queryable,
            //                        options.Page,
            //                        options.Rows,
            //                        out int rowCount,
            //                        orderbyDic).ToList();
            //    pageGridData.total = rowCount;
            //    //鏌ヨ鐣岄潰缁熻姹傜瓑瀛楁
            //    if (SummaryExpress != null)
            //    {
            //        pageGridData.summary = SummaryExpress.Invoke(queryable);
            //        //Func<T, T> groupExpress = x =>x;
            //        //pageGridData.summary = queryable.GroupBy(groupExpress).Select(SummaryExpress).FirstOrDefault();
            //    }
            //}
            //GetPageDataOnExecuted?.Invoke(pageGridData);
            pageGridData = BaseDal.QueryPage(wheres, options.Page, options.Rows, orderbyDic);
            return pageGridData;
        }
        protected string ValidatePageOptions(PageDataOptions options)
        public string ValidatePageOptions(PageDataOptions options)
        {
            options = options ?? new PageDataOptions();
            string where = "";
            string text = "";
            List<SearchParameters> searchParametersList = new List<SearchParameters>();
            if (options.Filter != null && options.Filter.Count > 0)
            {
@@ -104,75 +74,51 @@
                    searchParametersList = options.Wheres.DeserializeObject<List<SearchParameters>>();
                    options.Filter = searchParametersList;
                }
                catch { }
                catch
                {
                }
            }
            QueryRelativeList?.Invoke(searchParametersList);
            for (int i = 0; i < searchParametersList.Count; i++)
            base.QueryRelativeList?.Invoke(searchParametersList);
            int i;
            for (i = 0; i < searchParametersList.Count; i++)
            {
                if (string.IsNullOrEmpty(searchParametersList[i].Value))
                {
                    continue;
                }
                PropertyInfo property = TProperties.Where(c => c.Name.ToUpper() == searchParametersList[i].Name.ToUpper()).FirstOrDefault();
                if (property == null) continue;
                (bool, string, object) result = property.ValidationVal(searchParametersList[i].Value.Split(','));
                if (!result.Item1)
                PropertyInfo propertyInfo = TProperties.Where((PropertyInfo c) => c.Name.ToUpper() == searchParametersList[i].Name.ToUpper()).FirstOrDefault();
                if (propertyInfo == null)
                {
                    continue;
                }
                LinqExpressionType expressionType = searchParametersList[i].DisplayType.GetLinqCondition();
                if (expressionType == LinqExpressionType.Equal)
                object[] values = searchParametersList[i].Value.Split(',');
                List<(bool, string, object)> list = propertyInfo.ValidationValueForDbType(values).ToList();
                if (list == null || list.Count() == 0)
                {
                    if (string.IsNullOrEmpty(where))
                        where += $"{searchParametersList[i].Name} = '{searchParametersList[i].Value}'";
                    else
                        where += $" and {searchParametersList[i].Name} = '{searchParametersList[i].Value}'";
                    continue;
                }
                else
                {
                    if (string.IsNullOrEmpty(where))
                        where += $"{searchParametersList[i].Name} {searchParametersList[i].DisplayType} '{searchParametersList[i].Value}'";
                    else
                        where += $" and {searchParametersList[i].Name} {searchParametersList[i].DisplayType} '{searchParametersList[i].Value}'";
                }
            }
            return where;
        }
        /// <summary>
        /// 鑾峰彇鎺掑簭瀛楁
        /// </summary>
        /// <param name="pageData"></param>
        /// <param name="propertyInfo"></param>
        /// <returns></returns>
        private Dictionary<string, OrderByType> GetPageDataSort(PageDataOptions pageData, PropertyInfo[] propertyInfo)
        {
            if (!string.IsNullOrEmpty(pageData.Sort))
            {
                if (pageData.Sort.Contains(","))
                for (int j = 0; j < list.Count(); j++)
                {
                    List<string> sortArr = pageData.Sort.Split(",").Where(x => propertyInfo.Any(p => p.Name == x)).ToList();
                    Dictionary<string, OrderByType> sortDic = new Dictionary<string, OrderByType>();
                    foreach (var item in sortArr)
                    if (j == 0)
                    {
                        sortDic[item] = pageData.Order?.ToLower() == OrderByType.Asc.ToString() ? OrderByType.Asc : OrderByType.Desc;
                        text += "(";
                    }
                    return sortDic;
                    text = ((searchParametersList[i].DisplayType.GetLinqCondition() != 0) ? (text + $"{searchParametersList[i].Name} {searchParametersList[i].DisplayType} '{list[j].Item3}'") : (text + $"{searchParametersList[i].Name} = '{list[j].Item3}'"));
                    text = ((j != list.Count() - 1) ? (text + " or ") : (text + ")"));
                }
                else if (propertyInfo.Any(x => x.Name == pageData.Sort))
                if (i < searchParametersList.Count - 1)
                {
                    return new Dictionary<string, OrderByType> {
                        {
                            pageData.Sort,pageData.Order?.ToLower() == OrderByType.Asc.ToString() ? OrderByType.Asc : OrderByType.Desc
                        } };
                    text += " and ";
                }
            }
            return new Dictionary<string, OrderByType> { { "CreateDate", pageData.Order?.ToLower() == OrderByType.Asc.ToString() ? OrderByType.Asc : OrderByType.Desc } };
            return text;
        }
        public virtual object GetDetailPage(PageDataOptions pageData)
@@ -260,16 +206,15 @@
                }
                else if (keyPro.PropertyType == typeof(int) || keyPro.PropertyType == typeof(long))
                {
                    SugarColumn sugarColumn = keyPro.GetCustomAttribute<SugarColumn>();
                    if (sugarColumn.IsIdentity)
                    SugarColumn? sugarColumn = keyPro.GetCustomAttribute<SugarColumn>();
                    if (sugarColumn?.IsIdentity ?? true)
                    {
                        saveModel.MainData.Remove(keyPro.Name.FirstLetterToUpper());
                        saveModel.MainData.Remove(keyPro.Name.FirstLetterToLower());
                    }
                }
                TEntity entity = saveModel.MainData.DicToModel<TEntity>();
                //if (saveModel.DetailData == null && saveModel.DetailData.Count == 0)
                if (saveModel.DetailData == null )
                if (saveModel.DetailData == null || saveModel.DetailData.Count == 0)
                {
                    BaseDal.AddData(entity);
                    return WebResponseContent.Instance.OK();
@@ -328,7 +273,6 @@
            return content;
        }
        /// <summary>
        /// 淇敼鏁版嵁
        /// </summary>
@@ -377,7 +321,7 @@
                {
                    return WebResponseContent.Instance.Error("浼犲弬閿欒,鍙傛暟涓嶈兘涓虹┖");
                }
                string validResult = typeof(TEntity).ValidateDicInEntity(saveModel.MainData, false, TProperties, list?.ToArray());
                string validResult = typeof(TEntity).ValidateDicInEntity(saveModel.MainData, false, TProperties, list?.ToArray() ?? null);
                if (!string.IsNullOrEmpty(validResult))
                {
@@ -395,7 +339,7 @@
                List<string> listCol = new List<string>();
                foreach (var item in saveModel.MainData)
                {
                    PropertyInfo propertyInfo = typeof(TEntity).GetProperty(item.Key);
                    PropertyInfo? propertyInfo = typeof(TEntity).GetProperty(item.Key);
                    if (propertyInfo == null)
                    {
                        propertyInfo = typeof(TEntity).GetProperty(item.Key.FirstLetterToLower());
@@ -408,12 +352,11 @@
                    listCol.Add(propertyInfo?.Name);
                }
                //if (saveModel.DetailData == null && saveModel.DetailData.Count == 0)
                if (saveModel.DetailData == null)
                if (saveModel.DetailData == null || saveModel.DetailData.Count == 0)
                {
                    if (list != null)
                        listCol = listCol.Where(x => !list.Contains(x)).ToList();
                    bool result = BaseDal.UpdateData(entity, listCol, list);
                    //if (list != null)
                    //    listCol = listCol.Where(x => !list.Contains(x)).ToList();
                    bool result = BaseDal.UpdateData(entity/*, listCol, list*/);
                    return WebResponseContent.Instance.OK();
                }
@@ -512,7 +455,6 @@
            return content;
        }
        /// <summary>
        /// 鍒犻櫎鏁版嵁
        /// </summary>
@@ -540,7 +482,7 @@
            try
            {
                if (typeof(TEntity).GetNavigatePro() == null)
                    return BaseDal.DeleteDataByIds(keys) ? WebResponseContent.Instance.OK("鍒犻櫎鎴愬姛") : WebResponseContent.Instance.Error();
                    return BaseDal.DeleteDataByIds(keys) ? WebResponseContent.Instance.OK() : WebResponseContent.Instance.Error();
                else
                {
                    if (keys != null)
@@ -562,7 +504,7 @@
                        ((SqlSugarClient)BaseDal.Db).CommitTran();
                        return WebResponseContent.Instance.OK("鍒犻櫎鎴愬姛");
                        return WebResponseContent.Instance.OK();
                    }
                    else
                    {
@@ -625,9 +567,9 @@
                string savePath = AppDomain.CurrentDomain.BaseDirectory + $"ExcelExport";
                IExporter exporter = new ExcelExporter();
                string wheres = ValidatePageOptions(options);
                string wheres = options.ValidatePageOptions(TProperties);
                //鑾峰彇鎺掑簭瀛楁
                Dictionary<string, OrderByType> orderbyDic = GetPageDataSort(options, TProperties);
                Dictionary<string, OrderByType> orderbyDic = options.GetPageDataSort(TProperties);
                List<TEntity> entities = BaseDal.QueryData(wheres, orderbyDic);
@@ -726,5 +668,24 @@
            content = WebResponseContent.Instance.OK(data: savePath + "\\" + fileName);
            return content;
        }
        public WebResponseContent ExportSeedData()
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                string seedDataFolder = $"WIDESEA_DB.DBSeed.Json/{typeof(TEntity).Name}.tsv";
                List<TEntity> deviceInfos = BaseDal.QueryData();
                string str = JsonConvert.SerializeObject(deviceInfos, Formatting.Indented);
                List<Dictionary<string, object>> keyValuePairs = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(str);
                FileHelper.WriteFileAndDelOldFile($"{AppDomain.CurrentDomain.BaseDirectory}wwwroot/{seedDataFolder}", str);
                content = WebResponseContent.Instance.OK();
            }
            catch (Exception ex)
            {
                content = WebResponseContent.Instance.Error(ex.Message);
            }
            return content;
        }
    }
}