using Azure.Cosmos;

using System;
using System.Collections.Generic;
using System.Text;
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.Common;
using TEAMModelOS.SDK.Models.Service;
using HTEXLib.COMM.Helpers;

namespace TEAMModelFunction
{
    public class StuListService
    {
        public static async Task FixActivity(CosmosClient client,DingDing _dingDing, ListChange stuListChange, string type)
        {
            
            try
            {
                var query = $"SELECT distinct c.owner, c.id,c.code, c.classes,c.stuLists,c.subjects,c.progress,c.scope,c.startTime,c.school,c.creatorId,c.name,c.pk ,c.endTime   FROM c  where  c.pk='{type}' " +
                    $" and (( array_contains(c.classes,'{stuListChange.listid}')) or ( array_contains(c.stuLists,'{stuListChange.listid}'))or ( array_contains(c.tchLists,'{stuListChange.listid}')))";
                    //$"and A1 in('{stuListChange.listid}') ";
                List<MQActivity> datas = new List<MQActivity>();
                if (stuListChange.scope.Equals("school", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrEmpty(stuListChange.school)) {
                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<MQActivity>(queryText: query,
                       requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"{type}-{stuListChange.school}") }))
                    {
                        datas.Add(item);
                    }
                    ///还要处理该学校每个老师发布的班级的
                    List<SchoolTeacher> teachers = new List<SchoolTeacher>();
                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<SchoolTeacher>(queryText: $"SELECT c.id, c.name FROM c",
                        requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{stuListChange.school}") }))
                    {
                        teachers.Add(item);
                    }
                    foreach (var techer in teachers) {
                        var queryTech = $"SELECT distinct c.owner, c.id,c.code, c.classes,c.stuLists,c.subjects,c.progress,c.scope,c.startTime,c.school,c.creatorId,c.name,c.pk ,c.endTime   FROM c " +
                            $" where c.school='{stuListChange.school}'   and   c.pk='{type}'" +
                            $" and (( array_contains(c.classes,'{stuListChange.listid}')) or ( array_contains(c.stuLists,'{stuListChange.listid}')))";
                      //  $" and A1 in('{stuListChange.listid}') ";
                        await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<MQActivity>(queryText: queryTech,
                            requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"{type}-{techer.id}") }))
                        {
                            datas.Add(item);
                        }
                    }
                }
                if (stuListChange.scope.Equals("private", StringComparison.OrdinalIgnoreCase)&&!string.IsNullOrEmpty(stuListChange.creatorId))
                {
                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<MQActivity>(queryText: query,
                        requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"{type}-{stuListChange.creatorId}") }))
                    {
                        datas.Add(item);
                    }
                }
              //  await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-StuListService-FixActivity\n名单发生变更：涉及活动类型变更的 \n{datas.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
                foreach (MQActivity activity in datas)
                {
                    //已经完结的不再允许加入
                    if (activity.progress.Equals("finish") || activity.progress.Equals("pending"))
                    {
                        continue;
                    }
                    List<string> classes = ExamService.getClasses(activity.classes, activity.stuLists);
                    //学生新加入名单的
                    foreach (Students students in stuListChange.stujoin)
                    {
                        var stucourse = new StuActivity
                        {
                            id = activity.id,
                            scode = activity.code,
                            name = activity.name,
                            code = $"Activity-{students.code.Replace("Base-","")}-{students.id}",
                            scope = activity.scope,
                            school = activity.school,
                            creatorId = activity.creatorId,
                            pk = "Activity",
                            type = type,
                            subjects = activity.pk.ToLower().Equals("exam") && activity.subjects.IsNotEmpty() ? new List<string>() { activity.subjects[0].id } : new List<string>() { "" },
                            startTime = activity.startTime,
                            endTime = activity.endTime,
                            blob = activity.blob,
                            owner = activity.owner,
                            createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
                            taskStatus = -1,
                            classIds = classes
                        };
                     //   await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-StuListService-FixActivity\n名单发生变更 新建活动中间表\n{stucourse.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
                        await client.GetContainer(Constant.TEAMModelOS, "Student").UpsertItemAsync(stucourse, new PartitionKey(stucourse.code));
                    }
                    
                    //tmd新加入的
                    foreach (string tmdid in stuListChange.tmdjoin)
                    {
                        var stucourse = new StuActivity
                        {
                            id = activity.id,
                            scode = activity.code,
                            name = activity.name,
                            code = $"Activity-{tmdid}",
                            scope = activity.scope,
                            school = activity.school,
                            creatorId = activity.creatorId,
                            pk = "Activity",
                            type = type,
                            subjects = activity.pk.ToLower().Equals("exam") && activity.subjects.IsNotEmpty() ? new List<string>() { activity.subjects[0].id } : new List<string>() { "" },
                            startTime = activity.startTime,
                            endTime = activity.endTime,
                            blob = activity.blob,
                            owner = activity.owner,
                            createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
                            taskStatus = -1,
                            classIds = classes
                        }; 
                      //  await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-StuListService-FixActivity\n名单发生变更 新建活动中间表\n{stucourse.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
                        await client.GetContainer(Constant.TEAMModelOS, "Student").UpsertItemAsync(stucourse, new PartitionKey(stucourse.code));
                    }
                    //tmd新加入的
                    foreach (string tch in stuListChange.tchjoin)
                    {
                        var stucourse = new StuActivity
                        {
                            id = activity.id,
                            scode = activity.code,
                            name = activity.name,
                            code = $"Activity-{tch}",
                            scope = activity.scope,
                            school = activity.school,
                            creatorId = activity.creatorId,
                            pk = "Activity",
                            type = type,
                            subjects = activity.pk.ToLower().Equals("exam") && activity.subjects.IsNotEmpty() ? new List<string>() { activity.subjects[0].id } : new List<string>() { "" },
                            startTime = activity.startTime,
                            endTime = activity.endTime,
                            blob = activity.blob,
                            owner = activity.owner,
                            createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
                            taskStatus = -1,
                            classIds = classes
                        };
                        //  await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-StuListService-FixActivity\n名单发生变更 新建活动中间表\n{stucourse.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
                        await client.GetContainer(Constant.TEAMModelOS, "Teacher").UpsertItemAsync(stucourse, new PartitionKey(stucourse.code));
                    }
                    foreach (Students students in stuListChange.stuleave)
                    {
                        try
                        {

                            await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuActivity>(activity.id, new PartitionKey($"Activity-{students.code.Replace("Base-", "")}-{students.id}"));
                        }
                        catch (CosmosException ex)
                        {
                            //仅处理未写入的数据。
                        }
                    }
                    foreach (string tmdid in stuListChange.tmdhleave)
                    {
                        try
                        {

                            await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<StuActivity>(activity.id, new PartitionKey($"Activity-{tmdid}"));
                        }
                        catch(CosmosException ex )
                        {
                            //仅处理未写入的数据。
                        }
                    }
                }
            }
            catch(Exception ex ) {
                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-StuListService-FixActivity\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
            }
        }

        public static async Task FixStuCourse(CosmosClient client,DingDing  _dingDing, ListChange stuListChange)
        {
            //1.查找学校或教师的课程是否包含该名单的课程。
            var query = $"select distinct c.code,c.id,c.no,c.name,c.scope, c.creatorId,c.school from c join A0 in c.schedule where A0.stulist = '{stuListChange.listid}'";
            List<Course> courses = new List<Course>();
            if (stuListChange.scope.Equals("school") && !string.IsNullOrEmpty(stuListChange.school))
            {
                await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<Course>(queryText: query,
                    requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Course-{stuListChange.school}") }))
                {
                    courses.Add(item);
                }
            }
            if (stuListChange.scope.Equals("private") && !string.IsNullOrEmpty(stuListChange.creatorId))
            {
                await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<Course>(queryText: query,
                    requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Course-{stuListChange.creatorId}") }))
                {
                    courses.Add(item);
                }
            }
           // await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-StuListService-FixStuCourse\n名单发生变更 需要处理的课程\n{courses.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
            //2.获取课程的id 并尝试添加或移除对应的学生课程记录StuCourse。
            foreach (var course in courses)
            {
                //学生新加入名单的
                foreach (Students students in stuListChange.stujoin)
                {
                    var stucourse = new StuCourse
                    {
                        id = course.id,
                        scode = course.code,
                        name = course.name,
                        code = $"StuCourse-{students.code.Replace("Base-", "")}-{students.id}",
                        scope = course.scope,
                        school = course.school,
                        creatorId = course.creatorId,
                        pk = "StuCourse",
                        stulist = new List<string> { stuListChange.listid },
                        createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                    };
                   // await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-StuListService-FixStuCourse\n名单发生变更 新建课程中间表\n{stucourse.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
                    await client.GetContainer(Constant.TEAMModelOS, "Student").UpsertItemAsync(stucourse, new PartitionKey(stucourse.code));
                }
                //tmd新加入的
                foreach (string tmdid in stuListChange.tmdjoin)
                {
                    var stucourse = new StuCourse
                    {
                        id = course.id,
                        scode = course.code,
                        name = course.name,
                        code = $"StuCourse-{tmdid}",
                        scope = course.scope,
                        school = course.school,
                        creatorId = course.creatorId,
                        pk = "StuCourse",
                        stulist= new List<string> { stuListChange .listid},
                        createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                    };
                   // await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-StuListService-FixStuCourse\n名单发生变更 新建课程中间表\n{stucourse.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
                    await client.GetContainer(Constant.TEAMModelOS, "Student").UpsertItemAsync(stucourse, new PartitionKey(stucourse.code));
                }
                //移除名单的。 在点击相关的课程，再去二次校验是否存在，不存在则再去删除。
                foreach (var delStu in stuListChange.stuleave)
                {
                    await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemStreamAsync(course.id, new PartitionKey($"StuCourse-{delStu.code.Replace("Base-", "")}-{delStu.id}"));
                }
                foreach (var delTmd in stuListChange.tmdhleave)
                {
                    await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemStreamAsync(course.id, new PartitionKey($"StuCourse-{delTmd}"));
                }
            }
        }

    }
}
