schangxiang@126.com
2024-11-21 60735779c303c2dd10feea45d7fd761103b225e0
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
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
 
using OfficeOpenXml;
using System.IO.Compression;
 
namespace Admin.NET.Core.Service;
 
/// <summary>
/// 系统代码生成器服务 🧩
/// </summary>
[ApiDescriptionSettings(Order = 270)]
public class SysCodeGenService : IDynamicApiController, ITransient
{
    private readonly ISqlSugarClient _db;
 
    private readonly SysCodeGenConfigService _codeGenConfigService;
    private readonly SysEnumService _sysEnumService;
    private readonly IViewEngine _viewEngine;
    private readonly CodeGenOptions _codeGenOptions;
 
    public SysCodeGenService(ISqlSugarClient db,
        SysCodeGenConfigService codeGenConfigService,
        IViewEngine viewEngine,
        SysEnumService sysEnumService,
        IOptions<CodeGenOptions> codeGenOptions)
    {
        _db = db;
        _codeGenConfigService = codeGenConfigService;
        _sysEnumService = sysEnumService;
        _viewEngine = viewEngine;
        _codeGenOptions = codeGenOptions.Value;
    }
 
    /// <summary>
    /// 获取代码生成分页列表 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取代码生成分页列表")]
    public async Task<SqlSugarPagedList<CodeGenOutput>> Page(CodeGenInput input)
    {
        var ret = await _db.Queryable<SysCodeGen>()
            .WhereIF(!string.IsNullOrWhiteSpace(input.TableName), u => u.TableName.Contains(input.TableName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.BusName), u => u.BusName.Contains(input.BusName.Trim()))
            .Select<CodeGenOutput>()
            .OrderByDescending(x => x.UpdateTime)
            .ToPagedListAsync(input.Page, input.PageSize);
        foreach (var item in ret.Items)
        {
            //单独处理按钮 【Editby shaocx,2024-05-27】
            if (!string.IsNullOrEmpty(item.Buttons))
            {
                item.ButtonsList = item.Buttons.Split(",").ToList();
            }
        }
        return ret;
    }
 
    /// <summary>
    /// 增加代码生成 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    [DisplayName("增加代码生成")]
    public async Task AddCodeGen(AddCodeGenInput input)
    {
        var isExist = await _db.Queryable<SysCodeGen>().Where(u => u.TableName == input.TableName).AnyAsync();
        if (isExist)
            throw Oops.Oh(ErrorCodeEnum.D1400);
 
        var codeGen = input.Adapt<SysCodeGen>();
 
        //单独处理按钮 【Editby shaocx,2024-05-27】
        codeGen.Buttons = string.Join(",", input.ButtonsList);
 
        var newCodeGen = await _db.Insertable(codeGen).ExecuteReturnEntityAsync();
        // 加入配置表中
        _codeGenConfigService.AddList(GetColumnList(input), newCodeGen);
    }
 
    /// <summary>
    /// 更新代码生成 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    [DisplayName("更新代码生成")]
    public async Task UpdateCodeGen(UpdateCodeGenInput input)
    {
        var isExist = await _db.Queryable<SysCodeGen>().AnyAsync(u => u.TableName == input.TableName && u.Id != input.Id);
        if (isExist)
            throw Oops.Oh(ErrorCodeEnum.D1400);
 
        var isExistObj = await _db.Queryable<SysCodeGen>().FirstAsync(u => u.Id == input.Id);
        if (isExistObj == null)
            throw Oops.Oh(ErrorCodeEnum.D1002);
 
        //判断如果生成表变化了,就需要重置配置表 【Editby shaocx,2024-04-13】
        var isChangeTableName = false;
        if (input.TableName != isExistObj.TableName)
        {
            isChangeTableName = true;
        }
 
        var codeGen = input.Adapt<SysCodeGen>();
        if (input.ButtonsList?.Count > 0)
        {
            //单独处理按钮 【Editby shaocx,2024-05-27】
            codeGen.Buttons = string.Join(",", input.ButtonsList);
        }
 
        await _db.Updateable(codeGen).ExecuteCommandAsync();
 
        if (isChangeTableName)
        {
            // 刷新配置表
            await Refresh(input.Id);
        }
    }
 
    /// <summary>
    /// 删除代码生成 🔖
    /// </summary>
    /// <param name="inputs"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    [DisplayName("删除代码生成")]
    public async Task DeleteCodeGen(List<DeleteCodeGenInput> inputs)
    {
        if (inputs == null || inputs.Count < 1) return;
 
        int flag = inputs.First().DelFlag;
        if (flag == 2)
        {//重置配置
            await Refresh(inputs.First().Id);
        }
        else
        {//删除
            var codeGenConfigTaskList = new List<Task>();
            inputs.ForEach(u =>
            {
                _db.Deleteable<SysCodeGen>().In(u.Id).ExecuteCommand();
 
                // 删除配置表中
                codeGenConfigTaskList.Add(_codeGenConfigService.DeleteCodeGenConfig(u.Id));
            });
            await Task.WhenAll(codeGenConfigTaskList);
        }
    }
 
    /// <summary>
    /// 刷新配置表
    /// </summary>
    /// <returns></returns>
    [HttpGet("refresh/{id}")]
    [DisplayName("刷新配置表")]
    public async Task Refresh(long id)
    {
        var item = await _db.Queryable<SysCodeGen>().Where(u => u.Id == id).FirstAsync();
        // 删除配置表中
        await _codeGenConfigService.DeleteCodeGenConfig(id);
        // 加入配置表中
        _codeGenConfigService.AddList(GetColumnList(item.Adapt<AddCodeGenInput>()), item);
    }
 
    /// <summary>
    /// 获取代码生成详情 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取代码生成详情")]
    public async Task<SysCodeGen> GetDetail([FromQuery] QueryCodeGenInput input)
    {
        return await _db.Queryable<SysCodeGen>().SingleAsync(u => u.Id == input.Id);
    }
 
    /// <summary>
    /// 获取数据库库集合 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取数据库库集合")]
    public async Task<List<DatabaseOutput>> GetDatabaseList()
    {
        var dbConfigs = App.GetOptions<DbConnectionOptions>().ConnectionConfigs;
        return await Task.FromResult(dbConfigs.Adapt<List<DatabaseOutput>>());
    }
 
    /// <summary>
    /// 获取数据库表(实体)集合 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取数据库表(实体)集合")]
    public async Task<List<TableOutput>> GetTableList(string configId = SqlSugarConst.MainConfigId)
    {
        var provider = _db.AsTenant().GetConnectionScope(configId);
        var dbTableInfos = provider.DbMaintenance.GetTableInfoList(false); // 不能走缓存,否则切库不起作用
        var dbViewInfos = provider.DbMaintenance.GetViewInfoList(false);// 不能走缓存,否则切库不起作用,增加视图 【Editby shaocx,2024-05-15】
 
        var config = App.GetOptions<DbConnectionOptions>().ConnectionConfigs.FirstOrDefault(u => configId.Equals(u.ConfigId));
 
        var dbTableNames = dbTableInfos.Select(u => u.Name.ToLower()).ToList();
        IEnumerable<EntityInfo> entityInfos = await GetEntityInfos();
 
        var tableOutputList = new List<TableOutput>();
        foreach (var item in entityInfos)
        {
            var table = dbTableInfos.FirstOrDefault(u => u.Name.ToLower() == (config.DbSettings.EnableUnderLine ? UtilMethods.ToUnderLine(item.DbTableName) : item.DbTableName).ToLower());
            if (table != null)
            {
                tableOutputList.Add(new TableOutput
                {
                    ConfigId = configId,
                    EntityName = item.EntityName,
                    TableName = table.Name,
                    TableComment = item.TableDescription
                });
            }
            else
            {//增加视图 【Editby shaocx,2024-05-15】
                var view = dbViewInfos.FirstOrDefault(u => u.Name.ToLower() == (config.DbSettings.EnableUnderLine ? UtilMethods.ToUnderLine(item.DbTableName) : item.DbTableName).ToLower());
                if (view != null)
                {
                    tableOutputList.Add(new TableOutput
                    {
                        ConfigId = configId,
                        EntityName = item.EntityName,
                        TableName = view.Name,
                        TableComment = item.TableDescription
                    });
                }
            }
        }
        return tableOutputList;
    }
 
    /// <summary>
    /// 根据表名获取列集合 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("根据表名获取列集合")]
    public List<ColumnOuput> GetColumnListByTableName([Required] string tableName, string configId = SqlSugarConst.MainConfigId)
    {
        // 切库---多库代码生成用
        var provider = _db.AsTenant().GetConnectionScope(configId);
 
        var config = App.GetOptions<DbConnectionOptions>().ConnectionConfigs.FirstOrDefault(u => u.ConfigId.ToString() == configId);
        // 获取实体类型属性
        var entityType = provider.DbMaintenance.GetTableInfoList(false).FirstOrDefault(u => u.Name == tableName);
        if (entityType == null) return null;
        var entityBasePropertyNames = _codeGenOptions.EntityBaseColumn[nameof(EntityTenant)];
        // 按原始类型的顺序获取所有实体类型属性(不包含导航属性,会返回null)
        return provider.DbMaintenance.GetColumnInfosByTableName(entityType.Name).Select(u => new ColumnOuput
        {
            ColumnName = config.DbSettings.EnableUnderLine ? CodeGenUtil.CamelColumnName(u.DbColumnName, entityBasePropertyNames) : u.DbColumnName,
            ColumnKey = u.IsPrimarykey.ToString(),
            DataType = u.DataType.ToString(),
            NetType = CodeGenUtil.ConvertDataType(u, provider.CurrentConnectionConfig.DbType),
            ColumnComment = u.ColumnDescription
        }).ToList();
    }
 
    /// <summary>
    /// 获取数据表列(实体属性)集合
    /// </summary>
    /// <returns></returns>
    private List<ColumnOuput> GetColumnList([FromQuery] AddCodeGenInput input)
    {
        var entityType = GetEntityInfos().GetAwaiter().GetResult().FirstOrDefault(u => u.EntityName == input.TableName);
        if (entityType == null)
            return null;
        var config = App.GetOptions<DbConnectionOptions>().ConnectionConfigs.FirstOrDefault(u => u.ConfigId.ToString() == input.ConfigId);
        var dbTableName = config.DbSettings.EnableUnderLine ? UtilMethods.ToUnderLine(entityType.DbTableName) : entityType.DbTableName;
 
        // 切库---多库代码生成用
        var provider = _db.AsTenant().GetConnectionScope(!string.IsNullOrEmpty(input.ConfigId) ? input.ConfigId : SqlSugarConst.MainConfigId);
 
        var entityBasePropertyNames = _codeGenOptions.EntityBaseColumn[nameof(EntityTenant)];
        var columnInfos = provider.DbMaintenance.GetColumnInfosByTableName(dbTableName, false);
        var result = columnInfos.Select(u => new ColumnOuput
        {
            // 转下划线后的列名需要再转回来(暂时不转)
            //ColumnName = config.DbSettings.EnableUnderLine ? CodeGenUtil.CamelColumnName(u.DbColumnName, entityBasePropertyNames) : u.DbColumnName,
            ColumnName = u.DbColumnName,
            ColumnLength = u.Length,
            IsPrimarykey = u.IsPrimarykey,
            IsNullable = u.IsNullable,
            ColumnKey = u.IsPrimarykey.ToString(),
            NetType = CodeGenUtil.ConvertDataType(u, provider.CurrentConnectionConfig.DbType),
            DataType = CodeGenUtil.ConvertDataType(u, provider.CurrentConnectionConfig.DbType),
            ColumnComment = string.IsNullOrWhiteSpace(u.ColumnDescription) ? u.DbColumnName : u.ColumnDescription
        }).ToList();
 
        // 获取实体的属性信息,赋值给PropertyName属性(CodeFirst模式应以PropertyName为实际使用名称)
        var entityProperties = entityType.Type.GetProperties();
 
        for (int i = result.Count - 1; i >= 0; i--)
        {
            var columnOutput = result[i];
            // 先找自定义字段名的,如果找不到就再找自动生成字段名的(并且过滤掉没有SugarColumn的属性)
            var propertyInfo = entityProperties.FirstOrDefault(p => (p.GetCustomAttribute<SugarColumn>()?.ColumnName ?? "").ToLower() == columnOutput.ColumnName.ToLower()) ??
                entityProperties.FirstOrDefault(p => p.GetCustomAttribute<SugarColumn>() != null && p.Name.ToLower() == (config.DbSettings.EnableUnderLine
                ? CodeGenUtil.CamelColumnName(columnOutput.ColumnName, entityBasePropertyNames).ToLower()
                : columnOutput.ColumnName.ToLower()));
            if (propertyInfo != null)
            {
                columnOutput.PropertyName = propertyInfo.Name;
                columnOutput.ColumnComment = propertyInfo.GetCustomAttribute<SugarColumn>().ColumnDescription;
                //修改赋值类型 【Editby shaocx,2024-05-10】
                columnOutput.NetType = propertyInfo.PropertyType.ToString();
                //判断是否是枚举类型 【Editby shaocx,2024-05-10】
                if (propertyInfo.PropertyType.IsEnum || propertyInfo.PropertyType.FullName.IndexOf("Enum") > -1)
                {
                    columnOutput.IsEnum = true;
                }
            }
            else
            {
                result.RemoveAt(i); // 移除没有定义此属性的字段
            }
        }
        return result;
    }
 
    /// <summary>
    /// 获取库表信息
    /// </summary>
    /// <returns></returns>
    private async Task<IEnumerable<EntityInfo>> GetEntityInfos()
    {
        var entityInfos = new List<EntityInfo>();
 
        var type = typeof(SugarTable);
        var type_view = typeof(MySugarTableViewAttribute);//增加视图 【Editby shaocx,2024-05-15】
        var types = new List<Type>();
        if (_codeGenOptions.EntityAssemblyNames != null)
        {
            foreach (var assemblyName in _codeGenOptions.EntityAssemblyNames)
            {
                Assembly asm = Assembly.Load(assemblyName);
                types.AddRange(asm.GetExportedTypes().ToList());
            }
        }
        bool IsMyAttribute(Attribute[] o)
        {
            foreach (Attribute a in o)
            {
                if (a.GetType() == type || a.GetType() == type_view)
                    return true;
            }
            return false;
        }
        Type[] cosType = types.Where(o =>
        {
            return IsMyAttribute(Attribute.GetCustomAttributes(o, true));
        }
        ).ToArray();
 
        var _TableName = "";
        var _TableDescription = "";
        foreach (var c in cosType)
        {
            var sugarAttribute = c.GetCustomAttributes(type, true)?.FirstOrDefault();
 
            if (sugarAttribute == null)
            {//增加视图 【Editby shaocx,2024-05-15】
                sugarAttribute = c.GetCustomAttributes(type_view, true)?.FirstOrDefault();
                _TableName = ((MySugarTableViewAttribute)sugarAttribute).TableName;
                _TableDescription = ((MySugarTableViewAttribute)sugarAttribute).TableDescription;
            }
            else
            {
                _TableName = ((SugarTable)sugarAttribute).TableName;
                _TableDescription = ((SugarTable)sugarAttribute).TableDescription;
            }
 
 
            var des = c.GetCustomAttributes(typeof(DescriptionAttribute), true);
            var description = "";
            if (des.Length > 0)
            {
                description = ((DescriptionAttribute)des[0]).Description;
            }
            entityInfos.Add(new EntityInfo()
            {
                EntityName = c.Name,
                DbTableName = sugarAttribute == null ? c.Name : _TableName,
                TableDescription = sugarAttribute == null ? description : _TableDescription,
                Type = c
            });
        }
        return await Task.FromResult(entityInfos);
    }
 
    /// <summary>
    /// 获取程序保存位置 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取程序保存位置")]
    public List<string> GetApplicationNamespaces()
    {
        return _codeGenOptions.BackendApplicationNamespaces;
    }
 
    /// <summary>
    /// 代码生成到本地 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("代码生成到本地")]
    public async Task<dynamic> RunLocal(SysCodeGen input)
    {
        if (string.IsNullOrEmpty(input.GenerateType))
            input.GenerateType = "200";
 
        // 先删除该表已生成的菜单列表
        var templatePathList = GetTemplatePathList(input);
        List<string> targetPathList;
        var zipPath = Path.Combine(App.WebHostEnvironment.WebRootPath, "CodeGen", input.TableName);
        if (input.GenerateType.StartsWith('1'))
        {
            targetPathList = GetZipPathList(input);
            if (Directory.Exists(zipPath))
                Directory.Delete(zipPath, true);
        }
        else
            targetPathList = GetTargetPathList(input);
 
        var tableFieldList = await _codeGenConfigService.GetList(new CodeGenConfig() { CodeGenId = input.Id }); // 字段集合
        var queryWhetherList = tableFieldList.Where(u => u.QueryWhether == YesNoEnum.Y.ToString()).ToList(); // 前端查询集合
        var joinTableList = tableFieldList.Where(u => u.EffectType == "Upload" || u.EffectType == "fk" || u.EffectType == "ApiTreeSelect").ToList(); // 需要连表查询的字段
        (string joinTableNames, string lowerJoinTableNames) = GetJoinTableStr(joinTableList); // 获取连表的实体名和别名
 
        if (input.GenerateType.StartsWith('2'))
        {
            CodeGenUtil.ValidateCodeGenConfig(tableFieldList);
        }
 
        //处理可空类型 【Editby shaocx,2024-04-07】
        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;
        });
 
 
        //获取导入功能自定义模板代码
        StringBuilder templateContent = null;
        templateContent = CreateImportExcelTemplteCode(input, tableFieldList);
 
        var data = new CustomViewEngine(_db)
        {
            ConfigId = input.ConfigId,
            AuthorName = input.AuthorName,
            BusName = input.BusName,
            NameSpace = input.NameSpace,
            ClassName = input.TableName,
            ModuleName = input.ModuleName,
            Buttons = input.Buttons,
            ImportExcelCustomizationContent = templateContent.ToString(),
            ProjectLastName = input.NameSpace.Split('.').Last(),
            QueryWhetherList = queryWhetherList,
            TableField = tableFieldList,
            IsJoinTable = joinTableList.Count > 0,
            IsUpload = joinTableList.Where(u => u.EffectType == "Upload").Any(),
            PrintType = input.PrintType,
            PrintName = input.PrintName,
            TableType = input.TableType,
            KeyQueryStr = string.Join(",", tableFieldList.Where(x => x.WhetherKeyQuery == "Y").Select(x => x.ColumnComment).ToList())
        };
 
        for (var i = 0; i < templatePathList.Count; i++)
        {
            if (data.TableType == "视图" && templatePathList[i].IndexOf("editDialog.vue.vm") > -1) continue;
 
            if (!File.Exists(templatePathList[i])) continue;
            var tContent = File.ReadAllText(templatePathList[i]);
            var tResult = await _viewEngine.RunCompileFromCachedAsync(tContent, data, builderAction: builder =>
            {
                builder.AddAssemblyReferenceByName("System.Linq");
                builder.AddAssemblyReferenceByName("System.Collections");
                builder.AddUsing("System.Collections.Generic");
                builder.AddUsing("System.Linq");
            });
            var dirPath = new DirectoryInfo(targetPathList[i]).Parent.FullName;
            if (!Directory.Exists(dirPath))
                Directory.CreateDirectory(dirPath);
            File.WriteAllText(targetPathList[i], tResult, Encoding.UTF8);
        }
 
        if (!string.IsNullOrEmpty(input.Buttons))
        {//如果没有任何按钮,就不生成菜单 【Editby shaocx,2024-07-31】
            await AddMenu(input, input.TableName, input.BusName, input.MenuPid, tableFieldList, input.ModuleName);
        }
 
        if (input.Buttons.Contains("导入"))
        {
            //创建导入模版
            await CreateImportTemplte(input);
        }
 
        // 非ZIP压缩返回空
        if (!input.GenerateType.StartsWith('1'))
            return null;
        else
        {
            string downloadPath = zipPath + ".zip";
            // 判断是否存在同名称文件
            if (File.Exists(downloadPath))
                File.Delete(downloadPath);
            ZipFile.CreateFromDirectory(zipPath, downloadPath);
            return new { url = $"{App.HttpContext.Request.Scheme}://{App.HttpContext.Request.Host.Value}/CodeGen/{input.TableName}.zip" };
        }
    }
 
    /// <summary>
    /// 获取连表的实体名和别名
    /// </summary>
    /// <param name="configs"></param>
    /// <returns></returns>
    private static (string, string) GetJoinTableStr(List<CodeGenConfig> configs)
    {
        var uploads = configs.Where(u => u.EffectType == "Upload").ToList();
        var fks = configs.Where(u => u.EffectType == "fk").ToList();
        string str = ""; // <Order, OrderItem, Custom>
        string lowerStr = ""; // (o, i, c)
        foreach (var item in uploads)
        {
            lowerStr += "sysFile_FK_" + item.LowerPropertyName + ",";
            str += "SysFile,";
        }
        foreach (var item in fks)
        {
            lowerStr += item.LowerFkEntityName + "_FK_" + item.LowerFkColumnName + ",";
            str += item.FkEntityName + ",";
        }
        return (str.TrimEnd(','), lowerStr.TrimEnd(','));
    }
 
    /// <summary>
    /// 增加菜单
    /// </summary>
    /// <param name="input"></param>
    /// <param name="className"></param>
    /// <param name="busName"></param>
    /// <param name="pid"></param>
    /// <param name="tableFieldList"></param>
    /// <param name="moduleName"></param>
    /// <returns></returns>
    private async Task AddMenu(SysCodeGen input, string className, string busName, long pid, List<CodeGenConfig> tableFieldList, string moduleName)
    {
        var pPath = string.Empty;
        // 若 pid=0 为顶级则创建菜单目录
        if (pid == 0)
        {
            // 目录
            var menuType0 = new SysMenu
            {
                Pid = 0,
                Title = busName,
                Type = MenuTypeEnum.Dir,
                Icon = "robot",
                Path = "/" + className.ToLower(),
                Component = "Layout",
            };
            // 若先前存在则删除本级和下级
            var menuList0 = await _db.Queryable<SysMenu>().Where(u => u.Title == menuType0.Title && u.Type == menuType0.Type).ToListAsync();
            if (menuList0.Count > 0)
            {
                var listIds = menuList0.Select(u => u.Id).ToList();
                var childlistIds = new List<long>();
                foreach (var item in listIds)
                {
                    var childlist = await _db.Queryable<SysMenu>().ToChildListAsync(u => u.Pid, item);
                    childlistIds.AddRange(childlist.Select(u => u.Id).ToList());
                }
                listIds.AddRange(childlistIds);
                await _db.Deleteable<SysMenu>().Where(u => listIds.Contains(u.Id)).ExecuteCommandAsync();
                await _db.Deleteable<SysRoleMenu>().Where(u => listIds.Contains(u.MenuId)).ExecuteCommandAsync();
            }
            pid = (await _db.Insertable(menuType0).ExecuteReturnEntityAsync()).Id;
        }
        else
        {
            var pMenu = await _db.Queryable<SysMenu>().FirstAsync(u => u.Id == pid) ?? throw Oops.Oh(ErrorCodeEnum.D1505);
            pPath = pMenu.Path;
        }
 
        // 菜单
        var menuType1 = new SysMenu
        {
            Pid = pid,
            Title = busName,
            Name = className[..1].ToLower() + className[1..],
            Type = MenuTypeEnum.Menu,
            Path = pPath + "/" + className.ToLower(),
            Component = "/main/" + moduleName + @"/" + className[..1].ToLower() + className[1..] + "/index",
        };
        // 若先前存在则删除本级和下级
        var menuList1 = await _db.Queryable<SysMenu>().Where(u => u.Title == menuType1.Title && u.Type == menuType1.Type).ToListAsync();
        if (menuList1.Count > 0)
        {
            var listIds = menuList1.Select(u => u.Id).ToList();
            var childlistIds = new List<long>();
            foreach (var item in listIds)
            {
                var childlist = await _db.Queryable<SysMenu>().ToChildListAsync(u => u.Pid, item);
                childlistIds.AddRange(childlist.Select(u => u.Id).ToList());
            }
            listIds.AddRange(childlistIds);
            await _db.Deleteable<SysMenu>().Where(u => listIds.Contains(u.Id)).ExecuteCommandAsync();
            await _db.Deleteable<SysRoleMenu>().Where(u => listIds.Contains(u.MenuId)).ExecuteCommandAsync();
        }
 
        var pid1 = (await _db.Insertable(menuType1).ExecuteReturnEntityAsync()).Id;
        int menuOrder = 100;
 
        var menuList = new List<SysMenu>();
 
        if (input.Buttons.Contains("查询"))
        {
            // 按钮-page
            var menuType2 = new SysMenu
            {
                Pid = pid1,
                Title = "查询",
                Type = MenuTypeEnum.Btn,
                Permission = className[..1].ToLower() + className[1..] + ":page",
                OrderNo = menuOrder
            };
            menuOrder += 10;
            menuList.Add(menuType2);
        }
 
        if (input.Buttons.Contains("详情"))
        {
            // 按钮-detail
            var menuType2_1 = new SysMenu
            {
                Pid = pid1,
                Title = "详情",
                Type = MenuTypeEnum.Btn,
                Permission = className[..1].ToLower() + className[1..] + ":detail",
                OrderNo = menuOrder
            };
            menuOrder += 10;
            menuList.Add(menuType2_1);
        }
 
        if (input.Buttons.Contains("新增"))
        {
            // 按钮-add
            var menuType2_2 = new SysMenu
            {
                Pid = pid1,
                Title = "新增",
                Type = MenuTypeEnum.Btn,
                Permission = className[..1].ToLower() + className[1..] + ":add",
                OrderNo = menuOrder
            };
            menuOrder += 10;
            menuList.Add(menuType2_2);
        }
 
        if (input.Buttons.Contains("删除"))
        {
            // 按钮-delete
            var menuType2_3 = new SysMenu
            {
                Pid = pid1,
                Title = "删除",
                Type = MenuTypeEnum.Btn,
                Permission = className[..1].ToLower() + className[1..] + ":delete",
                OrderNo = menuOrder
            };
            menuOrder += 10;
            menuList.Add(menuType2_3);
        }
 
        if (input.Buttons.Contains("编辑"))
        {
            // 按钮-update
            var menuType2_4 = new SysMenu
            {
                Pid = pid1,
                Title = "编辑",
                Type = MenuTypeEnum.Btn,
                Permission = className[..1].ToLower() + className[1..] + ":update",
                OrderNo = menuOrder
            };
            menuOrder += 10;
            menuList.Add(menuType2_4);
        }
 
        if (input.Buttons.Contains("导入"))
        {
            // 按钮-import  【Editby shaocx,2024-05-27】
            var menuType2_5 = new SysMenu
            {
                Pid = pid1,
                Title = "导入",
                Type = MenuTypeEnum.Btn,
                Permission = className[..1].ToLower() + className[1..] + ":importExcel",
                OrderNo = menuOrder
            };
            menuOrder += 10;
            menuList.Add(menuType2_5);
        }
 
        if (input.Buttons.Contains("导出"))
        {
            // 按钮-import  【Editby shaocx,2024-05-27】
            var menuType2_6 = new SysMenu
            {
                Pid = pid1,
                Title = "导出",
                Type = MenuTypeEnum.Btn,
                Permission = className[..1].ToLower() + className[1..] + ":exportExcel",
                OrderNo = menuOrder
            };
            menuOrder += 10;
            menuList.Add(menuType2_6);
        }
 
 
        // 加入fk、Upload、ApiTreeSelect 等接口的权限
        // 在生成表格时,有些字段只是查询时显示,不需要填写(WhetherAddUpdate),所以这些字段没必要生成相应接口
        var fkTableList = tableFieldList.Where(u => u.EffectType == "fk" && (u.WhetherAddUpdate == "Y" || u.QueryWhether == "Y")).ToList();
        foreach (var @column in fkTableList)
        {
            var menuType = new SysMenu
            {
                Pid = pid1,
                Title = "外键" + @column.ColumnName,
                Type = MenuTypeEnum.Btn,
                Permission = className[..1].ToLower() + className[1..] + ":" + column.FkEntityName + column.ColumnName + "Dropdown",
                OrderNo = menuOrder
            };
            menuOrder += 10;
            menuList.Add(menuType);
        }
        var treeSelectTableList = tableFieldList.Where(u => u.EffectType == "ApiTreeSelect").ToList();
        foreach (var @column in treeSelectTableList)
        {
            var menuType = new SysMenu
            {
                Pid = pid1,
                Title = "树型" + @column.ColumnName,
                Type = MenuTypeEnum.Btn,
                Permission = className[..1].ToLower() + className[1..] + ":" + column.FkEntityName + "Tree",
                OrderNo = menuOrder
            };
            menuOrder += 10;
            menuList.Add(menuType);
        }
        var uploadTableList = tableFieldList.Where(u => u.EffectType == "Upload").ToList();
        foreach (var @column in uploadTableList)
        {
            var menuType = new SysMenu
            {
                Pid = pid1,
                Title = "上传" + @column.ColumnName,
                Type = MenuTypeEnum.Btn,
                Permission = className[..1].ToLower() + className[1..] + ":Upload" + column.ColumnName,
                OrderNo = menuOrder
            };
            menuOrder += 10;
            menuList.Add(menuType);
        }
        await _db.Insertable(menuList).ExecuteCommandAsync();
    }
 
 
 
    /// <summary>
    /// 获取模板文件路径集合
    /// </summary>
    /// <returns></returns>
    private static List<string> GetTemplatePathList(SysCodeGen input)
    {
        var templatePath = Path.Combine(App.WebHostEnvironment.WebRootPath, "Template");
        if (input.GenerateType.Substring(1, 1).Contains('1'))
        {
            return new List<string>()
            {
                Path.Combine(templatePath , "index.vue.vm"),
                Path.Combine(templatePath , "editDialog.vue.vm"),
                Path.Combine(templatePath , "manage.js.vm"),
            };
        }
        else if (input.GenerateType.Substring(1, 1).Contains('2'))
        {
            return new List<string>()
            {
                Path.Combine(templatePath , "Service.cs.vm"),
                Path.Combine(templatePath , "Input.cs.vm"),
                Path.Combine(templatePath , "Output.cs.vm"),
                //不再生成Dto.cs文件,这个文件没地方用到 【Editby shaocx,2024-05-22】
                //Path.Combine(templatePath , "Dto.cs.vm"),
            };
        }
        else
        {
            return new List<string>()
            {
                Path.Combine(templatePath , "Service.cs.vm"),
                Path.Combine(templatePath , "Input.cs.vm"),
                Path.Combine(templatePath , "Output.cs.vm"),
                //不再生成Dto.cs文件,这个文件没地方用到 【Editby shaocx,2024-05-22】
                //Path.Combine(templatePath , "Dto.cs.vm"),
                Path.Combine(templatePath , "index.vue.vm"),
                Path.Combine(templatePath , "editDialog.vue.vm"),
                Path.Combine(templatePath , "manage.js.vm"),
            };
        }
    }
 
    /// <summary>
    /// 获取模板文件路径集合
    /// </summary>
    /// <returns></returns>
    private static List<string> GetTemplatePathList()
    {
        var templatePath = Path.Combine(App.WebHostEnvironment.WebRootPath, "Template");
        return new List<string>()
        {
            Path.Combine(templatePath , "Service.cs.vm"),
            Path.Combine(templatePath , "Input.cs.vm"),
            Path.Combine(templatePath , "Output.cs.vm"),
            //不再生成Dto.cs文件,这个文件没地方用到 【Editby shaocx,2024-05-22】
            //Path.Combine(templatePath , "Dto.cs.vm"),
            Path.Combine(templatePath , "index.vue.vm"),
            Path.Combine(templatePath , "editDialog.vue.vm"),
            Path.Combine(templatePath , "manage.js.vm"),
        };
    }
 
    /// <summary>
    /// 设置生成文件路径
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    private List<string> GetTargetPathList(SysCodeGen input)
    {
        //var backendPath = Path.Combine(new DirectoryInfo(App.WebHostEnvironment.ContentRootPath).Parent.FullName, _codeGenOptions.BackendApplicationNamespace, "Service", input.TableName);
        var backendPath = Path.Combine(new DirectoryInfo(App.WebHostEnvironment.ContentRootPath).Parent.FullName, input.NameSpace, "Service", input.ModuleName, input.TableName);
        var servicePath = Path.Combine(backendPath, input.TableName + "Service.cs");
        var inputPath = Path.Combine(backendPath, "Dto", input.TableName + "Input.cs");
        var outputPath = Path.Combine(backendPath, "Dto", input.TableName + "Output.cs");
        //不再生成Dto.cs文件,这个文件没地方用到 【Editby shaocx,2024-05-22】
        //var viewPath = Path.Combine(backendPath, "Dto", input.TableName + "Dto.cs");
        var frontendPath = Path.Combine(new DirectoryInfo(App.WebHostEnvironment.ContentRootPath).Parent.Parent.FullName, _codeGenOptions.FrontRootPath, "src", "views", "main", input.ModuleName);
        var indexPath = Path.Combine(frontendPath, input.TableName[..1].ToLower() + input.TableName[1..], "index.vue");//
        var formModalPath = Path.Combine(frontendPath, input.TableName[..1].ToLower() + input.TableName[1..], "component", "editDialog.vue");
        var apiJsPath = Path.Combine(new DirectoryInfo(App.WebHostEnvironment.ContentRootPath).Parent.Parent.FullName, _codeGenOptions.FrontRootPath, "src", "api", "main", input.ModuleName, input.TableName[..1].ToLower() + input.TableName[1..] + ".ts");
 
        if (input.GenerateType.Substring(1, 1).Contains('1'))
        {
            // 生成到本项目(前端)
            return new List<string>()
            {
                indexPath,
                formModalPath,
                apiJsPath
            };
        }
        else if (input.GenerateType.Substring(1, 1).Contains('2'))
        {
            // 生成到本项目(后端)
            return new List<string>()
            {
                servicePath,
                inputPath,
                outputPath,
                //不再生成Dto.cs文件,这个文件没地方用到 【Editby shaocx,2024-05-22】
                //viewPath,
            };
        }
        else
        {
            // 前后端同时生成到本项目
            return new List<string>()
            {
                servicePath,
                inputPath,
                outputPath,
                //不再生成Dto.cs文件,这个文件没地方用到 【Editby shaocx,2024-05-22】
                //viewPath,
                indexPath,
                formModalPath,
                apiJsPath
            };
        }
    }
 
    /// <summary>
    /// 设置生成文件路径
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    private List<string> GetZipPathList(SysCodeGen input)
    {
        var zipPath = Path.Combine(App.WebHostEnvironment.WebRootPath, "CodeGen", input.TableName);
 
        //var backendPath = Path.Combine(zipPath, _codeGenOptions.BackendApplicationNamespace, "Service", input.TableName);
        var backendPath = Path.Combine(zipPath, input.NameSpace, "Service", input.TableName);
        var servicePath = Path.Combine(backendPath, input.TableName + "Service.cs");
        var inputPath = Path.Combine(backendPath, "Dto", input.TableName + "Input.cs");
        var outputPath = Path.Combine(backendPath, "Dto", input.TableName + "Output.cs");
        //不再生成Dto.cs文件,这个文件没地方用到 【Editby shaocx,2024-05-22】
        //var viewPath = Path.Combine(backendPath, "Dto", input.TableName + "Dto.cs");
        var frontendPath = Path.Combine(zipPath, _codeGenOptions.FrontRootPath, "src", "views", "main");
        var indexPath = Path.Combine(frontendPath, input.TableName[..1].ToLower() + input.TableName[1..], "index.vue");
        var formModalPath = Path.Combine(frontendPath, input.TableName[..1].ToLower() + input.TableName[1..], "component", "editDialog.vue");
        var apiJsPath = Path.Combine(zipPath, _codeGenOptions.FrontRootPath, "src", "api", "main", input.TableName[..1].ToLower() + input.TableName[1..] + ".ts");
        if (input.GenerateType.StartsWith("11"))
        {
            return new List<string>()
            {
                indexPath,
                formModalPath,
                apiJsPath
            };
        }
        else if (input.GenerateType.StartsWith("12"))
        {
            return new List<string>()
            {
                servicePath,
                inputPath,
                outputPath,
                //不再生成Dto.cs文件,这个文件没地方用到 【Editby shaocx,2024-05-22】
                //viewPath
            };
        }
        else
        {
            return new List<string>()
            {
                servicePath,
                inputPath,
                outputPath,
                //不再生成Dto.cs文件,这个文件没地方用到 【Editby shaocx,2024-05-22】
                //viewPath,
                indexPath,
                formModalPath,
                apiJsPath
            };
        }
    }
 
    #region 导入相关
 
    //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 == YesNoEnum.Y.ToString()).ToList(); // 前端查询增改集合
        templateContent.AppendLine("                          ");
        templateContent.AppendLine($"                           var addItem = new {input.TableName}();");
        //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.NetType.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.NetType}  enum{item.ColumnName} = default({item.NetType});");
                templateContent.AppendLine("                          ");
                templateContent.AppendLine($"                             if(!Enum.TryParse<{item.NetType}>(_{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.NetType))
            {
 
 
                templateContent.AppendLine($"                          if(!string.IsNullOrEmpty(_{item.ColumnName}))");
                templateContent.AppendLine("                          {");
                templateContent.AppendLine($"                              if (!{item.NetType}.TryParse(_{item.ColumnName}, out {item.NetType} 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.ToLower() == "datepicker")
                {
                    templateContent.AppendLine($"                                addItem.{item.ColumnName} = Convert.ToDateTime(Convert.ToDateTime(_{item.ColumnName}.Trim()).ToShortDateString());");
                }//日期时间控件
                else if (item.EffectType.ToLower() == "datetimepicker")
                {
                    templateContent.AppendLine($"                                addItem.{item.ColumnName} =   Convert.ToDateTime(_{item.ColumnName}.Trim());");
                }
                else
                {
                    templateContent.AppendLine($"                                addItem.{item.ColumnName} = ({item.NetType})(_{item.ColumnName}.Trim());");
                }
                templateContent.AppendLine("                           }");
            }
 
 
 
 
 
 
 
        }
 
        templateContent.AppendLine("                          #endregion");
        templateContent.AppendLine("                          ");
 
 
 
        return templateContent;
    }
 
    /// <summary>
    /// 根据表名创建导入模版
    /// </summary>
    /// <param name="input"></param>
    private async Task CreateImportTemplte(SysCodeGen input)
    {
        string errMsg = string.Empty;
        //业务名
        string _busName = input.BusName;
        var copayPath = TemplateConst.EXCEL_TEMPLATEFILE_导入模版路径 + "\\CommonTemplate.xlsx";
        string newPath = TemplateConst.EXCEL_TEMPLATEFILE_导入模版路径 + $"\\{_busName}{TemplateConst.EXCEL_TEMPLATEFILE_导入模版名称后缀}.xlsx";
        var tableFieldList = await _codeGenConfigService.GetList(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();
                showCodeGenConfigs = showCodeGenConfigs.Where(x => x.ColumnKey.ToLower() == "false").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($"生成导入模版文件异常,请查看系统日志:" + ex.Message);
        }
        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("");
        _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") ? "必填" : "非必填") + "): ";
            var _dataType = x.DataType.Replace("?", "").ToLower();
            if (effectTypeDict.ContainsKey(x.EffectType.ToLower()))
            {
                text += effectTypeDict[x.EffectType.ToLower()];
            }
            else if (x.EffectType.ToLower() == "enumselector")
            {//注意:这个判断要放在判断_dataType前面,主要是考虑枚举和int类型的混淆
                var queryValue = x.NetType.Split('.').Last();
                var enumStr = _sysEnumService.GetEnumDataListStr(new EnumDataInput() { EnumName = queryValue });
                text += enumStr + "。";
            }
            else if (typeNameDict.ContainsKey(_dataType))
            {
                text += typeNameDict[_dataType];
            }
            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;
    }
 
    #endregion
}