using AdminDAL.DTO.LockSetting; using AdminDAL.Query.DayLock; using GB5Shared.DTO.Framework.Criteria; using GB5Shared.DTO.Framework.Login; using GB5Shared.QueryExecutor; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using static GB5Shared.GB5Constant.Constant; namespace AdminDAL.CustomCode.DayLock { public class DayLockDAL : IDayLockDAL { private readonly IQueryExecutor queryExecutor; public DayLockDAL(IQueryExecutor IQueryExecutor) { queryExecutor = IQueryExecutor; } public async Task GetSelectListDayLock(CriteriaDTO CriteriaDTO, LoginDTO LoginDTO) { try { int OUId = -1; int LockId = -1; int PeriodId = -1; if (CriteriaDTO?.SectionCriteriaList != null) { foreach (var Section in CriteriaDTO.SectionCriteriaList) { foreach (var Attribute in Section.AttributesCriteriaList ?? new()) { var Value = NormalizeCriteriaValue(Attribute.FieldValue); switch (Attribute.FieldName?.ToLower()) { case "ou.id": if (Value != null) OUId = Convert.ToInt32(Value); break; case "lock.id": if (Value != null) LockId = Convert.ToInt32(Value); break; case "period.id": if (Value != null) PeriodId = Convert.ToInt32(Value); break; } } } } if (OUId == -1) { OUId = LoginDTO.WorkOUId; } string Sql = LoginDTO.DatabaseType switch { DBType.SQL => DayLockQB.GET_SELECTLIST_DAYLOCK, DBType.PostGre => DayLockQB.GET_SELECTLIST_DAYLOCK_PG, _ => throw new NotSupportedException($"Database type '{LoginDTO.DatabaseType}' is not supported.") }; var Parameters = new { ouid = OUId, lockid = LockId, periodid = PeriodId }; var Result = (await queryExecutor.QueryAsync(LoginDTO, Sql, Parameters)).ToList(); return JsonConvert.SerializeObject(Result); } catch (Exception) { throw; } } // CriteriaDTO.FieldValue deserializes as a boxed System.Text.Json.JsonElement — unwrap it // to a native CLR value before using it, otherwise Convert.ToInt32 fails with // "Unable to cast object of type 'JsonElement' to type 'IConvertible'". private static object NormalizeCriteriaValue(object value) { if (value is not System.Text.Json.JsonElement je) return value; return je.ValueKind switch { System.Text.Json.JsonValueKind.String => je.GetString(), System.Text.Json.JsonValueKind.Number => je.TryGetInt32(out var i) ? i : je.GetDouble(), System.Text.Json.JsonValueKind.True => true, System.Text.Json.JsonValueKind.False => false, System.Text.Json.JsonValueKind.Null => null, _ => je.ToString() }; } } }