using Microsoft.Azure.Cosmos; using Azure.Messaging.ServiceBus; using Microsoft.Azure.Documents; using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.Json; using System.Threading.Tasks; using TEAMModelOS.SDK; using TEAMModelOS.SDK.DI; using TEAMModelOS.SDK.Extension; using TEAMModelOS.SDK.Models; using TEAMModelOS.SDK.Models.Cosmos.Common; using TEAMModelOS.SDK.Models.Service; using TEAMModelOS.SDK.Models.Service.BI; using TEAMModelOS.Function; namespace TEAMModelOS.CosmosDBTriggers { public static class TriggerStudy { public static async Task Trigger(CoreAPIHttpService _coreAPIHttpService, AzureServiceBusFactory _serviceBus, AzureStorageFactory _azureStorage, DingDing _dingDing, CosmosClient client, JsonElement input, TriggerData tdata, AzureRedisFactory _azureRedis, IConfiguration _configuration) { try { if ((tdata.status != null && tdata.status.Value == 404) || tdata.publish == 1) { await client.GetContainer(Constant.TEAMModelOS, "Common").DeleteItemStreamAsync(tdata.id, new Microsoft.Azure.Cosmos.PartitionKey(tdata.code)); ActivityList data = input.ToObject(); //await IESActivityService.DeleteActivity(_coreAPIHttpService, client, _dingDing, data); var table_cancel = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord"); List records = await table_cancel.FindListByDict(new Dictionary() { { "RowKey", tdata.id } }); foreach (var record in records) { try { await table_cancel.DeleteSingle(record.PartitionKey, record.RowKey); await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), record.sequenceNumber); } catch (Exception ) { continue; } } await BIStats.SetTypeAddStats(client, _dingDing, tdata.school, "Study", -1, careDate: tdata.startTime);//BI统计增/减量 return; } var adid = tdata.id; var adcode = ""; string blobcntr = null; if (tdata.scope.Equals("school")) { adcode = $"Activity-{tdata.school}"; blobcntr = tdata.school; } else { adcode = $"Activity-{tdata.creatorId}"; blobcntr = tdata.creatorId; } Study study = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync(tdata.id, new Microsoft.Azure.Cosmos.PartitionKey($"{tdata.code}")); if (study != null) { string PartitionKey = string.Format("{0}{1}{2}", study.code, "-", study.progress); var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord"); List changeRecords = await table.FindListByDict(new Dictionary() { { "RowKey", tdata.id }, { "PartitionKey", PartitionKey } }); switch (study.progress) { case "pending": var messageWork = new ServiceBusMessage(new { id = tdata.id, progress = "going", code = tdata.code }.ToJsonString()); messageWork.ApplicationProperties.Add("name", "Study"); if (changeRecords.Count > 0) { try { await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), changeRecords[0].sequenceNumber); } catch (Exception) { } long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageWork, DateTimeOffset.FromUnixTimeMilliseconds(tdata.startTime)); changeRecords[0].sequenceNumber = start; await table.SaveOrUpdate(changeRecords[0]); } else { long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageWork, DateTimeOffset.FromUnixTimeMilliseconds(tdata.startTime)); ChangeRecord changeRecord = new() { RowKey = tdata.id, PartitionKey = PartitionKey, sequenceNumber = start, msgId = messageWork.MessageId }; await table.Save(changeRecord); } break; case "going": try { List<(string pId, List gid)> ps = new List<(string pId, List gid)>(); if (study.groupLists.Count > 0) { var group = study.groupLists; foreach (var gp in group) { foreach (KeyValuePair> pp in gp) { ps.Add((pp.Key, pp.Value)); } } } (List tchList, List classInfos) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, study.tchLists, study.school, ps); List tchActivities = new List(); (string standard, List tmdids, string school, List update, int statistics) list = (null, null, null, new List { StatisticsService.OfflineRecord }, 0); if (tchList.IsNotEmpty()) { list.tmdids = tchList.Select(x => x.id).ToList(); School school = null; if (!string.IsNullOrEmpty(study.school)) { school = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync(study.school, new Microsoft.Azure.Cosmos.PartitionKey("Base")); list.school = school.id; list.standard = school.standard; } string queryScore = $" select c.id from c where c.id ='{study.id}' and c.pk = 'Activity' "; List ids = new(); await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryStreamIteratorSql (queryText: queryScore)) { using var json = await JsonDocument.ParseAsync(item.Content); if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0) { foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray()) { if (obj.TryGetProperty("id", out JsonElement acId)) { ids.Add(acId.GetString()); } } } } if (ids.Count == 0) { tchList.ForEach(x => { tchActivities.Add(new StuActivity { pk = "Activity", id = study.id, code = $"Activity-{x.id}", type = "Study", name = study.name, startTime = study.startTime, endTime = study.endTime, scode = study.code, scope = study.scope, school = study.school, creatorId = study.creatorId, subjects = new List { "" }, blob = null, owner = study.owner, createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), taskStatus = -1, classIds = study.tchLists }); }); } } await IESActivityService.SaveStuActivity(client, _dingDing, null, null, tchActivities); await StatisticsService.SendServiceBus(list, _configuration, _serviceBus, client); var messageWorkEnd = new ServiceBusMessage(new { id = tdata.id, progress = "finish", code = tdata.code }.ToJsonString()); messageWorkEnd.ApplicationProperties.Add("name", "Study"); if (study.teacIds != null && study.teacIds.Count == 0) { study.teacIds = list.tmdids; await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(study, study.id, new Microsoft.Azure.Cosmos.PartitionKey($"{study.code}")); } if (changeRecords.Count > 0) { long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageWorkEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.endTime)); try { await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), changeRecords[0].sequenceNumber); } catch (Exception) { } changeRecords[0].sequenceNumber = end; await table.SaveOrUpdate(changeRecords[0]); } else { long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageWorkEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.endTime)); ChangeRecord changeRecord = new() { RowKey = tdata.id, PartitionKey = PartitionKey, sequenceNumber = end, msgId = messageWorkEnd.MessageId }; await table.Save(changeRecord); } } catch (Exception ex) { await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}研修活动异常-going {ex.Message}\n{ex.StackTrace}{tdata.ToJsonString()}{input}", GroupNames.醍摩豆服務運維群組); } finally { string pk = string.Format("{0}{1}{2}", study.code, "-", "pending"); await table.DeleteSingle(pk, tdata.id); } break; case "finish": try { List<(string pId, List gid)> gls = new List<(string pId, List gid)>(); if (study.groupLists.Count > 0) { var group = study.groupLists; foreach (var gp in group) { foreach (KeyValuePair> pp in gp) { gls.Add((pp.Key, pp.Value)); } } } //处理教研活动结束统计账户信息 if (study.staffIds.Count == 0) { List idList = await GroupListService.GetFinishMemberInfo(_coreAPIHttpService, client, _dingDing, study.school, study.classes, study.stuLists, study.tchLists, gls); study.staffIds = idList; await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(study, study.id, new Microsoft.Azure.Cosmos.PartitionKey(study.code)); } } catch (Exception e) { await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}研修活动异常-finish {e.Message}\n{e.StackTrace}{tdata.ToJsonString()}{input}", GroupNames.醍摩豆服務運維群組); } finally { string pk = string.Format("{0}{1}{2}", study.code, "-", "going"); await table.DeleteSingle(pk, tdata.id); } break; } } } catch (CosmosException e) { await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-CosmosDB异常{e.Message}\n{e.StackTrace}\n{e.StatusCode}", GroupNames.醍摩豆服務運維群組); } catch (Exception ex) { await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}研修活动异常{ex.Message}\n{ex.StackTrace}{tdata.ToJsonString()}{input}", GroupNames.醍摩豆服務運維群組); } } } }