hutongqing
2024-12-10 8d341db9d2d5699d527c88c935f0c4ce255a57a4
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
using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
using SqlSugar;
using StackExchange.Profiling;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using WIDESEA_Core.Attributes;
using WIDESEA_Core.CodeConfigEnum;
using WIDESEA_Core.Const;
using WIDESEA_Core.DB;
using WIDESEA_Core.DB.Models;
using WIDESEA_Core.Enums;
using WIDESEA_Core.Helper;
using WIDESEA_Core.Seed;
using WIDESEA_Core.Tenants;
using static Org.BouncyCastle.Math.EC.ECCurve;
 
namespace WIDESEA_Core.AOP
{
    public static class SqlSugarAop
    {
        public static void DataExecuting(object oldValue, DataFilterModel entityInfo)
        {
            if (entityInfo.OperationType == DataFilterType.InsertByObject)
            {
                PropertyInfo propertyInfo = entityInfo.EntityColumnInfo.PropertyInfo;
                CodeRuleAttribute? codeRuleAttribute = propertyInfo.GetCustomAttribute<CodeRuleAttribute>();
                if (codeRuleAttribute != null)
                {
                    SqlSugarClient sugarClient = new SqlSugarClient(new ConnectionConfig
                    {
                        ConfigId = MainDb.CurrentDbConnId,
                        ConnectionString = DBContext.GetMainConnectionDb().Connection,
                        IsAutoCloseConnection = true,
                        DbType = MainDb.DbType,
                    });
                    dynamic ruleConfig = sugarClient.Queryable(MainDb.CodeRuleConfig, "x").Where(nameof(CodeRuleAttribute.RuleCode), "=", codeRuleAttribute.RuleCode.ToString()).First();
                    if (ruleConfig != null)
                    {
                        string code = CreateCodeByRule(ruleConfig, sugarClient);
                        propertyInfo.SetValue(entityInfo.EntityValue, code, null);
                    }
                }
 
                SequenceAttribute? sequenceAttirbute = propertyInfo.GetCustomAttribute<SequenceAttribute>();
                if (sequenceAttirbute != null)
                {
                    if (propertyInfo.GetValue(entityInfo.EntityValue)?.ObjToInt() <= 0)
                    {
                        SqlSugarClient sugarClient = new SqlSugarClient(new ConnectionConfig
                        {
                            ConfigId = MainDb.CurrentDbConnId,
                            ConnectionString = DBContext.GetMainConnectionDb().Connection,
                            IsAutoCloseConnection = true,
                            DbType = MainDb.DbType,
                        });
                        int count = sugarClient.Ado.GetScalar($"SELECT COUNT(*) FROM sys.sequences WHERE name = '{sequenceAttirbute.SequenceName}'").ObjToInt();
                        if (count == 0)
                        {
                            string sql = $"CREATE SEQUENCE {sequenceAttirbute.SequenceName} AS [int] START WITH {sequenceAttirbute.StartWith} INCREMENT BY {sequenceAttirbute.Increment} MINVALUE {sequenceAttirbute.SeqMinValue} MAXVALUE {sequenceAttirbute.SeqMaxValue} {(sequenceAttirbute.IsCycle ? "CYCLE" : "")} CACHE";
                            sugarClient.Ado.ExecuteCommand(sql);
                        }
                        int seq = sugarClient.Ado.GetScalar($"SELECT NEXT VALUE FOR {sequenceAttirbute.SequenceName}").ObjToInt();
                        propertyInfo.SetValue(entityInfo.EntityValue, seq, null);
                    }
                  
                }
            }
 
            if (entityInfo.EntityValue is BaseEntity baseEntity)
            {
                // 新增操作
                if (entityInfo.OperationType == DataFilterType.InsertByObject)
                {
                    if (entityInfo.PropertyName == nameof(BaseEntity.CreateDate))
                    {
                        baseEntity.CreateDate = DateTime.Now;
                    }
                }
 
                if (entityInfo.OperationType == DataFilterType.UpdateByObject)
                {
                    baseEntity.ModifyDate = DateTime.Now;
                }
 
 
                //if (App.User?.UserId > 0)
                {
                    switch (entityInfo.OperationType)
                    {
                        case DataFilterType.UpdateByObject:
                            baseEntity.Modifier = App.User.UserName;
                            break;
                        case DataFilterType.InsertByObject:
                            baseEntity.Creater = App.User.UserName;
                            break;
                    }
                }
            }
        }
 
        private static void UpdateConfigData(dynamic ruleConfig)
        {
            try
            {
 
            }
            catch (Exception ex)
            {
 
            }
        }
 
        private static string CreateCodeByRule(dynamic ruleConfig, SqlSugarClient sugarClient)
        {
            string code = string.Empty;
            DateTime dataTime = DateTime.Now;
            DateTime now = DateTime.Now;
            try
            {
                if (ruleConfig.ModifyDate != null)
                {
                    dataTime = Convert.ToDateTime(ruleConfig.ModifyDate);
                }
                else
                {
                    dataTime = Convert.ToDateTime(ruleConfig.CreateDate);
                }
 
                if (now.Year == dataTime.Year && now.Month == dataTime.Month && now.Day == dataTime.Day)
                {
                    now = dataTime;
                    ruleConfig.CurrentVal = Convert.ToInt32(ruleConfig.CurrentVal) + 1;
                }
                else
                {
                    ruleConfig.CurrentVal = 1;
                }
 
                ruleConfig.ModifyDate = DateTime.Now;
 
                code = ruleConfig.Format;
                code = code.Replace($"[{CodeFormatTypeEnum.YYYY}]", now.Year.ToString().PadLeft(4, '0'));
                code = code.Replace($"[{CodeFormatTypeEnum.MM}]", now.Month.ToString().PadLeft(2, '0'));
                code = code.Replace($"[{CodeFormatTypeEnum.DD}]", now.Day.ToString().PadLeft(2, '0'));
                code = code.Replace($"[{CodeFormatTypeEnum.ST}]", ruleConfig.StartStr.ToString());
                code = code.Replace($"[{CodeFormatTypeEnum.NUM}]", ruleConfig.CurrentVal.ToString().PadLeft(ruleConfig.Length ?? 0, '0'));
            }
            catch (Exception ex)
            {
 
            }
            finally
            {
                Dictionary<string, object> keyValuePairs = new Dictionary<string, object>() { { nameof(ruleConfig.CurrentVal), ruleConfig.CurrentVal }, { nameof(ruleConfig.Id), ruleConfig.Id }, { nameof(ruleConfig.ModifyDate), DateTime.Now } };
                sugarClient.Updateable(keyValuePairs).AS(MainDb.CodeRuleConfig).WhereColumns(nameof(ruleConfig.Id)).ExecuteCommand();
            }
            return code;
        }
 
        private static string GetWholeSql(SugarParameter[] paramArr, string sql)
        {
            foreach (var param in paramArr)
            {
                sql = sql.Replace(param.ParameterName, $@"'{param.Value.ObjToString()}'");
            }
 
            return sql;
        }
 
        private static string GetParas(SugarParameter[] pars)
        {
            string key = "【SQL参数】:";
            foreach (var param in pars)
            {
                key += $"{param.ParameterName}:{param.Value}\n";
            }
 
            return key;
        }
    }
}