using Azure.Cosmos;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using TEAMModelOS.Models;
using TEAMModelOS.SDK.Models;
using TEAMModelOS.SDK;
using TEAMModelOS.SDK.DI;
using TEAMModelOS.SDK.Extension;
using Azure;
using TEAMModelOS.SDK.Models.Cosmos.Common;
using Azure.Messaging.ServiceBus;
using Microsoft.Extensions.Configuration;
using TEAMModelOS.Filter;
using HTEXLib.COMM.Helpers;

namespace TEAMModelOS.Controllers
{
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    //[Authorize(Roles = "IES5")]
    [Route("stulist")]
    [ApiController]
    public class StuListController : ControllerBase
    {
        private AzureCosmosFactory _azureCosmos;
        private readonly DingDing _dingDing;
        private readonly Option _option;
        private readonly AzureServiceBusFactory _serviceBus;
        private readonly AzureStorageFactory _azureStorage;
        public IConfiguration _configuration { get; set; }
        public StuListController(AzureCosmosFactory azureCosmos, DingDing dingDing, IOptionsSnapshot<Option> option, AzureServiceBusFactory serviceBus, AzureStorageFactory azureStorage, IConfiguration configuration)
        {
            _azureCosmos = azureCosmos;
            _dingDing = dingDing;
            _option = option?.Value;
            _serviceBus = serviceBus;
            _configuration = configuration;
            _azureStorage = azureStorage;
        }
        //处理通用名单
        [ProducesDefaultResponseType]
        [AuthToken(Roles = "teacher,admin")]
        [HttpPost("upsert-list")]
        public async Task<IActionResult> upsertList(StuList stuList)
        {
            try
            {
                var (userid, _, _, school) = HttpContext.GetAuthTokenInfo();
                stuList.creatorId = userid;
                stuList.school = school;
                stuList = await upsertList(stuList, stuList.scope);
                return Ok(new { stuList });
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，course/upsert-list()\n{ex.Message}{ex.StackTrace}\n{stuList}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }
        }
        /*
        {
            "stuListNo": "1124582",
            "studentId":  "19990005",//tmdId/studentId 只能是其中一个有值
            "tmdId":"1538614518",

        }

         */
        /// <summary>
        /// 扫码加入名单
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [HttpPost("scan-code-join-list")]
        public async Task<IActionResult> ScanCodeJoinList(JsonElement json)
        {
            try
            {
                if (!json.TryGetProperty("stuListNo", out JsonElement _stuListNo)) return BadRequest();
                json.TryGetProperty("school", out JsonElement _school);
                string school = $"{_school}";
                var client = _azureCosmos.GetCosmosClient();
                var queryNo = $"SELECT  *  FROM c where  c.no ='{_stuListNo}'";
                StuList stuList = null;
                json.TryGetProperty("studentId", out JsonElement _studentId);
                json.TryGetProperty("tmdId", out JsonElement _tmdId);
                if (!string.IsNullOrEmpty(school) && !string.IsNullOrEmpty($"{_studentId}"))
                {
                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: queryNo,
                          requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"StuList-{school}") }))
                    {
                        using var jsonNo = await JsonDocument.ParseAsync(item.ContentStream);
                        if (jsonNo.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
                        {
                            var stuDoc = jsonNo.RootElement.GetProperty("Documents").EnumerateArray();
                            while (stuDoc.MoveNext())
                            {
                                JsonElement data = stuDoc.Current;
                                stuList = data.ToObject<StuList>();
                                if (stuList != null)
                                {
                                    (int status, StuList stuLis) = JoinList(stuList, $"{_studentId}", $"{_tmdId}", school);
                                    stuLis = await upsertList(stuList, "school");
                                    return Ok(new { status, stuLis });
                                }
                            }
                        }
                    }
                }
                json.TryGetProperty("id_token", out JsonElement id_token);
                if (!string.IsNullOrEmpty($"{_tmdId}") && !string.IsNullOrEmpty($"{id_token}"))
                {
                    var jwt = new JwtSecurityToken(id_token.GetString());
                    var id = jwt.Payload.Sub;
                    jwt.Payload.TryGetValue("name", out object name);
                    jwt.Payload.TryGetValue("picture", out object picture);
                    try
                    {
                        TmdUser tmduser = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<TmdUser>(id, new PartitionKey("Base"));
                    }
                    catch (CosmosException ex)
                    {
                        if (ex.Status == 404)
                        {
                            //如果沒有，則初始化Teacher基本資料到Cosmos
                            TmdUser tmduser = new TmdUser
                            {
                                id = id,
                                pk = "Base",
                                code = "Base",
                                name = name?.ToString(),
                                picture = picture?.ToString(),
                                //创建账号并第一次登录IES5则默认赠送1G
                                defaultSchool = null,
                                schools = new List<TmdUser.School>(),
                            };
                            tmduser = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync<TmdUser>(tmduser, new PartitionKey("Base"));
                        }
                    }
                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIterator(queryText: queryNo,
                       requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"StuList") }))
                    {
                        using var jsonNo = await JsonDocument.ParseAsync(item.ContentStream);
                        if (jsonNo.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
                        {
                            var stuDoc = jsonNo.RootElement.GetProperty("Documents").EnumerateArray();
                            while (stuDoc.MoveNext())
                            {
                                JsonElement data = stuDoc.Current;
                                stuList = data.ToObject<StuList>();
                                if (stuList != null)
                                {
                                    (int status, StuList stuLis) = JoinList(stuList, $"{_studentId}", $"{_tmdId}", school);
                                    stuLis = await upsertList(stuList, "private");
                                    return Ok(new { status, stuLis });
                                }
                            }
                        }
                    }
                    return Ok(new { status = -1 });
                }
                else
                {
                    await _dingDing.SendBotMsg($"OS，{_option.Location}，course/scan-code-join-list()\n扫码加入课程参数异常{json}", GroupNames.醍摩豆服務運維群組);
                    return BadRequest();
                }

            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，course/scan-code-join-list()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }
        }


        /// <summary>
        /// 根据邀请码加入名单
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [AuthToken(Roles = "admin,teacher,student")]
        [HttpPost("input-code-join-list")]
        public async Task<IActionResult> GetListByNo(JsonElement json)
        {
            try
            {

                if (!json.TryGetProperty("stuListNo", out JsonElement _stuListNo)) return BadRequest();
                var (userid, _name, _picture, school) = HttpContext.GetAuthTokenInfo();
                var client = _azureCosmos.GetCosmosClient();
                var queryNo = $"SELECT  *  FROM c where  c.no ='{_stuListNo}'";
                StuList stuList = null;
                json.TryGetProperty("studentId", out JsonElement _studentId);
                json.TryGetProperty("tmdId", out JsonElement _tmdId);
                if (string.IsNullOrEmpty($"{_tmdId}") && userid.Equals($"{_tmdId}"))
                {
                    try
                    {
                        TmdUser tmduser = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<TmdUser>(userid, new PartitionKey("Base"));
                    }
                    catch (CosmosException ex)
                    {
                        if (ex.Status == 404)
                        {
                            //如果沒有，則初始化Teacher基本資料到Cosmos
                            TmdUser tmduser = new TmdUser
                            {
                                id = userid,
                                pk = "Base",
                                code = "Base",
                                name = _name,
                                picture = _picture,
                                //创建账号并第一次登录IES5则默认赠送1G
                                defaultSchool = null,
                                schools = new List<TmdUser.School>(),
                            };
                            tmduser = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync<TmdUser>(tmduser, new PartitionKey("Base"));
                        }
                    }
                }
                if (!string.IsNullOrEmpty(school))
                {
                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: queryNo,
                          requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"StuList-{school}") }))
                    {
                        using var jsonNo = await JsonDocument.ParseAsync(item.ContentStream);
                        if (jsonNo.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
                        {
                            var stuDoc = jsonNo.RootElement.GetProperty("Documents").EnumerateArray();
                            while (stuDoc.MoveNext())
                            {
                                JsonElement data = stuDoc.Current;
                                stuList = data.ToObject<StuList>();
                                if (stuList != null)
                                {
                                    (int status, StuList stuLis) = JoinList(stuList, $"{_studentId}", $"{_tmdId}", school);
                                    stuLis = await upsertList(stuList, "school");
                                    return Ok(new { status, stuLis });
                                }
                            }
                        }
                    }
                }
                await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIterator(queryText: queryNo,
                    requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"StuList") }))
                {
                    using var jsonNo = await JsonDocument.ParseAsync(item.ContentStream);
                    if (jsonNo.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
                    {
                        var stuDoc = jsonNo.RootElement.GetProperty("Documents").EnumerateArray();
                        while (stuDoc.MoveNext())
                        {
                            JsonElement data = stuDoc.Current;
                            stuList = data.ToObject<StuList>();
                            if (stuList != null)
                            {
                                (int status, StuList stuLis) = JoinList(stuList, $"{_studentId}", $"{_tmdId}", school);
                                stuLis = await upsertList(stuList, "private");
                                return Ok(new { status, stuLis });
                            }
                        }
                    }
                }
                return Ok(new { status = -1 });
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，course/get-list-by-no()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }
        }

        public (int status, StuList stuList) JoinList(StuList stuList, string _studentId, string _tmdId, string school)
        {
            int status = -1;
            if (string.IsNullOrEmpty($"{_studentId}") && string.IsNullOrEmpty($"{_tmdId}"))
            {
                //加入学生或醍摩豆ID为空
                status = 1;
            }
            else
            {
                if (!string.IsNullOrEmpty($"{_studentId}") && !string.IsNullOrEmpty(school))
                {
                    string _stuid = $"{_studentId}";
                    var student = stuList.students.Find(x => x.id == _stuid);
                    if (student != null)
                    {
                        //重复加入
                        status = 2;
                    }
                    else
                    {
                        status = 0;
                        stuList.students.Add(new Students { id = _stuid, code = $"Base-{school}", schoolId = $"{school}" });
                    }
                }
                if (!string.IsNullOrEmpty($"{_tmdId}"))
                {
                    string tmdid = $"{_tmdId}";
                    var tmd = stuList.tmids.Find(x => x == tmdid);
                    if (!string.IsNullOrEmpty(tmd))
                    {
                        //重复加入
                        status = 2;
                    }
                    else
                    {
                        status = 0;
                        stuList.tmids.Add(tmdid);
                    }
                }
            }
            return (status, stuList);
        }
        
        private async Task<StuList> upsertList(StuList stuList, string scope)
        {
            try
            {
                var client = _azureCosmos.GetCosmosClient();

                //todo 需要校验是否重复
                if (string.IsNullOrEmpty(stuList.no))
                {
                    stuList.no = $"{Utils.CreatSaltString(6, "0123456789")}";
                    //string table = $"{scope}" != "school" ? "Teacher" : "School";
                    for (int i = 0; i < 10; i++)
                    {
                        var queryNo = $"SELECT  c.no  FROM c where  c.no ='{stuList.no}'";
                        List<string> noStus = new();
                        await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: queryNo,
                                requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"{stuList.code}") }))
                        {
                            using var jsonNo = await JsonDocument.ParseAsync(item.ContentStream);
                            if (jsonNo.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
                            {
                                var accounts = jsonNo.RootElement.GetProperty("Documents").EnumerateArray();
                                while (accounts.MoveNext())
                                {
                                    JsonElement account = accounts.Current;
                                    noStus.Add(account.GetProperty("no").GetString());
                                }
                            }
                        }
                        await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIterator(queryText: queryNo,
                                requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey("StuList") }))
                        {
                            using var jsonNo = await JsonDocument.ParseAsync(item.ContentStream);
                            if (jsonNo.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
                            {
                                var accounts = jsonNo.RootElement.GetProperty("Documents").EnumerateArray();
                                while (accounts.MoveNext())
                                {
                                    JsonElement account = accounts.Current;
                                    noStus.Add(account.GetProperty("no").GetString());
                                }
                            }
                        }
                        if (noStus.Count == 0)
                        {
                            break;
                        }
                        else
                        {
                            if (i == 9)
                            {
                                string msg = $"OS，{_option.Location}，school/course/upsert-list()\n 编号生成异常，重复生成次数超过10次";
                                await _dingDing.SendBotMsg(msg, GroupNames.醍摩豆服務運維群組);
                                throw new Exception(msg);
                            }
                            else
                            {
                                stuList.no = $"{Utils.CreatSaltString(6, "0123456789")}";
                            }
                        }
                    }
                }

                stuList.code = stuList.pk + "-" + stuList.code.Replace("StuList-", "");
                if (scope.ToString().Equals("school", StringComparison.OrdinalIgnoreCase))
                {
                    stuList.scope = "school";
                    ListChange change = new ListChange()
                    {
                        listid = stuList.id,
                        scope = $"{scope}",
                        originCode = stuList.school,
                        school = stuList.school,
                        creatorId = stuList.creatorId
                    };
                    var query = $"SELECT distinct value(c)  FROM c where  c.id='{stuList.id}'";
                    List<StuList> odlStus = new List<StuList>();
                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<StuList>(queryText: query,
                            requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"StuList-{stuList.school}") }))
                    {
                        odlStus.Add(item);
                    }
                    if (odlStus.Count > 0)
                    {
                        if (stuList.students != null)
                        {

                            if (odlStus[0].students != null)
                            {
                                StuList oldStu = odlStus[0];
                                foreach (var stu in stuList.students)
                                {
                                    bool flag = false;
                                    //判断新增名单成员不在已经存在的名单
                                    foreach (var old in oldStu.students)
                                    {
                                        if (old.id.Equals(stu.id) && old.code.Equals(stu.code))
                                        {
                                            flag = true;
                                        }
                                    }
                                    if (flag == false)
                                    {
                                        change.stujoin.Add(stu);
                                    }
                                }
                                foreach (var old in oldStu.students)
                                {
                                    bool flag = false;
                                    //判断已存在名单成员不在变更后的名单里
                                    foreach (var stu in stuList.students)
                                    {
                                        if (old.id.Equals(stu.id) && old.code.Equals(stu.code))
                                        {
                                            flag = true;
                                        }
                                    }
                                    if (flag == false)
                                    {
                                        change.stuleave.Add(old);
                                    }
                                }
                            }
                        }
                        if (stuList.tmids != null)
                        {
                            if (odlStus[0].tmids != null)
                            {
                                StuList oldStu = odlStus[0];
                                foreach (var tmdid in stuList.tmids)
                                {
                                    bool flag = false;
                                    //判断新增名单成员不在已经存在的名单
                                    foreach (var old in oldStu.tmids)
                                    {
                                        if (old.Equals(tmdid))
                                        {
                                            flag = true;
                                        }
                                    }
                                    if (flag == false)
                                    {
                                        change.tmdjoin.Add(tmdid);
                                    }
                                }
                                foreach (var old in oldStu.tmids)
                                {
                                    bool flag = false;
                                    //判断已存在名单成员不在变更后的名单里
                                    foreach (var tmdid in stuList.tmids)
                                    {
                                        if (old.Equals(tmdid))
                                        {
                                            flag = true;
                                        }
                                    }
                                    if (flag == false)
                                    {
                                        change.tmdhleave.Add(old);
                                    }
                                }
                            }
                        }
                        if (change.tmdjoin.Count != 0 || change.tmdhleave.Count != 0 || change.stujoin.Count != 0 || change.stuleave.Count != 0)
                        {
                            var messageChange = new ServiceBusMessage(change.ToJsonString());
                            messageChange.ApplicationProperties.Add("name", "StuList");
                            var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
                            await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
                        }
                    }
                    stuList = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").UpsertItemAsync(stuList, new PartitionKey($"StuList-{stuList.school}"));
                }
                else
                {
                    stuList.scope = "private";
                    if (stuList.students.IsNotEmpty())
                    {
                        stuList.school = stuList.students[0].code.Replace("Base-", "");
                    }
                    ListChange change = new ListChange()
                    {
                        listid = stuList.id,
                        scope = $"{scope}",
                        originCode = stuList.creatorId,
                        school = stuList.school,
                        creatorId = stuList.creatorId
                    };

                    var query = $"SELECT distinct value(c)  FROM c    where  c.id='{stuList.id}'";
                    List<StuList> odlStus = new List<StuList>();
                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<StuList>(queryText: query,
                            requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"StuList") }))
                    {
                        odlStus.Add(item);
                    }
                    if (odlStus.Count > 0)
                    {
                        if (stuList.students != null)
                        {

                            if (odlStus[0].students != null)
                            {
                                StuList oldStu = odlStus[0];
                                foreach (var stu in stuList.students)
                                {
                                    bool flag = false;
                                    //判断新增名单成员不在已经存在的名单
                                    foreach (var old in oldStu.students)
                                    {
                                        if (old.id == stu.id && old.code == stu.code)
                                        {
                                            flag = true;
                                        }
                                    }
                                    if (flag == false)
                                    {
                                        change.stujoin.Add(stu);
                                    }
                                }
                                foreach (var old in oldStu.students)
                                {
                                    bool flag = false;
                                    //判断已存在名单成员不在变更后的名单里
                                    foreach (var stu in stuList.students)
                                    {
                                        if (old.id.Equals(stu.id) && old.code.Equals(stu.code))
                                        {
                                            flag = true;
                                        }
                                    }
                                    if (flag == false)
                                    {
                                        change.stuleave.Add(old);
                                    }
                                }
                            }
                        }
                        if (stuList.tmids != null)
                        {
                            if (odlStus[0].tmids != null)
                            {
                                StuList oldStu = odlStus[0];
                                foreach (var tmdid in stuList.tmids)
                                {
                                    bool flag = false;
                                    //判断新增名单成员不在已经存在的名单
                                    foreach (var old in oldStu.tmids)
                                    {
                                        if (old == tmdid)
                                        {
                                            flag = true;
                                        }
                                    }
                                    if (flag == false)
                                    {
                                        change.tmdjoin.Add(tmdid);
                                    }

                                }
                                foreach (var old in oldStu.tmids)
                                {
                                    bool flag = false;
                                    //判断已存在名单成员不在变更后的名单里
                                    foreach (var tmdid in stuList.tmids)
                                    {
                                        if (old.Equals(tmdid))
                                        {
                                            flag = true;
                                        }
                                    }
                                    if (flag == false)
                                    {
                                        change.tmdhleave.Add(old);
                                    }
                                }
                            }
                        }
                        if (change.tmdjoin.Count != 0 || change.tmdhleave.Count != 0 || change.stujoin.Count != 0 || change.stuleave.Count != 0)
                        {
                            var messageChange = new ServiceBusMessage(change.ToJsonString());
                            messageChange.ApplicationProperties.Add("name", "StuList");
                            var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
                            await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
                        }
                    }
                    stuList.code = "StuList";
                    stuList = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").UpsertItemAsync(stuList, new PartitionKey($"StuList"));
                }
                return stuList;
            }
            catch (Exception ex)
            {
                string msg = $"OS，{_option.Location}，course/upsert-list()\n{ex.Message}{ex.StackTrace}\n{stuList.ToJsonString()}";
                await _dingDing.SendBotMsg(msg, GroupNames.醍摩豆服務運維群組);
                throw new Exception(msg, ex);
            }
        }

        //查询名单
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "Teacher")]
        [HttpPost("find-list")]
        public async Task<IActionResult> FindList(JsonElement requert)
        {
            try
            {
                if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
                if (!requert.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
                var client = _azureCosmos.GetCosmosClient();
                List<object> stuList = new List<object>();
                //List<int> stuCount = new List<int>();
                var query = $"select value(c) from c";
                if (scope.ToString().Equals("school", StringComparison.OrdinalIgnoreCase))
                {
                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"StuList-{code}") }))
                    {
                        using var json = await JsonDocument.ParseAsync(item.ContentStream);
                        if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
                        {
                            foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
                            {
                                //List<Students> stu = obj.GetProperty("students").ToObject<List<Students>>();
                                stuList.Add(obj.ToObject<object>());
                                //stuList.Add(stu.Count);
                                //stuCount.Add(stu.Count);
                            }
                        }
                    }
                }
                else
                {
                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"StuList") }))
                    {
                        using var json = await JsonDocument.ParseAsync(item.ContentStream);
                        if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
                        {
                            foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
                            {
                                //List<Students> stu = obj.GetProperty("students").ToObject<List<Students>>();
                                stuList.Add(obj.ToObject<object>());
                                //stuList.Add(stu.Count);
                                //stuCount.Add(stu.Count);
                            }
                        }
                    }
                }

                return Ok(new { stuList });
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，course/find-list()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }

        }

        //查询名单
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "Teacher")]
        [HttpPost("get-summary-list")]
        public async Task<IActionResult> getSummary(JsonElement requert)
        {
            try
            {
                if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
                if (!requert.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
                if (!requert.TryGetProperty("ids", out JsonElement classId)) return BadRequest();
                var client = _azureCosmos.GetCosmosClient();
                List<object> stuList = new();
                //List<int> stuCount = new List<int>();
                List<string> ids = new();
                ids = classId.ToObject<List<string>>();
                if (!(ids.Count > 0)) return BadRequest();
                //List<Students> stu = new();
                var query = $"select c.id,c.name,c.students,c.tmids,c.no,c.code,c.scope,c.school,c.creatorId from c where c.id in ({string.Join(",", ids.Select(o => $"'{o}'"))})";
                if (scope.ToString().Equals("school", StringComparison.OrdinalIgnoreCase))
                {
                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"StuList-{code}") }))
                    {
                        using var json = await JsonDocument.ParseAsync(item.ContentStream);
                        if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
                        {
                            foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
                            {
                                //stu = obj.GetProperty("students").ToObject<List<Students>>();
                                stuList.Add(obj.ToObject<object>());
                                //stuList.Add(stu.Count);
                                //stuCount.Add(stu.Count);
                            }
                        }
                    }
                }
                else
                {
                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"StuList") }))
                    {
                        using var json = await JsonDocument.ParseAsync(item.ContentStream);
                        if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
                        {
                            foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
                            {
                                //stu = obj.GetProperty("students").ToObject<List<Students>>();
                                stuList.Add(obj.ToObject<object>());
                                //stuList.Add(stu.Count);
                                //stuCount.Add(stu.Count);
                            }
                        }
                    }
                }

                return Ok(new { stuList });
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，course/get-summary-list()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }
        }

        //查询名单
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "Teacher")]
        [HttpPost("delete-list")]
        public async Task<IActionResult> deleteList(JsonElement requert)
        {
            try
            {
                if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
                if (!requert.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
                if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
                var client = _azureCosmos.GetCosmosClient();
                //var query = $"select c.id,c.name,c.students,c.tmids from c where c.id in ({string.Join(",", ids.Select(o => $"'{o}'"))})";
                if (scope.ToString().Equals("school", StringComparison.OrdinalIgnoreCase))
                {
                    /*List<string> classIds = new List<string>();
                    var query = $"select c.id from c join A0 in c.schedule where A0.teacherId = '{id}'";
                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{id}") }))
                    {
                        using var json = await JsonDocument.ParseAsync(item.ContentStream);
                        if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
                        {
                            var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
                            while (accounts.MoveNext())
                            {
                                JsonElement account = accounts.Current;
                                if (string.IsNullOrEmpty(account.GetProperty("id").GetString()))
                                {
                                    continue;
                                }
                                classIds.Add(account.GetProperty("id").GetString());
                                listClassInfo.Add((account.GetProperty("id").GetString(), account.GetProperty("scope").GetString()));
                            }
                        }
                    }*/
                    await client.GetContainer(Constant.TEAMModelOS, "School").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"StuList-{code}"));
                }
                else
                {
                    await client.GetContainer(Constant.TEAMModelOS, "Teacher").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"StuLis"));
                    /*await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"StuList") }))
                    {
                        using var json = await JsonDocument.ParseAsync(item.ContentStream);
                        if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
                        {
                            foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
                            {
                                List<Students> stu = obj.GetProperty("students").ToObject<List<Students>>();
                                stuList.Add(obj.ToObject<object>());
                                //stuList.Add(stu.Count);
                                //stuCount.Add(stu.Count);
                            }
                        }
                    }*/
                }

                return Ok(new { id });
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，course/delete-list()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }
        }
    }
}
