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;
using TEAMModelOS.SDK.Models;
using TEAMModelOS.SDK.Models.Cosmos;
using TEAMModelOS.SDK.Models.Cosmos.Common;
using TEAMModelOS.SDK.Models.Table;
using HTEXLib.COMM.Helpers;

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.Equals("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(Constant.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 = Guid.NewGuid().ToString(),
                                            //评测id 或者阅卷配置id
                                            cid = 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,
                                            //按题阅卷时，题号
                                            qu = marker.qu,
                                            //模块数
                                            model = sub.model,
                                            type = 1,
                                            createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                                        };
                                        await client.GetContainer(Constant.TEAMModelOS, "Teacher").UpsertItemAsync<CorrectTask>(task, new Azure.Cosmos.PartitionKey(task.code));
                                    }
                                }


                                //生成异常卷处理人员
                                if (sub.err.IsNotEmpty())
                                {

                                    foreach (var tId in sub.err)
                                    {
                                        CorrectTask task = new CorrectTask
                                        {
                                            ttl = -1,
                                            pk = "CorrectTask",
                                            code = "CorrectTask-" + tId,
                                            
                                            id = Guid.NewGuid().ToString(),
                                            //评测id 或者阅卷配置id
                                            cid = 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,
                                            //模块数
                                            model = sub.model,
                                            type = 2,
                                            createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                                        };
                                        await client.GetContainer(Constant.TEAMModelOS, "Teacher").UpsertItemAsync<CorrectTask>(task, new Azure.Cosmos.PartitionKey(task.code));
                                    }


                                }

                                //生成仲裁人员

                                if (sub.arb.IsNotEmpty())
                                {

                                    foreach (var tId in sub.arb)
                                    {
                                        CorrectTask task = new CorrectTask
                                        {
                                            ttl = -1,
                                            pk = "CorrectTask",
                                            code = "CorrectTask-" + tId,
                                            
                                            id = Guid.NewGuid().ToString(),
                                            //评测id 或者阅卷配置id
                                            cid = 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,
                                            //模块数
                                            model = sub.model,
                                            type = 3,
                                            createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                                        };
                                        await client.GetContainer(Constant.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(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(eid, new Azure.Cosmos.PartitionKey(ecode));
                                List<ExamClassResult> classResults = new List<ExamClassResult>();
                                //获取原题配分
                                int paperIndex = 0;
                                foreach (ExamSubject subject in info.subjects)
                                {
                                    if (subject.id.Equals(subjectId))
                                    {
                                        break;
                                    }
                                    else
                                    {
                                        paperIndex++;
                                    }
                                }
                                List<double> paperPoint = info.papers[paperIndex].point;

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

                                    await foreach (var item in client.GetContainer(Constant.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(Constant.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<ItemResponse<Scoring>>> tasks = new List<Task<ItemResponse<Scoring>>>();
                                //初始化老师阅卷记录
                                //List<string> tmds = new List<string>();
/*                                List<string> marks = new List<string>();
                                for (int i = 0; i < correct.num; i++)
                                {
                                    marks.Add("");
                                }*/
                                foreach (ExamClassResult examClass in classResults)
                                {
                                    foreach (string stuId in examClass.studentIds)
                                    {
                                        int index = examClass.studentIds.IndexOf(stuId);
                                        if (index > -1)
                                        {
                                            List<double> scc = examClass.studentScores[index];
                                            List<Item> items = new List<Item>();
                                            List<Qs> qss = new List<Qs>();
                                            int itemIndex = 0;
                                            foreach (double psc in scc)
                                            {
                                                //初始化异常卷信息，初始化仲裁卷信息
                                                Qs qs = new Qs();
                                                List<Info> infos = new List<Info>();
                                                Item item = new Item
                                                {
                                                    ssc = paperPoint[itemIndex],
                                                    scores = infos
                                                };
                                                itemIndex++;
                                                items.Add(item);
                                                qss.Add(qs);
                                            }
                                            Scoring sc = new Scoring
                                            {
                                                id = Guid.NewGuid().ToString(),
                                                code = "Scoring-" + info.school,
                                                blob = examClass.studentAnswers[index].Count > 0 ? examClass.studentAnswers[index][0] : "",
                                                stuId = stuId,
                                                examId = eid,
                                                subjectId = subjectId,
                                                scores = examClass.studentScores[index],
                                                count = correct.num,
                                                //marks = marks,
                                                items = items,
                                                qs = qss,
                                                //endTime = correct.endTime,
                                                model = sub.model

                                            };
                                            tasks.Add(client.GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync<Scoring>(sc, new Azure.Cosmos.PartitionKey(sc.code)));
                                        }
                                        //tasks.Add(redisClient.HashSetAsync($"Exam:Scoring:{eid}-{subjectId}", stuId, new { tmdId = tmds, ans = examClass.studentAnswers[index].Count > 0 ? 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;
                }
            }
        }
    }
}
