using Azure;
using Azure.Cosmos;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
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 TEAMModelOS.SDK
{
    public class TriggerStuActivity
    {
        public static async Task RefreshStuActivity(CosmosClient client, DingDing _dingDing, string id, string code)
        {
            MQActivity activity = null;
            try
            {
                var aactivity = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id, new Azure.Cosmos.PartitionKey(code));
                using var da = await JsonDocument.ParseAsync(aactivity.ContentStream);
                activity = da.ToObject<MQActivity>();
            }
            catch (CosmosException )
            {
                activity=null;
            }
            if (activity != null)
            {
                List<string> classes = ExamService.getClasses(activity.classes, activity.stuLists);
                (List<TmdInfo> tmdids, List<StuInfo> students,List<ClassListInfo> classLists) = await GetStuList(client, _dingDing, classes, activity.school);
                if (tmdids.IsNotEmpty())
                {
                    foreach (TmdInfo tmdid in tmdids)
                    {
                        var stucourse = new StuActivity
                        {
                            id = activity.id,
                            scode = activity.code,
                            name = activity.name,
                            code = $"Activity-{tmdid.id}",
                            scope = activity.scope,
                            school = activity.school,
                            creatorId = activity.creatorId,
                            pk = "Activity",
                            type = activity.pk,
                            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 client.GetContainer(Constant.TEAMModelOS, "Student").UpsertItemAsync(stucourse, new PartitionKey(stucourse.code));
                    }
                }
                if (students.IsNotEmpty())
                {
                    foreach (StuInfo student in students)
                    {
                        var stucourse = new StuActivity
                        {
                            id = activity.id,
                            scode = activity.code,
                            name = activity.name,
                            code = $"Activity-{activity.school}-{student.id}",
                            scope = activity.scope,
                            school = activity.school,
                            creatorId = activity.creatorId,
                            pk = "Activity",
                            type = activity.pk,
                            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 client.GetContainer(Constant.TEAMModelOS, "Student").UpsertItemAsync(stucourse, new PartitionKey(stucourse.code));
                    }
                }
            }
        }

        public static async Task<string> SaveStuActivity(CosmosClient client, DingDing _dingDing, List<StuActivity> stuActivities,List<StuActivity> tmdActivities, List<StuActivity>  tchActivities) {
            try {
                if (stuActivities.IsNotEmpty())
                {
                    foreach (var x in stuActivities)
                    {
                        await client.GetContainer(Constant.TEAMModelOS, "Student").UpsertItemAsync(x, new PartitionKey(x.code));
                    }
                }
                if (tmdActivities.IsNotEmpty())
                {
                    foreach (var x in tmdActivities)
                    {
                        await client.GetContainer(Constant.TEAMModelOS, "Student").UpsertItemAsync(x, new PartitionKey(x.code));
                    }
                }
                if (tchActivities.IsNotEmpty())
                {
                    foreach (var x in tchActivities)
                    {
                        await client.GetContainer(Constant.TEAMModelOS, "Teacher").UpsertItemAsync(x, new PartitionKey(x.code));
                    }
                }
            } catch (Exception ex) {
                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-OS，TriggerStuActivity-SaveStuActivity\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
            }
            return ""; 
        }
        /// <summary>
        /// 获取行政班接口
        /// </summary>
        /// <param name="client"></param>
        /// <param name="_dingDing"></param>
        /// <param name="classes"></param>
        /// <param name="school"></param>
        /// <returns></returns>
        public static async Task<List<ClassInfo>> GetClassInfo(CosmosClient client, DingDing _dingDing, List<string> classes, string school)
        {
            try {
                List<ClassInfo> classInfos = new List<ClassInfo>();
                if (classes.IsNotEmpty()) {
                    List<string> sqlList = new List<string>();
                    classes.ForEach(x => { sqlList.Add($" '{x}' "); });
                    string sql = string.Join(" , ", sqlList);
                    if (!string.IsNullOrEmpty(school))
                    {
                        await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<ClassInfo>(queryText: $"select c.id,c.name ,c.periodId,c.year from c where c.id in ({sql})",
                           requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Class-{school}") }))
                        {

                            classInfos.Add(item);
                        }
                        await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<ClassInfo>(queryText: $"select c.id,c.name from c where c.id in ({sql})",
                          requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"StuList-{school}") }))
                        {
                            //item.from = "SchStuList";
                            classInfos.Add(item);
                        }
                        await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<ClassInfo>(queryText: $"select c.id,c.name from c where c.id in ({sql})",
                        requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"TchList-{school}") }))
                        {
                            //item.from = "SchStuList";
                            classInfos.Add(item);
                        }
                    }
                    List<StuList> tchLists = new List<StuList>();
                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<ClassInfo>(queryText: $"select c.id,c.name from c where c.id in ({sql})",
                        requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"StuList") }))
                    {
                       // item.from = "TchStuList";
                        classInfos.Add(item);
                    }
                    classInfos = classInfos.GroupBy(c => c.id).Select(s => s.First()).ToList();
                }
                return classInfos;
            } catch (Exception ex) {
                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-OS，TriggerStuActivity-GetClassInfo\n{ex.Message}\n{ex.StackTrace}\n class{classes.ToJsonString()},{school}", GroupNames.醍摩豆服務運維群組);
                throw new Exception(ex.Message, ex);
            }
        }
        public static async Task<(List<TmdInfo> tmdinfos, List<StuInfo> students, List<ClassListInfo> classInfo)> GetStuListInStu(CosmosClient client, DingDing _dingDing, List<string> claes, string school)
        {
            try
            {
                List<string> classes = new List<string>();
                foreach (string ss in claes)
                {
                    classes.Add(ss);
                }
                List<TmdInfo> tmdinfos = new List<TmdInfo>();
                List<Students> studentss = new List<Students>();
                List<string> tmdids = new List<string>();
                List<StuInfo> stuInfos = new List<StuInfo>();
                if (!classes.IsNotEmpty()) { return (tmdinfos, new List<StuInfo>(), null); }
                List<string> sqlList = new List<string>();
                classes.ForEach(x => { sqlList.Add($" '{x}' "); });
                string sql = string.Join(" , ", sqlList);
                List<StuList> schList = new List<StuList>();
                List<Student> students = new List<Student>();
                if (!string.IsNullOrEmpty(school))
                {
                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<StuList>(queryText: $"select value(c) from c where c.id in ({sql})",
                    requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"StuList-{school}") }))
                    {
                        schList.Add(item);
                    }
                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: $"select value(c) from c where c.classId in ({sql})",
                        requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Base-{school}") }))
                    {
                        students.Add(item);
                    }
                }
                List<StuList> tchLists = new List<StuList>();
                await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<StuList>(queryText: $"select value(c) from c where c.id in ({sql})",
                    requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"StuList") }))
                {
                    tchLists.Add(item);
                }

                foreach (var x in schList)
                {
                    if (x.students.IsNotEmpty())
                    {
                        studentss.AddRange(x.students);
                    }
                    if (x.tmids.IsNotEmpty())
                    {
                        tmdids.AddRange(x.tmids);
                    }
                   
                    classes.Remove(x.id);
                }
                foreach (var x in tchLists)
                {
                    if (x.students.IsNotEmpty())
                    {
                        studentss.AddRange(x.students);
                    }
                    if (x.tmids.IsNotEmpty())
                    {
                        tmdids.AddRange(x.tmids);
                    }
                    classes.Remove(x.id);
                }

                if (tmdids.IsNotEmpty())
                {
                    List<TmdInfo> infos = new List<TmdInfo>();
                    List<string> inids = new List<string>();
                    tmdids.ForEach(x => { inids.Add($"'{x}'"); });
                    var insql = string.Join(",", inids);
                    var queryslt = $"SELECT  value(c) FROM c where c.id in ({insql})";
                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<TmdInfo>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
                    {
                        infos.Add(item);
                        tmdids.Remove(item.id);
                    }
                    if (tmdids.IsNotEmpty()) {
                        inids = new List<string>();
                        tmdids.ForEach(x => { inids.Add($"'{x}'"); });
                        insql = string.Join(",", inids);
                        queryslt = $"SELECT  value(c) FROM c where c.id in ({insql})";
                        await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<TmdInfo>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
                        {
                            infos.Add(item);
                        }
                    }
                    tmdinfos.AddRange(infos);
                }
                if (studentss.IsNotEmpty())
                {
                    var stuGroups = studentss.GroupBy(x => x.code).ToList().Select(x => new { key = x.Key, list = x.ToList() }) ;
                    foreach (var gp in stuGroups) {
                        List<string> inidstus = new List<string>();
                        gp.list.Select(x => x.id).ToList().ForEach(x => { inidstus.Add($"'{x}'"); });
                        PartitionKey partitionKey = new PartitionKey($"Base-{gp.key.Replace("Base-", "")}");
                        var insqlstu = string.Join(",", inidstus);
                        var querystu = $"SELECT  c.id,c.code,c.name,c.picture,c.classId,c.groupId,c.groupName,c.year,c.schoolId FROM c where c.id in ({insqlstu})";
                        await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<StuInfo>(queryText: querystu, requestOptions: new QueryRequestOptions() { PartitionKey= partitionKey }))
                        {
                            stuInfos.Add(item);
                        }
                    }
                }
                students.ForEach(x =>
                {
                    if (!stuInfos.Select(y => y.classId).ToList().Contains(x.id))
                    {
                        stuInfos.Add(new StuInfo { id = x.id, code = x.code, schoolId = x.schoolId, classId = x.classId, name = x.name, picture = x.picture, year = x.year,groupId = x.groupId,groupName=x.groupName,no=x.no });
                    }
                });
                List<ClassListInfo> classInfo = new List<ClassListInfo>();
                schList.ForEach(x => {
                    ClassListInfo classListInfo = new ClassListInfo { id = x.id, name = x.name };
                    if (x.students.IsNotEmpty())
                    {
                        x.students.ForEach(y => {
                            var stuinfo = stuInfos.Where(z => z.id.Equals(y.id)).FirstOrDefault();
                            if (stuinfo != null)
                            {
                                classListInfo.stuInfos.Add(stuinfo);
                            }
                        });
                    }
                    if (x.tmids.IsNotEmpty())
                    {
                        x.tmids.ForEach(y => {
                            var tmdinfo = tmdinfos.Where(z => z.id.Equals(y)).FirstOrDefault();
                            if (tmdinfo != null)
                            {
                                classListInfo.tmdInfos.Add(tmdinfo);
                            }
                        });
                    }
                    classInfo.Add(classListInfo);
                });
                tchLists.ForEach(x => {
                    ClassListInfo classListInfo = new ClassListInfo { id = x.id, name = x.name };
                    if (x.students.IsNotEmpty())
                    {
                        x.students.ForEach(y => {
                            var stuinfo = stuInfos.Where(z => z.id.Equals(y.id)).FirstOrDefault();
                            if (stuinfo != null)
                            {
                                classListInfo.stuInfos.Add(stuinfo);
                            }
                        });
                    }
                    if (x.tmids.IsNotEmpty())
                    {
                        x.tmids.ForEach(y => {
                            var tmdinfo = tmdinfos.Where(z => z.id.Equals(y)).FirstOrDefault();
                            if (tmdinfo != null)
                            {
                                classListInfo.tmdInfos.Add(tmdinfo);
                            }
                        });
                    }
                    classInfo.Add(classListInfo);
                });


                //var classeids= students.GroupBy(x => x.classId).Select(x => x.Key).ToList();
                List<ClassInfo> classInfos = await GetClassInfo(client, _dingDing, classes, school);
                classInfos.ForEach(x =>
                {
                    ClassListInfo classListInfo = new ClassListInfo { id = x.id, name = x.name };
                    var list = students.Where(y => y.classId .Equals(x.id)).ToList();
                    list.ForEach(z => { classListInfo.stuInfos.Add(new StuInfo { id = z.id, code = z.code, schoolId = z.schoolId, classId = z.classId, name = z.name, picture = z.picture, year = z.year,groupId=z.groupId,groupName=z.groupName,no=z.no }); });
                    classInfo.Add(classListInfo);
                });

                return (tmdinfos, stuInfos, classInfo);
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-OS，TriggerStuActivity-GetStuList\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
            }
            return (null, null, null);
        }
        public static async Task<(List<TmdInfo> tmdinfos, List<ClassListInfo> classInfo)> GetTchList(CosmosClient client, DingDing _dingDing, List<string> claes, string school)
        {
            try
            {
                List<TmdInfo> tmdinfos = new List<TmdInfo>();
                List<ClassListInfo> classInfo = new List<ClassListInfo>();
                if (claes.Count == 1 && claes.First().Equals("default"))
                {
                    List<TmdInfo> infos = new List<TmdInfo>();
                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<TmdInfo>(queryText: $"SELECT  value(c) FROM c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{school}") }))
                    {
                        infos.Add(item);
                    }
                    tmdinfos.AddRange(infos);
                    classInfo.Add(new ClassListInfo { id = "default",name= "default", tmdInfos = infos });
                }
                else {
                    List<string> classes = new List<string>();
                    foreach (string ss in claes)
                    {
                        classes.Add(ss);
                    }

                    List<string> tmdids = new List<string>();
                    List<StuInfo> stuInfos = new List<StuInfo>();
                    if (!classes.IsNotEmpty()) { return (tmdinfos, null); }
                    List<string> sqlList = new List<string>();
                    classes.ForEach(x => { sqlList.Add($" '{x}' "); });
                    string sql = string.Join(" , ", sqlList);
                    List<TchList> tchLists = new List<TchList>();

                    if (!string.IsNullOrEmpty(school))
                    {
                        await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<TchList>(queryText: $"select value(c) from c where c.id in ({sql})",
                        requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"TchList-{school}") }))
                        {
                            tchLists.Add(item);
                        }

                    }
                    foreach (var x in tchLists)
                    {

                        if (x.teachers.IsNotEmpty())
                        {
                            tmdids.AddRange(x.teachers);
                        }
                        classes.Remove(x.id);
                    }

                    if (tmdids.IsNotEmpty())
                    {
                        List<TmdInfo> infos = new List<TmdInfo>();
                        List<string> inids = new List<string>();
                        tmdids.ForEach(x => { inids.Add($"'{x}'"); });
                        var insql = string.Join(",", inids);
                        var queryslt = $"SELECT  value(c) FROM c where c.id in ({insql})";
                        //合并代码/
                        await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<TmdInfo>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
                        {
                            infos.Add(item);
                        }
                        tmdinfos.AddRange(infos);
                    }
                    tchLists.ForEach(x => {
                        ClassListInfo classListInfo = new ClassListInfo { id = x.id, name = x.name };
                        if (x.teachers.IsNotEmpty())
                        {
                            x.teachers.ForEach(y => {
                                var tmdinfo = tmdinfos.Where(z => z.id.Equals(y)).FirstOrDefault();
                                if (tmdinfo != null)
                                {
                                    classListInfo.tmdInfos.Add(tmdinfo);
                                }
                            });
                        }
                        classInfo.Add(classListInfo);
                    });
                }
                return (tmdinfos,  classInfo);
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-OS，TriggerStuActivity-GetStuList\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
            }
            return (null,  null);
        }
        public static async Task<(List<TmdInfo> tmdinfos, List<StuInfo> students, List<ClassListInfo> classInfo)> GetStuList(CosmosClient client, DingDing _dingDing, List<string> claes, string school)
        {
            try
            {
                List<string> classes = new List<string>();
                foreach (string ss in claes)
                {
                    classes.Add(ss);
                }
                List<TmdInfo> tmdinfos = new List<TmdInfo>();
                List<Students> studentss = new List<Students>();
                List<string> tmdids = new List<string>();
                List<StuInfo> stuInfos = new List<StuInfo>();
                if (!classes.IsNotEmpty()) { return (tmdinfos, new List<StuInfo>(), null); }
                List<string> sqlList = new List<string>();
                classes.ForEach(x => { sqlList.Add($" '{x}' "); });
                string sql = string.Join(" , ", sqlList);
                List<StuList> schList = new List<StuList>();
                List<Student> students = new List<Student>();
                if (!string.IsNullOrEmpty(school))
                {
                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<StuList>(queryText: $"select value(c) from c where c.id in ({sql})",
                    requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"StuList-{school}") }))
                    {
                        schList.Add(item);
                    }
                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: $"select value(c) from c where c.classId in ({sql})",
                        requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Base-{school}") }))
                    {
                        students.Add(item);
                    }
                }
                List<StuList> tchLists = new List<StuList>();
                await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<StuList>(queryText: $"select value(c) from c where c.id in ({sql})",
                    requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"StuList") }))
                {
                    tchLists.Add(item);
                }

                foreach (var x in schList)
                {
                    if (x.students.IsNotEmpty())
                    {
                        studentss.AddRange(x.students);
                    }
                    if (x.tmids.IsNotEmpty())
                    {
                        tmdids.AddRange(x.tmids);
                    }
                    classes.Remove(x.id);
                }
                foreach (var x in tchLists)
                {
                    if (x.students.IsNotEmpty())
                    {
                        studentss.AddRange(x.students);
                    }
                    if (x.tmids.IsNotEmpty())
                    {
                        tmdids.AddRange(x.tmids);
                    }
                    classes.Remove(x.id);
                }

                if (tmdids.IsNotEmpty())
                {
                    List<TmdInfo> infos = new List<TmdInfo>();
                    List<string> inids = new List<string>();
                    tmdids.ForEach(x => { inids.Add($"'{x}'"); });
                    var insql = string.Join(",", inids);
                    var queryslt = $"SELECT  value(c) FROM c where c.id in ({insql})";
                    //合并代码/
                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<TmdInfo>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
                    {
                        infos.Add(item);
                    }
                    tmdinfos.AddRange(infos);
                }
                if (studentss.IsNotEmpty())
                {
                    List<string> inidstus = new List<string>();
                    foreach (Students stu in studentss)
                    {
                        var querystu = $"SELECT  c.id,c.code,c.name,c.picture,c.classId,c.year,c.schoolId FROM c where c.id = '{stu.id}'";
                        await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<StuInfo>(queryText: querystu, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{stu.code}") }))
                        {
                            stuInfos.Add(item);
                        }
                    }
                    /*studentss.Select(x => x.id).ToList().ForEach(x => { inidstus.Add($"'{x}'"); });
                    var insqlstu = string.Join(",", inidstus);
                    var querystu = $"SELECT  c.id,c.code,c.name,c.picture,c.classId,c.year,c.schoolId FROM c where c.id in ({insqlstu})";
                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<StuInfo>(queryText: querystu, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{school}") }))
                    {
                        stuInfos.Add(item);
                    }*/
                }
                students.ForEach(x =>
                {
                    if (!stuInfos.Select(y => y.classId).ToList().Contains(x.id))
                    {
                        stuInfos.Add(new StuInfo { id = x.id, code = x.code, schoolId = x.schoolId, classId = x.classId, name = x.name, picture = x.picture, year = x.year, groupId = x.groupId, groupName = x.groupName, no = x.no });
                    }
                });
                List<ClassListInfo> classInfo = new List<ClassListInfo>();
                schList.ForEach(x => {
                    ClassListInfo classListInfo = new ClassListInfo { id = x.id, name = x.name };
                    if (x.students.IsNotEmpty())
                    {
                        x.students.ForEach(y => {
                            var stuinfo = stuInfos.Where(z => z.id.Equals(y.id)).FirstOrDefault();
                            if (stuinfo != null)
                            {
                                classListInfo.stuInfos.Add(stuinfo);
                            }
                        });
                    }
                    if (x.tmids.IsNotEmpty())
                    {
                        x.tmids.ForEach(y => {
                            var tmdinfo = tmdinfos.Where(z => z.id.Equals(y)).FirstOrDefault();
                            if (tmdinfo != null)
                            {
                                classListInfo.tmdInfos.Add(tmdinfo);
                            }
                        });
                    }
                    classInfo.Add(classListInfo);
                });
                tchLists.ForEach(x => {
                    ClassListInfo classListInfo = new ClassListInfo { id = x.id, name = x.name };
                    if (x.students.IsNotEmpty())
                    {
                        x.students.ForEach(y => {
                            var stuinfo = stuInfos.Where(z => z.id.Equals(y.id)).FirstOrDefault();
                            if (stuinfo != null)
                            {
                                classListInfo.stuInfos.Add(stuinfo);
                            }
                        });
                    }
                    if (x.tmids.IsNotEmpty())
                    {
                        x.tmids.ForEach(y => {
                            var tmdinfo = tmdinfos.Where(z => z.id.Equals(y)).FirstOrDefault();
                            if (tmdinfo != null)
                            {
                                classListInfo.tmdInfos.Add(tmdinfo);
                            }
                        });
                    }
                    classInfo.Add(classListInfo);
                });


                //var classeids= students.GroupBy(x => x.classId).Select(x => x.Key).ToList();
                List<ClassInfo> classInfos = await GetClassInfo(client, _dingDing, classes, school);
                classInfos.ForEach(x =>
                {
                    ClassListInfo classListInfo = new ClassListInfo { id = x.id, name = x.name };
                    var list = students.Where(y => y.classId.Equals(x.id)).ToList();
                    list.ForEach(z => { classListInfo.stuInfos.Add(new StuInfo { id = z.id, code = z.code, schoolId = z.schoolId, classId = z.classId, name = z.name, picture = z.picture, year = z.year, groupId = z.groupId, groupName = z.groupName, no = z.no }); });
                    classInfo.Add(classListInfo);
                });

                return (tmdinfos, stuInfos, classInfo);
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-OS，TriggerStuActivity-GetStuList\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
            }
            return (null, null, null);
        }
    }
    public class ClassListInfo
    {
        public string id { get; set; }
        public string name { get; set; }
        // public string from { get; set; }
        public List<StuInfo> stuInfos { get; set; } = new List<StuInfo>();
        public List<TmdInfo> tmdInfos { get; set; } = new List<TmdInfo>();
    }
}
