using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading.Tasks;
using Azure.Cosmos;
using Azure.Messaging.ServiceBus;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
using StackExchange.Redis;
using TEAMModelOS.SDK.DI;
using TEAMModelOS.SDK.Extension;
using TEAMModelOS.SDK.Helper.Common.CollectionHelper;
using TEAMModelOS.SDK.Models;
using TEAMModelOS.SDK.Models.Cosmos.Common;
namespace TEAMModelFunction
{
    public class NoticeServiceBus
    {
        private readonly AzureCosmosFactory _azureCosmos;
        private readonly DingDing _dingDing;
        private readonly AzureStorageFactory _azureStorage;
        private readonly AzureRedisFactory _azureRedis;
        private readonly AzureServiceBusFactory _serviceBus;
        public NoticeServiceBus(AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis, AzureServiceBusFactory serviceBus)
        {
            _azureCosmos = azureCosmos;
            _dingDing = dingDing;
            _azureStorage = azureStorage;
            _azureRedis = azureRedis;
            _serviceBus = serviceBus;
        }
        [FunctionName("Notice")]
        public async Task Notice([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "notice", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
        {
            var client = _azureRedis.GetRedisClient(8);
            try
            {

                // List<Task<string>> tasks = new List<Task<string>>();
                //List<Task> sessionTasks = new List<Task>();
                var jsonMsg = JsonDocument.Parse(msg);
                Notice notice = msg.ToObject<Notice>();
                var blobcntr = "";
                if (notice.scope.Equals("school"))
                {
                    blobcntr = notice.school;
                }
                else
                {
                    blobcntr = notice.creatorId;
                }
                if (string.IsNullOrEmpty(blobcntr))
                {
                    return;
                }
#if DEBUG
                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-NoticeServiceBus-Notice：\n发起通知{msg}", GroupNames.成都开发測試群組);
#endif
                long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                long day30 = 2592000L;
                //处理过期时间大于30天
                if (notice.expire - now > day30) {
                    notice.expire = now + day30;
                }
                //通知的主体内容
                var urlNotice = $"{notice.msgId}.json";
                var blobNotice = new
                {
                    notice.type,
                    notice.priority,
                    notice.from,
                    notice.toservice,
                    notice.creation,//创建时间
                    notice.expire,//到期时间
                    notice.msgId,
                    notice.creatorId,
                    notice.school,
                    notice.scope,
                    notice.body,
                };
                //通知的接收人的集合信息
                await _azureStorage.UploadFileByContainer(blobcntr, blobNotice.ToJsonString(), "notice", urlNotice);
                var urlReceiver = $"{notice.msgId}_receiver.json";
                var blobReceiver = new
                {
                    notice.stuids,
                    notice.tmdids
                };
                await _azureStorage.UploadFileByContainer(blobcntr, blobReceiver.ToJsonString(), "notice", urlReceiver);

                //发送通知给用户
               
                // "ttl":2592000,不能超过30天（2592000），一天（3600），一周（25200）

                if (notice.stuids.IsNotEmpty())
                {
                    //  List<Receiver> receivers = new List<Receiver>();
                    foreach (var stu in notice.stuids)
                    {
                        Receiver receiver = new Receiver
                        {
                            id = notice.msgId,
                            status = 0,
                            ctime = now,
                            urlNotice = $"/notice/{urlNotice}",
                        };
                        var url = $"{stu.id}/receive/{notice.msgId}.json";
                        await client.HashSetAsync($"Notice:Receiver:{stu.schoolId}-{stu.id}", notice.msgId, $"/student/{url}");
                        // await client.GetContainer("TEAMModelOS", "Common").UpsertItemAsync<Receiver>(receiver,new Azure.Cosmos.PartitionKey(receiver.code));
                        //  /student/{stuid}/receive/{notice.sid}.json
                        //存放通知到学生容器空间

                        await _azureStorage.UploadFileByContainer(blobcntr, receiver.ToJsonString(), "student", url);
                        var messageBlob = new ServiceBusMessage(receiver.ToJsonString()) { SessionId = $"{stu.schoolId}-{stu.id}" };
                        // messageBlob.ApplicationProperties.Add("name", "Receiver");
                        await _serviceBus.GetServiceBusClient().SendMessageAsync("notice-task", messageBlob);
                    }
                }
                if (notice.tmdids.IsNotEmpty())
                {
                    foreach (var tmdid in notice.tmdids)
                    {
                        Receiver receiver = new Receiver
                        {
                            id = notice.msgId,
                            status = 0,
                            ctime = now,
                            urlNotice = $"/notice/{urlNotice}",
                        };
                        var url = $"{notice.msgId}.json";
                        await client.HashSetAsync($"Notice:Receiver:{tmdid}", notice.msgId, receiver.ToJsonString());
                        //await client.GetContainer("TEAMModelOS", "Common").UpsertItemAsync<Receiver>(receiver, new Azure.Cosmos.PartitionKey(receiver.code));
                        //  /student/{stuid}/receive/{notice.sid}.json
                        //存放通知到学生容器空间

                        await _azureStorage.UploadFileByContainer(blobcntr, receiver.ToJsonString(), "receive", url);
                        var messageBlob = new ServiceBusMessage(receiver.ToJsonString()) { SessionId = $"{tmdid}" };
                        //messageBlob.ApplicationProperties.Add("name", "Receiver");
                        await _serviceBus.GetServiceBusClient().SendMessageAsync("notice-task", messageBlob);
                    }
                }
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-NoticeServiceBus-Notice\n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
            }
        }

    }
}
