using Azure.Cosmos;
using Azure.Messaging.ServiceBus;
using Microsoft.Azure.Documents;
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading.Tasks;
using TEAMModelOS.SDK.DI;
using TEAMModelOS.SDK.Extension;
using TEAMModelOS.SDK.Helper.Common.CollectionHelper;
using TEAMModelOS.SDK.Models;
using TEAMModelOS.SDK.Models.Cosmos;

namespace TEAMModelFunction
{
    public static class TriggerCorrect
    {
        public static async void Trigger(AzureServiceBusFactory _serviceBus, AzureStorageFactory _azureStorage, DingDing _dingDing,
           CosmosClient client, Document input, TriggerData tdata, AzureRedisFactory _azureRedis)
        {
            if ((tdata.status != null && tdata.status.Value == 404) || tdata.ttl > 0)
            {
                return;
            }
            var adid = tdata.id;
            var adcode = "";
            string blobcntr = null;
            if (tdata.scope == "school")
            {
                adcode = $"Activity-{tdata.school}";
                blobcntr = tdata.school;
            }
            else {
                return;
            }
            await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}阅卷配置【{tdata.name}-{tdata.id}-ttl={tdata.ttl}】正在执行", GroupNames.成都开发測試群組);
            Correct correct = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<Correct>(input.Id, new Azure.Cosmos.PartitionKey($"{tdata.code}"));
            List<ChangeRecord> correctRecords = await _azureStorage.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", input.Id }, { "PartitionKey", correct.progress } });
            if (correct != null) {
                switch (correct.progress) {
                    case "pending":
                        var messageCorrect = new ServiceBusMessage(new { id = input.Id, progress = "going", code = tdata.code }.ToJsonString());
                        messageCorrect.ApplicationProperties.Add("name", "Correct");
                        if (correctRecords.Count > 0)
                        {
                            long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageCorrect, DateTimeOffset.FromUnixTimeMilliseconds(tdata.stime));
                            await _serviceBus.GetServiceBusClient().cancelMessage(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), correctRecords[0].sequenceNumber);
                            correctRecords[0].sequenceNumber = start;
                            await _azureStorage.SaveOrUpdate<ChangeRecord>(correctRecords[0]);
                        }
                        else
                        {
                            long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageCorrect, DateTimeOffset.FromUnixTimeMilliseconds(tdata.stime));
                            ChangeRecord changeRecord = new ChangeRecord
                            {
                                RowKey = input.Id,
                                PartitionKey = "pending",
                                sequenceNumber = start,
                                msgId = messageCorrect.MessageId
                            };
                            await _azureStorage.Save<ChangeRecord>(changeRecord);
                        }
                        break;
                    case "going":
                        if (correct.subs.IsNotEmpty()) {
                            
                            foreach (var sub in correct.subs) {
                                ///生成阅卷教师的阅卷任务列表
                                if (sub.markers.IsNotEmpty()) {
                                    foreach (var marker in sub.markers) {
                                        CorrectTask task = new CorrectTask
                                        {
                                            ttl = -1,
                                            pk= "CorrectTask",
                                            code = "CorrectTask-" + marker.id,
                                            //评测id 或者阅卷配置id
                                            id = correct.id,
                                            //科目
                                            subject=sub.id,
                                            //科目名称
                                            subjectName=sub.name,
                                            //评测code
                                            ecode=correct.scode,
                                            //阅卷配置code
                                            scode=correct.code,
                                            //任务名称
                                            name=correct.name,
                                            //开始时间
                                            startTime=correct.startTime,
                                            //结束时间
                                            endTime=correct.endTime,
                                            //批改数量
                                            count=marker.count
                                        };
                                       await  client.GetContainer("TEAMModelOS", "Teacher").UpsertItemAsync<CorrectTask>(task,new Azure.Cosmos.PartitionKey(task.code));
                                    }
                                }
                                //生成异常卷处理人员
                                //生成仲裁人员
                                //调用本次考试所涉及的所有已经作答的数据 并生成阅卷池，存入redis
                                //评测id
                                string eid = correct.id;
                                //评测的分区键
                                string ecode = correct.scode;
                                //评测科目
                                string subjectId = sub.id;
                                //生成临时作答数据存放到redis
                                var redisClient = _azureRedis.GetRedisClient(8);
                                ExamInfo info = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(eid, new Azure.Cosmos.PartitionKey(ecode));
                                List<ExamClassResult> classResults = new List<ExamClassResult>();

                                if (info.scope.Equals("school"))
                                {

                                    await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamClassResult>(
                                    queryText: $"select value(c) from c where c.examId = '{eid}' and c.subjectId = '{subjectId}'",
                                    requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"ExamClassResult-{info.school}") }))
                                    {
                                        classResults.Add(item);
                                    }
                                }
                                else
                                {
                                    await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamClassResult>(
                                        queryText: $"select value(c) from c where c.examId = '{eid}' and c.subjectId = '{subjectId}'",
                                        requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"ExamClassResult-{info.creatorId}") }))
                                    {
                                        classResults.Add(item);
                                    }
                                }
                                List<Task<bool>> tasks = new List<Task<bool>>();
                                foreach (ExamClassResult examClass in classResults)
                                {
                                    foreach (string stuId in examClass.studentIds)
                                    {
                                        int index = examClass.studentIds.IndexOf(stuId);
                                        tasks.Add(redisClient.HashSetAsync($"Exam:Scoring:{eid}-{subjectId}", stuId, new { tmdId = "" , ans = examClass.studentAnswers[index][0], score = examClass.studentScores[index] }.ToJsonString()));
                                    }

                                }
                                await Task.WhenAll(tasks);
                            }
                        }
                        var messageCorrectEnd = new ServiceBusMessage(new { id = input.Id, progress = "finish", code = tdata.code }.ToJsonString());
                        messageCorrectEnd.ApplicationProperties.Add("name", "Correct");
                        if (correctRecords.Count > 0)
                        {
                            long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageCorrectEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.etime));
                            await _serviceBus.GetServiceBusClient().cancelMessage(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), correctRecords[0].sequenceNumber);
                            correctRecords[0].sequenceNumber = end;
                            await _azureStorage.SaveOrUpdate<ChangeRecord>(correctRecords[0]);
                        }
                        else
                        {
                            long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageCorrectEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.etime));
                            ChangeRecord changeRecord = new ChangeRecord
                            {
                                RowKey = input.Id,
                                PartitionKey = "going",
                                sequenceNumber = end,
                                msgId = messageCorrectEnd.MessageId
                            };
                            await _azureStorage.Save<ChangeRecord>(changeRecord);
                        }
                        break;
                    case "finish":
                        ///暂不处理
                        break;
                }
            }
        }
    }
}
