schangxiang@126.com
2024-04-23 f47411fb53aeee0c7bd514cbc841f9030349f448
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
using Admin.NET.Core;
using Admin.NET.Core.Util.LowCode.Front.Code;
using Admin.NET.Core.Util.LowCode.Front.Model;
using Furion;
using Furion.DatabaseAccessor;
using Furion.DatabaseAccessor.Extensions;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.Extras.Admin.NET.Entity;
using Furion.Extras.Admin.NET.Util.LowCode.Front.Code;
using Furion.FriendlyException;
using Furion.ViewEngine;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Newtonsoft.Json;
using OfficeOpenXml.Drawing;
using OfficeOpenXml;
using System;
using System.Text;
using System.Web;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Math;
using OfficeOpenXml.Style;
using System.Net.WebSockets;
using OfficeOpenXml.FormulaParsing.Excel.Functions.RefAndLookup;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using System.Reflection;
using NetTopologySuite.Noding;
using System.Xml.Linq;
using static Npgsql.Replication.PgOutput.Messages.RelationMessage;
using StackExchange.Profiling.Internal;
using System.Collections.Generic;
using System.Data.SqlTypes;
 
namespace Admin.NET.Application.CodeGen
{
    /// <summary>
    /// 代码生成器服务
    /// </summary>
    [Route("api/[Controller]")]
    [ApiDescriptionSettings(Name = "CodeGenerate", Order = 100)]
    public class CodeGenerateService : ICodeGenService, IDynamicApiController, ITransient
    {
        private readonly IRepository<SysCodeGen> _sysCodeGenRep; // 代码生成器仓储
        private readonly IRepository<SysLowCode> _sysLowCodeRep; // 代码生成器仓储
        private readonly ICodeGenConfigService _codeGenConfigService;
        private readonly IViewEngine _viewEngine;
        private readonly ISysExcelTemplateService _sysExcelTemplateService;
        private readonly IRepository<SysMenu> _sysMenuRep; // 菜单表仓储
 
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="sysCodeGenRep"></param>
        /// <param name="sysLowCodeRep"></param>
        /// <param name="codeGenConfigService"></param>
        /// <param name="viewEngine"></param>
        /// <param name="sysMenuRep"></param>
        public CodeGenerateService(IRepository<SysCodeGen> sysCodeGenRep,
                              IRepository<SysLowCode> sysLowCodeRep,
                              ICodeGenConfigService codeGenConfigService,
                              IViewEngine viewEngine,
                              IRepository<SysMenu> sysMenuRep,
            ISysExcelTemplateService sysExcelTemplateService)
        {
            _sysCodeGenRep = sysCodeGenRep;
            _sysLowCodeRep = sysLowCodeRep;
            _codeGenConfigService = codeGenConfigService;
            _viewEngine = viewEngine;
            _sysMenuRep = sysMenuRep;
            _sysExcelTemplateService = sysExcelTemplateService;
        }
 
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("page")]
        public async Task<PageResult<SysCodeGen>> QueryCodeGenPageList([FromQuery] CodeGenPageInput input)
        {
            //if(input.)
            //// 加入配置表中
            //_codeGenConfigService.AddList(GetColumnList(input.Adapt<AddCodeGenInput>()), codeGen);
 
            var tableName = !string.IsNullOrEmpty(input.TableName?.Trim());
            var busName = !string.IsNullOrEmpty(input.BusName?.Trim());
            var codeGens = await _sysCodeGenRep.DetachedEntities
                                               .Where((tableName, u => EF.Functions.Like(u.TableName, $"%{input.TableName.Trim()}%")))
                                               .Where((busName, u => EF.Functions.Like(u.BusName, $"%{input.BusName.Trim()}%")))
                                               .ToADPagedListAsync(input.PageNo, input.PageSize);
            return codeGens;
        }
 
        /// <summary>
        /// 增加
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task AddCodeGen(AddCodeGenInput input)
        {
            var isExist = await _sysCodeGenRep.DetachedEntities.AnyAsync(u => u.TableName == input.TableName);
            if (isExist)
                throw Oops.Oh(ErrorCode.D1400);
 
            if (input.LowCodeId != null && input.LowCodeId > 0)
            {
                isExist = await _sysCodeGenRep.DetachedEntities.AnyAsync(u => u.LowCodeId == input.LowCodeId);
            }
 
            if (!isExist)
            {
                var codeGen = input.Adapt<SysCodeGen>();
                var newCodeGen = await codeGen.InsertNowAsync();
 
                // 加入配置表中
                await _codeGenConfigService.DelAndAddList(GetColumnList(input), newCodeGen.Entity);
            }
        }
 
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="inputs"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public Task DeleteCodeGen(List<DeleteCodeGenInput> inputs)
        {
            if (inputs == null || inputs.Count < 1) return Task.Run(() => { });
 
            var taskList = new List<Task>();
 
            inputs.ForEach(u =>
            {
                taskList.Add(_sysCodeGenRep.DeleteAsync(u.Id));
                // 删除配置表中
                taskList.Add(_codeGenConfigService.Delete(u.Id));
            });
            return Task.WhenAll(taskList);//等待所有任务完成
        }
 
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("edit")]
        public async Task UpdateCodeGen(UpdateCodeGenInput input)
        {
            var isExistObjOther = await _sysCodeGenRep.DetachedEntities.FirstOrDefaultAsync(u => u.TableName == input.TableName && u.Id != input.Id);
            if (isExistObjOther != null)
                throw Oops.Oh(ErrorCode.D1400);
 
            var isExistObj = await _sysCodeGenRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == input.Id);
            if (isExistObj == null)
                throw Oops.Oh(ErrorCode.D1002);
 
            //判断如果生成表变化了,就需要重置配置表 【Editby shaocx,2024-04-13】
            var isChangeTableName = false;
            if (input.TableName != isExistObj.TableName)
            {
                isChangeTableName = true;
            }
 
            var codeGen = input.Adapt<SysCodeGen>();
            await codeGen.UpdateAsync();
 
 
            if (isChangeTableName)
            {
                // 加入配置表中
                await _codeGenConfigService.DelAndAddList(GetColumnList(input.Adapt<AddCodeGenInput>()), codeGen);
            }
        }
 
        /// <summary>
        /// 刷新配置表
        /// </summary>
        /// <returns></returns>
        [HttpGet("refresh/{id}")]
        public void Refresh(long id)
        {
            var item = _sysCodeGenRep.Where(x => x.Id == id).FirstOrDefault();
            // 加入配置表中
            _codeGenConfigService.DelAndAddList(GetColumnList(item.Adapt<AddCodeGenInput>()), item);
        }
 
        /// <summary>
        /// 详情
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("detail")]
        public async Task<SysCodeGen> GetCodeGen([FromQuery] QueryCodeGenInput input)
        {
            return await _sysCodeGenRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == input.Id);
        }
 
        /// <summary>
        /// 获取数据库库集合
        /// </summary>
        /// <returns></returns>
        [HttpGet("DatabaseList")]
        public List<DatabaseOutput> GetDatabaseList()
        {
            var DbContextLocators = AppDomain.CurrentDomain.GetAssemblies()
                        .SelectMany(
                            a => a.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IDbContextLocator)))
                        )
                        .Select(x => new DatabaseOutput { DatabaseName = x.Name, DatabaseComment = x.FullName })
                        .ToList();
 
            return DbContextLocators;
        }
 
        /// <summary>
        /// 获取数据库表(实体)集合
        /// </summary>
        /// <returns></returns>
        [HttpGet("InformationList")]
        public List<TableOutput> GetTableList(string dbContextLocatorName)
        {
            var dbContext = Db.GetDbContext();//默认数据库
            if (!string.IsNullOrEmpty(dbContextLocatorName))
            {
                var dbContentLocator = AppDomain.CurrentDomain.GetAssemblies()
                           .SelectMany(a => a.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IDbContextLocator)))).Where(x => x.Name == dbContextLocatorName).FirstOrDefault();
 
                dbContext = Db.GetDbContext(dbContentLocator);
            }
            // 获取实体类型属性
            //var entityType = dbContext.Model.GetEntityTypes()要改成 var entityType = dbContext.GetService<IDesignTimeModel>().Model.GetEntityTypes()
 
            return dbContext.GetService<IDesignTimeModel>().Model.GetEntityTypes().Select(u => new TableOutput
            {
                DatabaseName = dbContextLocatorName,
                TableName = u.GetDefaultTableName(),
                TableComment = u.GetComment()
            }).ToList();
        }
 
        /// <summary>
        /// 根据表名获取列
        /// </summary>
        /// <returns></returns>
        [HttpGet("ColumnList/{databaseName}/{tableName}")]
        public List<TableColumnOuput> GetColumnListByTableName(string databaseName, string tableName)
        {
            var dbContext = Db.GetDbContext();//默认数据库
            if (!string.IsNullOrEmpty(databaseName))
            {
                var dbContentLocator = AppDomain.CurrentDomain.GetAssemblies()
                           .SelectMany(a => a.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IDbContextLocator)))).Where(x => x.Name == databaseName).FirstOrDefault();
 
                dbContext = Db.GetDbContext(dbContentLocator);
            }
            // 获取实体类型属性
            var entityType = dbContext.GetService<IDesignTimeModel>().Model.GetEntityTypes().FirstOrDefault(u => u.ClrType.Name == tableName);
            if (entityType == null) return null;
 
            // 获取原始类型属性
            var type = entityType.ClrType;
            if (type == null) return null;
 
            // 按原始类型的顺序获取所有实体类型属性(不包含导航属性,会返回null)
            return type.GetProperties().Select(propertyInfo => entityType.FindProperty(propertyInfo.Name))
                       .Where(p => p != null).Select(p => new TableColumnOuput
                       {
                           ColumnName = p.Name,
                           ColumnKey = p.IsKey().ToString(),
                           DataType = p.PropertyInfo.PropertyType.ToString(),
                           NetType = CodeGenUtil.ConvertDataType(p.PropertyInfo.PropertyType.ToString()),
                           ColumnComment = p.GetComment()
                       }).ToList();
        }
 
        /// <summary>
        /// 获取数据表列(实体属性)集合
        /// </summary>
        /// <returns></returns>
        [NonAction]
        public List<TableColumnOuput> GetColumnList([FromQuery] AddCodeGenInput input)
        {
            var dbContext = Db.GetDbContext();//默认数据库
            if (!string.IsNullOrEmpty(input.DatabaseName))
            {
                var dbContentLocator = AppDomain.CurrentDomain.GetAssemblies()
                           .SelectMany(a => a.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IDbContextLocator)))).Where(x => x.Name == input.DatabaseName).FirstOrDefault();
 
                dbContext = Db.GetDbContext(dbContentLocator);
            }
            // 获取实体类型属性
            var entityType = dbContext.GetService<IDesignTimeModel>().Model.GetEntityTypes()
                .FirstOrDefault(u => u.ClrType.Name == input.TableName);
            if (entityType == null) return null;
 
            // 获取原始类型属性
            var type = entityType.ClrType;
            if (type == null) return null;
 
            // 按原始类型的顺序获取所有实体类型属性(不包含导航属性,会返回null)
            return type.GetProperties().Select(propertyInfo => entityType.FindProperty(propertyInfo.Name))
                       .Where(p => p != null)
                       .Select(p => new TableColumnOuput
                       {
                           ColumnName = p.Name,
                           IsNullable = p.IsNullable,
                           ColumnKey = p.IsKey().ToString(),
                           DataType = p.PropertyInfo.PropertyType.ToString(),
                           ColumnComment = p.GetComment()
                       }).ToList();
        }
 
        /// <summary>
        /// 代码生成_本地项目
        /// </summary>
        /// <returns></returns>
        [HttpPost("runLocal")]
        public async Task<dynamic> RunLocal(SysCodeGen input)
        {
            return await CommonRun(input, "200");
        }
 
        /// <summary>
        /// 代码生成_压缩包方式下载
        /// </summary>
        /// <returns></returns>
        [HttpGet("runDown")]
        public async Task<IActionResult> RunDown(long id)
        {
            SysCodeGen input = await _sysCodeGenRep.Where(x => x.Id == id).FirstOrDefaultAsync();
            var ret = await CommonRun(input, "100");
            var _path = App.WebHostEnvironment.WebRootPath + @"\" + ret.url;
 
            var fileName = HttpUtility.UrlEncode($"代码生成({ret.fileName}).zip", Encoding.GetEncoding("UTF-8"));
 
            var path = Path.Combine(_path, "");
            return new FileStreamResult(new FileStream(path, FileMode.Open), "application/octet-stream") { FileDownloadName = fileName };
        }
 
 
        /// <summary>
        /// 代码生成
        /// </summary>
        /// <param name="input"></param>
        /// <param name="curGenerateType">200:生成本地,100:生成本地压缩包</param>
        /// <returns></returns>
        private async Task<dynamic> CommonRun(SysCodeGen input, string curGenerateType)
        {
 
 
 
            var templatePathList = GetTemplatePathList();
            var targetPathList = new List<string>();
            var zipPath = System.IO.Path.Combine(App.WebHostEnvironment.WebRootPath, "CodeGen", input.TableName);
            if (curGenerateType.StartsWith('1'))
            {
                targetPathList = GetZipPathList(input);
                if (Directory.Exists(zipPath))
                    Directory.Delete(zipPath, true);
            }
            else
                targetPathList = GetTargetPathList(input);
 
            var tableFieldList = await _codeGenConfigService.List(new CodeGenConfig() { CodeGenId = input.Id }); // 字段集合
            if (curGenerateType.StartsWith('2'))
            {
                CodeGenHelper.ValidateCodeGenConfig(tableFieldList);
            }
            for (var i = 0; i < templatePathList.Count; i++)
            {
                var tContent = System.IO.File.ReadAllText(templatePathList[i]);
 
                tableFieldList.ForEach(u =>
                {
                    u.NetTypeIsNullLableForQueryInput = "?";
                    u.NetTypeIsNullLableForAddEditOutParam = "";
                    switch (u.NetType.ToLower())
                    {
                        case "int":
                        case "int32":
                        case "long":
                        case "guid":
                        case "decimal":
                        case "datetime":
                        case "datetimeoffset":
                        case "bool": //增加布尔类型的条件 【Editby shaocx,2024-04-07】
                            u.NetTypeIsNullLable = "?";
                            if (u.WhetherRequired != "Y")
                            {
                                u.NetTypeIsNullLableForAddEditOutParam = "?";
                            }
                            break;
                        case "string":
                            u.NetTypeIsNullLableForQueryInput = "";
                            break;
                        default://其他,比如枚举 【Editby shaocx,2024-04-07】
                            if (u.WhetherRequired != "Y")
                            {
                                u.NetTypeIsNullLableForAddEditOutParam = "?";
                            }
                            break;
                    }
                    u.OriginalColumnName = u.ColumnName;
                });
 
                if (i >= 6) // 适应前端首字母小写
                {
                    tableFieldList.ForEach(u =>
                    {
                        u.ColumnName = u.ColumnName.Substring(0, 1).ToLower() + u.ColumnName[1..];
                    });
                }
 
                var queryWhetherList = tableFieldList.Where(u => u.QueryWhether == YesOrNot.Y.ToString()).ToList(); // 前端查询集合
 
                string FormDesign = "";
 
                if (input.LowCodeId != null && input.LowCodeId > 0)
                {
                    FormDesign = _sysLowCodeRep.Where(x => x.Id == input.LowCodeId).Select(x => x.FormDesign).FirstOrDefault();
                }
 
                List<Front_Dynamic> dynamicLoad_dict = new List<Front_Dynamic>();
                Dictionary<string, List<string>> dynamicData = new Dictionary<string, List<string>>();
 
                if (!string.IsNullOrEmpty(FormDesign))
                {
                    try
                    {
                        var AllDynamic = FormDesign.ConvertToFront().AllFront().AllDynamic();
 
                        AllDynamic.Where(x => x.Dynamic).Select(x => x.DynamicKey).ToList().ForEach(item =>
                        {
                            dynamicData.Add(item, new List<string>());
                            var d = item.GetDynamic();
                            if (d != null)
                            {
                                if (d.Head == "dict")
                                {
                                    dynamicLoad_dict.Add(d);
                                }
                            }
                        });
                    }
                    catch { }
                }
 
                try
                {
                    //获取导入功能自定义模板代码
                    StringBuilder templateContent = null;
                    //Service控制器生成导入功能自定义代码   updare by liuwq
                    if (templatePathList[i].IndexOf("Service.cs.vm") >= 0)
                    {
                        templateContent = CreateImportExcelTemplteCode(input, tableFieldList);
                    }
                    var tResult = _viewEngine.RunCompileFromCached(tContent, new
                    {
 
                        input.AuthorName,
                        input.BusName,
                        input.NameSpace,
                        input.ModuleName,//增加模块地址 【Editby shaocx,2024-04-07】
                        input.ProName,
                        input.DatabaseName,
                        input.IsOnlyQuery,
                        input.IsWhetherImport,
                        ClassName = input.TableName,
                        CamelizeClassName = input.TableName.Substring(0, 1).ToLower() + input.TableName[1..], //首字母小写
                        QueryWhetherList = queryWhetherList,
                        TableField = tableFieldList,
                        input.LowCodeId,
                        FormDesign,
                        DynamicData = JsonConvert.SerializeObject(dynamicData),
                        DynamicLoad_Dict = dynamicLoad_dict,
                        IsFile = tableFieldList.Where(x => x.DtoNetType.Contains("Front_FileDto")).Any(),
                        FileTableField = tableFieldList.Where(x => x.DtoNetType.Contains("Front_FileDto")).ToList(),
 
                        ImportExcelCustomizationContent = templateContent?.ToString()//导入功能自定义模板代码
                    }); ;
 
                    var dirPath = new DirectoryInfo(targetPathList[i]).Parent.FullName;
                    if (!Directory.Exists(dirPath))
                        Directory.CreateDirectory(dirPath);
                    System.IO.File.WriteAllText(targetPathList[i], tResult, Encoding.UTF8);
                }
                catch (Exception ex)
                {
                    throw Oops.Oh($"错误模板:{templatePathList[i]}。错误信息:{ex.Message}。");
                }
 
 
 
 
 
 
            }
 
            await AddMenu(input, input.DatabaseName.Substring(0, 5), input.TableName, input.BusName, input.MenuApplication, input.MenuPid, input.ModuleName);
 
            if (input.IsWhetherImport == true)
            {
                //创建导入模版
                await CreateImportTemplte(input);
            }
 
 
 
            // 非ZIP压缩返回空
            if (!curGenerateType.StartsWith('1'))
                return null;
            else
            {
                string downloadPath = zipPath + ".zip";
                // 判断是否存在同名称文件
                if (System.IO.File.Exists(downloadPath))
                    System.IO.File.Delete(downloadPath);
                System.IO.Compression.ZipFile.CreateFromDirectory(zipPath, downloadPath);
                //return new { url = $"{App.HttpContext.Request.Scheme}://{App.HttpContext.Request.Host.Value}/CodeGen/{input.TableName}.zip" };
                return new { url = $@"CodeGen\{input.TableName}.zip", fileName = input.TableName };
            }
        }
 
        //update by liuwq 20240418
        /// <summary>
        /// 创建导入功能自定义模板代码 
        /// </summary>
        /// <param name="input"></param>
        /// <param name="tableFieldList"></param>
        /// <returns></returns>
        private static StringBuilder CreateImportExcelTemplteCode(SysCodeGen input, List<CodeGenConfig> tableFieldList)
        {
            StringBuilder templateContent = new StringBuilder();
            var whetherAddUpdate = tableFieldList.Where(u => u.WhetherAddUpdate == YesOrNot.Y.ToString()).ToList(); // 前端查询增改集合
            templateContent.AppendLine("                          ");
            templateContent.AppendLine($"                           var addItem = new {input.TableName}()");
            templateContent.AppendLine("                            {");
            templateContent.AppendLine("                               CreatedTime = SysHelper.GetNowTime(),");
            templateContent.AppendLine("                               CreatedUserId = SysHelper.GetUserId(),");
            templateContent.AppendLine("                               CreatedUserName = SysHelper.GetUserName(),");
            templateContent.AppendLine("                               UpdatedTime = SysHelper.GetNowTime(),");
            templateContent.AppendLine("                               UpdatedUserId = SysHelper.GetUserId(),");
            templateContent.AppendLine("                               UpdatedUserName = SysHelper.GetUserName()");
            templateContent.AppendLine("                             };");
 
 
            templateContent.AppendLine("                          #region 定义变量");
            foreach (var item in whetherAddUpdate)
            {
                templateContent.AppendLine($"                           var _{item.ColumnName} = \"\";//{item.ColumnComment}");
            }
 
            templateContent.AppendLine("                          #endregion");
            templateContent.AppendLine("                          ");
 
            templateContent.AppendLine("                          ");
            templateContent.AppendLine("                          #region 取值");
            foreach (var item in whetherAddUpdate)
            {
                templateContent.AppendLine($"                           _{item.ColumnName} = row[\"{item.ColumnComment}\"]?.ToString() ;");
            }
 
            templateContent.AppendLine("                          #endregion");
            templateContent.AppendLine("                          ");
 
            templateContent.AppendLine("                          ");
            templateContent.AppendLine("                          #region 验证");
 
            //数值类型验证
            List<string> numericalTypeList = new List<string>()
            {
                "int",
                "long",
                "decimal"
            };
 
 
 
            foreach (var item in whetherAddUpdate)
            {
 
 
                //必填字段验证是否为空
                if (item.WhetherRequired.Equals("Y"))
                {
                    templateContent.AppendLine("                          ");
                    templateContent.AppendLine($"                          if (string.IsNullOrEmpty(_{item.ColumnName}))");
                    templateContent.AppendLine("                          {");
                    templateContent.AppendLine($"                            throw Oops.Oh($\"第{{index}}行[{item.ColumnComment}]{{_{item.ColumnName}}}不能为空!\");");
                    templateContent.AppendLine("                          }");
                    templateContent.AppendLine("                          ");
 
 
                }
 
 
 
 
                //验证值是否有效
 
                //验证bool值
                if (item.DtoNetType.Equals("bool"))
                {
                    templateContent.AppendLine($"                          if(!string.IsNullOrEmpty(_{item.ColumnName}))");
                    templateContent.AppendLine("                          {");
                    templateContent.AppendLine($"                            if(!_{item.ColumnName}.Equals(\"是\") && !_{item.ColumnName}.Equals(\"否\"))");
                    templateContent.AppendLine("                             {");
                    templateContent.AppendLine($"                               throw Oops.Oh($\"第{{index}}行[{item.ColumnComment}]{{_{item.ColumnName}}}值不正确!\");");
                    templateContent.AppendLine("                             }");
                    templateContent.AppendLine("                             else");
                    templateContent.AppendLine("                             {");
                    templateContent.AppendLine($"                               bool out{item.ColumnName} = _{item.ColumnName}.Equals(\"是\") ? true : false;");
                    templateContent.AppendLine($"                               addItem.{item.ColumnName} = out{item.ColumnName};");
                    templateContent.AppendLine("                             }");
                    templateContent.AppendLine("                             }");
                    templateContent.AppendLine("                          ");
 
                }
                //验证枚举值是否有效
                else if (!string.IsNullOrWhiteSpace(item.DictTypeCode))//字典code不为空 是使用枚举值
                {
                    templateContent.AppendLine($"                          if(!string.IsNullOrEmpty(_{item.ColumnName}))");
                    templateContent.AppendLine("                          {");
                    templateContent.AppendLine($"                          {item.DataType}  enum{item.ColumnName} = default({item.DataType});");
                    templateContent.AppendLine("                          ");
                    templateContent.AppendLine($"                             if(!Enum.TryParse<{item.DataType}>(_{item.ColumnName}, out enum{item.ColumnName})&&!string.IsNullOrEmpty(_{item.ColumnName}))");
                    templateContent.AppendLine("                              {");
                    templateContent.AppendLine($"                                throw Oops.Oh($\"第{{index}}行[{item.ColumnComment}]{{_{item.ColumnName}}}值不正确!\");");
                    templateContent.AppendLine("                              }");
                    templateContent.AppendLine("                              else");
                    templateContent.AppendLine("                              {");
                    templateContent.AppendLine($"                                 addItem.{item.ColumnName} = enum{item.ColumnName};");
                    templateContent.AppendLine("                              }");
                    templateContent.AppendLine("                          ");
                    templateContent.AppendLine("                           }");
 
                }//验证数值是否有效
                else if (numericalTypeList.Any(a => a == item.DtoNetType))
                {
 
 
                    templateContent.AppendLine($"                          if(!string.IsNullOrEmpty(_{item.ColumnName}))");
                    templateContent.AppendLine("                          {");
                    templateContent.AppendLine($"                              if (!{item.DtoNetType}.TryParse(_{item.ColumnName}, out {item.DtoNetType} out{item.ColumnName})&&!string.IsNullOrEmpty(_{item.ColumnName}))");
                    templateContent.AppendLine("                              {");
                    templateContent.AppendLine($"                                 throw Oops.Oh($\"第{{index}}行[{item.ColumnComment}]{{_{item.ColumnName}}}值不正确!\");");
                    templateContent.AppendLine("                              }");
                    templateContent.AppendLine($"                              if (out{item.ColumnName} <= 0&&!string.IsNullOrEmpty(_{item.ColumnName}))");
                    templateContent.AppendLine("                              {");
                    templateContent.AppendLine($"                                 throw Oops.Oh($\"第{{index}}行[{item.ColumnComment}]{{_{item.ColumnName}}}值不能小于等于0!\");");
                    templateContent.AppendLine("                              }");
                    templateContent.AppendLine("                              else");
                    templateContent.AppendLine("                              {");
                    templateContent.AppendLine($"                                 addItem.{item.ColumnName} = out{item.ColumnName};");
                    templateContent.AppendLine("                              }");
                    templateContent.AppendLine("                          ");
                    templateContent.AppendLine("                          }");
 
                }
                else
                {
                    templateContent.AppendLine($"                          if(!string.IsNullOrEmpty(_{item.ColumnName}))");
                    templateContent.AppendLine("                          {");
 
                    //日期控件
                    if (item.EffectType == "datepicker")
                    {
                        templateContent.AppendLine($"                                addItem.{item.ColumnName} = Convert.ToDateTime(Convert.ToDateTime(_{item.ColumnName}).ToShortDateString());");
                    }//日期时间控件
                    else if (item.EffectType == "datetimepicker")
                    {
                        templateContent.AppendLine($"                                addItem.{item.ColumnName} =   Convert.ToDateTime(_{item.ColumnName});");
                    }
                    else
                    {
                        templateContent.AppendLine($"                                addItem.{item.ColumnName} = ({item.DtoNetType})_{item.ColumnName};");
                    }
                    templateContent.AppendLine("                           }");
                }
 
 
 
 
 
 
 
            }
 
            templateContent.AppendLine("                          #endregion");
            templateContent.AppendLine("                          ");
 
 
 
            return templateContent;
        }
 
        private async Task AddMenu(SysCodeGen input, string menucodePre, string className, string busName, string application, long pid, string _ModuleName)
        {
            // 定义菜单编码前缀
            var codePrefix = menucodePre + "_" + className.ToLower();//改为取数据库定位器的前五个字母方便区分业务 //"dilon_" + className.ToLower();
 
            // 先删除该表已生成的菜单列表
            var menus = await _sysMenuRep.DetachedEntities.Where(u => u.Code == codePrefix || u.Code.StartsWith(codePrefix + "_")).ToListAsync();
            await _sysMenuRep.DeleteAsync(menus);
 
            // 如果 pid 为 0 说明为顶级菜单, 需要创建顶级目录
            if (pid == 0)
            {
                //解决 选择父级菜单“顶级”会多生成一级菜单的问题 【Editby shaocx,2024-04-13】
                /*
                // 目录
                var menuType0 = new SysMenu
                {
                    Pid = 0,
                    Pids = "[0],",
                    Name = busName + "管理",
                    Code = codePrefix,
                    Type = MenuType.DIR,
                    Icon = "robot",
                    Router = "/" + className.ToLower(),
                    Component = "PageView",
                    Application = application
                };
                pid = _sysMenuRep.InsertNowAsync(menuType0).GetAwaiter().GetResult().Entity.Id;
                //*/
            }
            // 由于后续菜单会有修改, 需要判断下 pid 是否存在, 不存在报错
            else if (!await _sysMenuRep.DetachedEntities.AnyAsync(e => e.Id == pid))
                throw Oops.Oh(ErrorCode.D1505);
 
            // 菜单
            string _pids = "";
            if (pid == 0)
            {
                _pids = "[0],";
            }
            else
            {
                _pids = "[0],[" + pid + "],";
            }
            var menuType1 = new SysMenu
            {
                Pid = pid,
                Pids = _pids,
                Name = busName,
                Code = codePrefix + "_mgr",
                Type = MenuType.MENU,
                Router = "/" + className.ToLower(),
                Component = "main/" + _ModuleName + "/" + className + "/index",//增加 模块地址的配置【Editby shaocx,2024-04-07】
                Application = application,
                OpenType = MenuOpenType.COMPONENT
            };
            var pid1 = _sysMenuRep.InsertNowAsync(menuType1).GetAwaiter().GetResult().Entity.Id;
 
            // 按钮-page
            var menuType2 = new SysMenu
            {
                Pid = pid1,
                Pids = "[0],[" + pid + "],[" + pid1 + "],",
                Name = busName + "查询",
                Code = codePrefix + "_mgr_page",
                Type = MenuType.BTN,
                Permission = className + ":page",
                Application = application,
            }.InsertAsync();
 
            // 按钮-detail
            var menuType2_1 = new SysMenu
            {
                Pid = pid1,
                Pids = "[0],[" + pid + "],[" + pid1 + "],",
                Name = busName + "详情",
                Code = codePrefix + "_mgr_detail",
                Type = MenuType.BTN,
                Permission = className + ":detail",
                Application = application,
            }.InsertAsync();
 
            if (input.IsOnlyQuery != true)
            {
                // 按钮-add
                var menuType2_2 = new SysMenu
                {
                    Pid = pid1,
                    Pids = "[0],[" + pid + "],[" + pid1 + "],",
                    Name = busName + "增加",
                    Code = codePrefix + "_mgr_add",
                    Type = MenuType.BTN,
                    Permission = className + ":add",
                    Application = application,
                }.InsertAsync();
 
                // 按钮-delete
                var menuType2_3 = new SysMenu
                {
                    Pid = pid1,
                    Pids = "[0],[" + pid + "],[" + pid1 + "],",
                    Name = busName + "删除",
                    Code = codePrefix + "_mgr_delete",
                    Type = MenuType.BTN,
                    Permission = className + ":delete",
                    Application = application,
                }.InsertAsync();
 
                // 按钮-edit
                var menuType2_4 = new SysMenu
                {
                    Pid = pid1,
                    Pids = "[0],[" + pid + "],[" + pid1 + "],",
                    Name = busName + "编辑",
                    Code = codePrefix + "_mgr_edit",
                    Type = MenuType.BTN,
                    Permission = className + ":edit",
                    Application = application,
                }.InsertAsync();
 
                //按钮-导入
                if (input.IsWhetherImport == true)
                {
                    var menuType2_6 = new SysMenu
                    {
                        Pid = pid1,
                        Pids = "[0],[" + pid + "],[" + pid1 + "],",
                        Name = busName + "导入excel",
                        Code = codePrefix + "_mgr_import_excel",
                        Type = MenuType.BTN,
                        Permission = className + ":importExcel",
                        Application = application,
                    }.InsertAsync();
                }
 
            }
 
 
            var menuType2_5 = new SysMenu
            {
                Pid = pid1,
                Pids = "[0],[" + pid + "],[" + pid1 + "],",
                Name = busName + "导出excel",
                Code = codePrefix + "_mgr_export_excel",
                Type = MenuType.BTN,
                Permission = className + ":exportExcel",
                Application = application,
            }.InsertAsync();
 
 
        }
 
        /// <summary>
        /// 获取模板文件路径集合
        /// </summary>
        /// <returns></returns>
        private List<string> GetTemplatePathList()
        {
            var templatePath = App.WebHostEnvironment.WebRootPath + @"\Template\";
            return new List<string>()
            {
                templatePath + "Service.cs.vm",
                templatePath + "IService.cs.vm",
                templatePath + "Input.cs.vm",
                templatePath + "Output.cs.vm",
                //不再生成Dto文件 【Editby shaocx,2024-04-20】
                //templatePath + "Dto.cs.vm",
                templatePath + "Mapper.cs.vm",
                templatePath + "index.vue.vm",
                templatePath + "addForm.vue.vm",
                templatePath + "editForm.vue.vm",
                templatePath + "excelForm.vue.vm",
                templatePath + "Manage.js.vm",
            };
        }
 
        /// <summary>
        /// 设置生成文件路径
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private List<string> GetTargetPathList(SysCodeGen input)
        {
            //增加 模块路径的写入 【Editby shaocx,2024-04-07】
            var backendPath = new DirectoryInfo(App.WebHostEnvironment.ContentRootPath).Parent.FullName + @"\" + input.NameSpace + @"\Service\" + input.ModuleName + @"\" + input.TableName + @"\";//后端文件夹父路径
            var servicePath = backendPath + input.TableName + "Service.cs";
            var iservicePath = backendPath + "I" + input.TableName + "Service.cs";
            var inputPath = backendPath + @"Dto\" + input.TableName + "Input.cs";
            var outputPath = backendPath + @"Dto\" + input.TableName + "Output.cs";
            //不再生成Dto文件 【Editby shaocx,2024-04-20】
            //var viewPath = backendPath + @"Dto\" + input.TableName + "Dto.cs";
            var mapperPath = backendPath + @"Map\" + input.TableName + "Mapper.cs";
            //增加 模块路径的写入 【Editby shaocx,2024-04-07】
            var frontendPath = new DirectoryInfo(App.WebHostEnvironment.ContentRootPath).Parent.Parent.FullName + @"\" + input.FrontProName + @"\src\views\main\" + input.ModuleName + @"\";//前端文件夹父路径
            var indexPath = frontendPath + input.TableName + @"\index.vue";
            var addFormPath = frontendPath + input.TableName + @"\addForm.vue";
            var editFormPath = frontendPath + input.TableName + @"\editForm.vue";
            var excelFormPath = frontendPath + input.TableName + @"\excelForm.vue";
            //增加 模块路径的写入 【Editby shaocx,2024-04-07】
            var apiJsPath = new DirectoryInfo(App.WebHostEnvironment.ContentRootPath).Parent.Parent.FullName + @"\" + input.FrontProName + @"\src\api\modular\main\" + input.ModuleName + @"\" + input.TableName + "Manage.js";
 
            return new List<string>()
            {
                servicePath,
                iservicePath,
                inputPath,
                outputPath,
                //不再生成Dto文件 【Editby shaocx,2024-04-20】
                //viewPath,
                mapperPath,
                indexPath,
                addFormPath,
                editFormPath,
                excelFormPath,
                apiJsPath
            };
        }
 
        /// <summary>
        /// 字符串首字母小写
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public string LowercaseFirst(string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return input; // 如果输入为空,则直接返回
            }
 
            char firstChar = char.ToLower(input[0]); // 将第一个字符转换为小写
            string remainder = input.Length > 1 ? input.Substring(1) : ""; // 获取剩余的字符串部分
            return firstChar + remainder; // 返回首字母小写的字符串
        }
 
 
        /// <summary>
        /// 设置生成文件路径
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private List<string> GetZipPathList(SysCodeGen input)
        {
            var zipPath = System.IO.Path.Combine(App.WebHostEnvironment.WebRootPath, "CodeGen", input.TableName);
 
            var backendPath = System.IO.Path.Combine(zipPath, input.NameSpace, "Service", input.ModuleName, input.TableName);//后端文件夹父路径
            var servicePath = System.IO.Path.Combine(backendPath, input.TableName + "Service.cs");
            var iservicePath = System.IO.Path.Combine(backendPath, "I" + input.TableName + "Service.cs");
            var inputPath = System.IO.Path.Combine(backendPath, "Dto", input.TableName + "Input.cs");
            var outputPath = System.IO.Path.Combine(backendPath, "Dto", input.TableName + "Output.cs");
            var viewPath = System.IO.Path.Combine(backendPath, "Dto", input.TableName + "Dto.cs");
            var mapperPath = System.IO.Path.Combine(backendPath, "Dto", input.TableName + "Mapper.cs");
 
 
            var frontendPath = System.IO.Path.Combine(zipPath, input.FrontProName, "src", "views", "main", input.ModuleName, input.TableName);//前端文件夹父路径
            var indexPath = frontendPath + @"\index.vue";
            var addFormPath = frontendPath + @"\addForm.vue";
            var editFormPath = frontendPath + @"\editForm.vue";
            var excelFormPath = frontendPath + @"\excelForm.vue";
            //增加 模块路径的写入 【Editby shaocx,2024-04-07】
            var _apiJsPath = System.IO.Path.Combine(zipPath, input.FrontProName, "src", "api", "modular", "main", input.ModuleName);//前端文件夹父路径
            var apiJsPath = new DirectoryInfo(_apiJsPath) + @"\" + input.TableName + "Manage.js";
 
            return new List<string>()
            {
                servicePath,
                iservicePath,
                inputPath,
                outputPath,
                viewPath,
                mapperPath,
                indexPath,
                addFormPath,
                editFormPath,
                excelFormPath,
                apiJsPath
            };
        }
 
 
        /// <summary>
        /// 根据表名创建导入模版
        /// </summary>
        /// <param name="input"></param>
        private async Task CreateImportTemplte(SysCodeGen input)
        {
            string errMsg = string.Empty;
            //表名
            string tableName = input.TableName;
            var copayPath = TemplateConst.EXCEL_TEMPLATEFILE_导入模版路径 + "\\CommonTemplate.xlsx";
            string newPath = TemplateConst.EXCEL_TEMPLATEFILE_导入模版路径 + $"\\{tableName}{TemplateConst.EXCEL_TEMPLATEFILE_导入模版名称后缀}.xlsx";
            var tableFieldList = await _codeGenConfigService.List(new CodeGenConfig() { CodeGenId = input.Id }); // 字段集合
            CreatExcel(tableFieldList, copayPath, newPath);
        }
 
 
        /// <summary>
        /// 根据实体类名 生成导入excel模版
        /// </summary>
        /// <param name="tableFieldList">代码生成选择配置表的字段</param>
        /// <param name="copayPath"></param>
        /// <param name="newPath"></param>
        private void CreatExcel(List<CodeGenConfig> tableFieldList, string copayPath, string newPath)
        {
            string errMsg = string.Empty;
            try
            {
                #region 验证原始导入模板文件是否存在
                if (!File.Exists(copayPath))
                {
                    errMsg = $"用来复制生成模版的EXCEL文件不存在";
                    throw Oops.Oh($"生成导入模版文件异常:{errMsg}");
                }
                #endregion
 
                //获取模板文件
                FileInfo copyFile = new FileInfo(copayPath);
 
                // 检查新生成的导入模版文件是否存在,存在就删除,以避免可能的异常。
                if (File.Exists(newPath))
                {
                    File.Delete(newPath); // 删除文件
                }
                //复制原始导入模版,创建新的导入模版文件
                copyFile.CopyTo(newPath, true);
                FileInfo existingFile = new FileInfo(newPath);
                using (ExcelPackage package = new ExcelPackage(existingFile))
                {
                    //获取模板内容
                    ExcelWorksheet worksheet = package.Workbook.Worksheets[0];//获取第一个worksheet
                    //行和列都是从1开始,而不是从0开始!!!
                    int _remarkRowIndex = 1;//worksheet 行索引(说明) 注意:默认是第一行是导入模版的说明
                    int _mergeRowCount = _remarkRowIndex;//合并行 (必填字段数量) 默认是第一行合并 
                    int _titleRowIndex = 2;//worksheet 行索引(标题)注意:默认是第一行是导入模版的标题
                    int _cellIndex = 1;//worksheet 列索引 注意:默认是第一列开始设置导入模版的标题
 
                    //模版第一列作为模版使用,所有新增的列样式报错一致
                    var templateCell = worksheet.Cells[_titleRowIndex, _cellIndex];
 
                    string _remark = string.Empty;  //第一行添加说明,注意换行。
 
                    //获取要处理的代码生成配置的是增改的模版字段
                    var showCodeGenConfigs = tableFieldList.Where(w => w.WhetherAddUpdate.Equals("Y")).ToList();
                    int _mergeCellsCount = showCodeGenConfigs.Count();//合并列(模版赋值的标题列数)
                                                                      //获取必填字段
 
                    //创建模版说明
                    StringBuilder _remarkContentBuilder = GetParseTemplateHint(showCodeGenConfigs);
                    string _remarkContent = _remarkContentBuilder.ToString();
 
                    #region 合并单元格
                    //合并单元格,合并行和列。默认是合并第一行的所有标题列
                    var cellRange = worksheet.Cells[1, 1, _mergeRowCount, _mergeCellsCount];
 
                    cellRange.Value = _remarkContent;//合并单元格后的内容赋值
                    var mergeCell = cellRange.Merge = true;//合并
                    int rowHeight = GetRowHeightBasedOnContent(showCodeGenConfigs.Count()); // 根据内容计算行高(这里需要你自己实现逻辑)
                    worksheet.Row(_remarkRowIndex).Height = rowHeight; // 设置行高,注意EPPlus的单位不同,需要转换
 
                    #endregion
 
                    //循环创建模版标题列
                    foreach (var item in showCodeGenConfigs)
                    {
                        var currentCell = worksheet.Cells[_titleRowIndex, _cellIndex];
                        //给新模版列标题赋值
                        currentCell.Value = item.ColumnComment;
                        //复制拷贝的excel模版列,给新模版列样式赋值
                        currentCell.StyleID = templateCell.StyleID;
                        // worksheet.Column(_cellIndex).AutoFit();//宽度自适应
 
                        _cellIndex++;
                    }
 
 
                    package.Save();//保存
                }
            }
            catch (Exception ex)
            {
                throw Oops.Oh($"生成导入模版文件异常,请查看系统日志");
            }
            finally { }
        }
 
 
 
 
 
 
        // 这里是一个假设的方法,用于根据单元格内容计算行高。你需要根据实际情况来实现这个逻辑。
        private static int GetRowHeightBasedOnContent(int lineCount)
        {
            // 这里只是一个示例逻辑,你可能需要更复杂的算法来决定合适的行高。
 
            return (lineCount + 3) * 20; // 
        }
 
 
        private StringBuilder GetParseTemplateHint(List<CodeGenConfig> requiredTableFieldList)
        {
            StringBuilder _remarkContentBuilder = new StringBuilder();
            _remarkContentBuilder.AppendLine("");
            _remarkContentBuilder.AppendLine("1.支持Excel2007及以上版本文件。");
            _remarkContentBuilder.AppendLine("2.导入新增数据时不能超过5000行。");
            _remarkContentBuilder.AppendLine("3.导入更新数据时不能超过2000行。");
            _remarkContentBuilder.AppendLine("");
            _remarkContentBuilder.AppendLine("");
 
            Dictionary<string, string> typeNameDict = new()
            {
                { "string", "文本。"},
                { "int", "数字。"},
                { "long", "数字。"},
                { "decimal", "小数。"},
                { "bool", "布尔。示例:是、否。"},
 
            };
            Dictionary<string, string> effectTypeDict = new()
            {
                { "datepicker", "日期。 示例: 2023/3/1"},
                { "datetimepicker", "日期时间。示例: 2023/3/1 12:00:00"},
 
            };
            requiredTableFieldList.ForEach(x =>
            {
                string text = "";
                text += x.ColumnComment + "(" + (x.WhetherRequired.Equals("Y") ? "必填" : "非必填") + "): ";
                if (effectTypeDict.ContainsKey(x.EffectType))
                {
                    text += effectTypeDict[x.EffectType];
                }
                else if (typeNameDict.ContainsKey(x.DtoNetType))
                {
                    text += typeNameDict[x.DtoNetType];
                }
                else
                {
                    text += ("注意:类型未能识别出来,需要自己维护!!!。");
                }
                _remarkContentBuilder.AppendLine(text);
            });
 
            return _remarkContentBuilder;
 
        }
 
 
 
        /// <summary>
        /// 根据属性名称判断是否是枚举类型
        /// </summary>
        /// <param name="type"></param>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentException"></exception>
        public static bool IsEnumProperty(Type type, string propertyName)
        {
            PropertyInfo propertyInfo = type.GetProperty(propertyName);
            if (propertyInfo == null)
            {
                throw new ArgumentException("Property not found", nameof(propertyName));
            }
            return propertyInfo.PropertyType.IsEnum;
        }
    }
}