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

namespace TEAMModelOS.Controllers
{
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    //[Authorize(Roles = "IES5")]
    [Route("teacher/comment")]
    [ApiController]
    public class CommentController : ControllerBase
    {
        private readonly AzureCosmosFactory _azureCosmos;
        private readonly DingDing _dingDing;
        private readonly Option _option;
        private readonly AzureStorageFactory _azureStorage;
        public IConfiguration _configuration { get; set; }
        private readonly AzureServiceBusFactory _serviceBus;
        public CommentController(AzureCosmosFactory azureCosmos, DingDing dingDing, IOptionsSnapshot<Option> option, AzureStorageFactory azureStorage, AzureServiceBusFactory serviceBus, IConfiguration configuration)
        {
            _azureCosmos = azureCosmos;
            _dingDing = dingDing;
            _option = option?.Value;
            _azureStorage = azureStorage;
            _serviceBus = serviceBus;
            _configuration = configuration;
        }

        /// <summary>
        /// 添加教师评语快捷回复
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [HttpPost("add-comment")]
        public async Task<IActionResult> AddComment(JsonElement request)
        {
            //var id = "Comment-" + request.TEAMModelId.Replace("#", "");
            //ResponseBuilder builder = ResponseBuilder.custom();
            //List<Comment> comments = await _azureCosmos.FindByDict<Comment>(new Dictionary<string, object> { { "code", request.TEAMModelId }, { "id", id } });
            //Comment comment = new Comment();
            //if (comments.IsEmpty())
            //{
            //    comment.id = id;
            //    comment.code = request.TEAMModelId;
            //    comment.comment.Add(request.comment);
            //    comments.Add(comment);
            //}
            //else {
            //    comment = comments[0];
            //    comment.comment.Add(request.comment);
            //}
            //builder.Data(await _azureCosmos.SaveOrUpdate(comment));
            //return builder.build();
            //return Ok(await _azureCosmos.SaveOrUpdate(comment));
            return Ok();
        }

        /// <summary>
        /// 查询教师评语罐头
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [HttpPost("find-comment")]
        public async Task<IActionResult> findComment(JsonElement requert)
        {
            //var client = _azureCosmos.GetCosmosClient();
            //if (!requert.TryGetProperty("school_code", out JsonElement school_code)) return BadRequest();
            ////var (id, name, picture, _) = HttpContext.GetAuthTokenInfo();
            //if (!requert.TryGetProperty("id_token", out JsonElement id_token)) return BadRequest();
            //var jwt = new JwtSecurityToken(id_token.GetString());
            //if (!jwt.Payload.Iss.Equals("account.teammodel", StringComparison.Ordinal)) return BadRequest();
            //var id = jwt.Payload.Sub;

            //List<object> comments = new List<object>();
            //var query = $"select c.id,c.comment from c";
            //await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Comment-{id}") }))
            //{
            //    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())
            //        {
            //            comments.Add(obj.ToObject<object>());
            //        }
            //    }
            //}

            return Ok();
        }
        /// <summary>
        /// 更新保存教师评语罐头,如果评语列表为空则删除
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [HttpPost("upsert-comment")]
        public async Task<IActionResult> UpsertComment(Comment request)
        {
            // request.TryAdd("PartitionKey", request.lang);
            //ResponseBuilder builder = ResponseBuilder.custom();
            //Comment comment = null;
            //if (request.comment.Count > 0)
            //{
            //    if (string.IsNullOrEmpty(request.id)) {
            //        request.id  = "Comment-" + request.code.Replace("#", "");
            //    }
            //    comment = await _azureCosmos.SaveOrUpdate<Comment>(request);
            //}
            //else {
            //    if (!string.IsNullOrEmpty(request.id))
            //    {
            //        IdPk idPk = await _azureCosmos.DeleteAsync<Comment>(request.id, request.code);
            //    }

            //}
            ////return builder.Data(comment).build();
            return Ok();
        }

        //批注
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "Teacher")]
        [HttpPost("upsert-answer")]
        public async Task<IActionResult> upsertAnswer(JsonElement request)
        {

            if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
            if (!request.TryGetProperty("mark", out JsonElement mark)) return BadRequest();
            if (!request.TryGetProperty("studentId", out JsonElement studentId)) return BadRequest();
            if (!request.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
            if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
            //if (!request.TryGetProperty("classId", out JsonElement classId)) return BadRequest();
            if (!request.TryGetProperty("index", out JsonElement itemIndex)) return BadRequest();
            //根据不同评测的类型返回对应的编码
            if (!request.TryGetProperty("code", out JsonElement school)) return BadRequest();
            try
            {
                var client = _azureCosmos.GetCosmosClient();
                List<ExamClassResult> examClassResults = new List<ExamClassResult>();
                await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(
                    queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and array_contains(c.studentIds,'{studentId}')",
                    requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school}") }))
                {
                    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())
                        {
                            examClassResults.Add(obj.ToObject<ExamClassResult>());
                        }
                    }
                }
                ExamClassResult classResult = new ExamClassResult();
                Details ans = mark.ToObject<Details>();
                List<List<string>> standard = new List<List<string>>();
                List<double> points = new List<double>();
                List<Task<string>> tasks = new List<Task<string>>();
                foreach (ExamClassResult result in examClassResults)
                {
                    int index = result.studentIds.IndexOf(studentId.ToString());
                    /*StringBuilder builder = new StringBuilder();
                    builder.Append(result.examId).Append("/");
                    builder.Append(result.subjectId).Append("/");
                    builder.Append(studentId).Append("mark").Append("/");
                    //builder.Append(tId).Append('/');
                    builder.Append("ans.json");
                    *//*string FileName = result.examId + "/" + result.subjectId + "/" + studentId;
                    string blob = FileName + "/" + "ans.json";*//*
                    tasks.Add(_azureStorage.UploadFileByContainer(school.ToString(), ans.ToJsonString(), "exam", builder.ToString(), false));
                    //result.studentAnswers[newIndex].Add(builder.ToString());
                    *//*string FileName = result.examId + "/" + result.subjectId + "/" + studentId + "mark";
                    string blob = await _azureStorage.UploadFileByContainer(school.ToString(), ans.ToJsonString(), "exam", FileName + "/" + "ans.json");*//*
                    //result.studentAnswers[index].Add(blob);*/
                    List<Details> details = result.mark[index][itemIndex.GetInt32()];
                    if (details.Count > 0)
                    {
                        List<Details> ds = details.Where(x => x.tmdId.Equals(tId.GetString())).ToList();
                        if (ds.Count > 0)
                        {
                            foreach (Details de in ds)
                            {
                                if (de.tmdId.Equals(ans.tmdId))
                                {
                                    de.mark = ans.mark;
                                    de.sc = ans.sc;
                                    //de.index = itemIndex.GetInt32();
                                }
                            }
                        }
                        else {
                            result.mark[index][itemIndex.GetInt32()].Add(ans);
                        }
                    }
                    else {
                        result.mark[index][itemIndex.GetInt32()].Add(ans);
                    }
                    
                    /*result.mark[index][itemIndex.GetInt32()].Add(ans);
                    if (result.mark == null || result.mark.Count == 0)
                    {
                        List<List<string>> annotation = new List<List<string>>();
                        foreach (string ids in result.studentIds)
                        {
                            annotation.Add(new List<string>());
                        }
                        result.mark = annotation;
                    }
                    result.mark[index].Add(builder.ToString());*/
                    classResult = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(result, result.id, new PartitionKey($"{result.code}"));
                }
                await Task.WhenAll(tasks);
               /* //变更blob 大小
                ExamInfo info = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamInfo>(id.ToString(), new Azure.Cosmos.PartitionKey($"Exam-{school}"));
                info.size = await _azureStorage.GetBlobContainerClient(school.ToString()).GetBlobsSize($"exam/{id}");
                var messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "annotation", root = $"exam/{id}", name = school }.ToJsonString());

                messageBlob.ApplicationProperties.Add("name", "BlobRoot");
                var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
                await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);*/
                return Ok(new { classResult });
            }
            catch (Exception e)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，teacher/comment/upsertAnswer()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }

        }


        [ProducesDefaultResponseType]
        [HttpPost("tch-activity-count")]
        [AuthToken(Roles = "admin,teacher")]
        public async Task<IActionResult> TchActivityCount(JsonElement requert) {
            var (id, _, _, school) = HttpContext.GetAuthTokenInfo();
            var client = _azureCosmos.GetCosmosClient();
            HashSet<string> classes = new HashSet<string>();
            HashSet<string> stulist = new HashSet<string>();
            //获取学校的名单：
            List<Schedule> schedules = new List<Schedule>();
            string scheduleSql = $"SELECT   c.schedule  FROM c join scdl in c.schedule where c.pk='Course' and scdl.teacherId='{id}'";
            await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<Course>(scheduleSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{school}") }))
            {
                schedules.AddRange(item.schedule);
            }
            schedules.ForEach(x => {
                if (!string.IsNullOrEmpty(x.classId)) {
                    classes.Add(x.classId);
                }
                if (!string.IsNullOrEmpty(x.stulist))
                {
                    stulist.Add(x.stulist);
                }
            });
            List<string> types = new List<string> { "Exam", "Survey" ,"Vote"};
            List<MQActivity> datas = new List<MQActivity>();
            List<KeyValuePair<string, int>> count = new List<KeyValuePair<string, int>>();
            foreach (var type in types) {
                string pksql = $"  c.pk='{type}' ";
                string joinSqlClasses = "";
                string andSqlClasses = "";
                if (classes.ToList().IsNotEmpty())
                {
                    joinSqlClasses = " join A1 in c.classes ";
                    List<string> sqlList = new List<string>();
                    classes.ToList().ForEach(x => { sqlList.Add($" '{x}' "); });
                    string sql = string.Join(" , ", sqlList);
                    andSqlClasses = $"   A1 in ({sql}) ";
                }
                string joinSqlStulist = "";
                string andSqlStulist = "";
                if (stulist.ToList().IsNotEmpty())
                {
                    joinSqlStulist = " join A1 in c.stuLists ";
                    List<string> sqlList = new List<string>();
                    stulist.ToList().ForEach(x => { sqlList.Add($" '{x}' "); });
                    string sql = string.Join(" , ", sqlList);
                    andSqlStulist = $"   A1 in ({sql}) ";
                }
                string classesSql = "";
                if (!string.IsNullOrWhiteSpace(joinSqlClasses))
                {
                    classesSql = $" and    {andSqlClasses }  ";
                }
                int acount = 0;
                if (!string.IsNullOrWhiteSpace(school) && classes.ToList().IsNotEmpty()) {
                    string querySchool = $" 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 {joinSqlClasses}   where   {pksql}    {classesSql}";
                    //查询数据归属学校的
                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<MQActivity>(querySchool, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{type}-{school}") }))
                    {
                        if (item.progress.Equals("going", StringComparison.OrdinalIgnoreCase)) {
                            datas.Add(item);
                        }
                        acount += 1;
                    }
                }
                string stuListsSql = "";
                if (!string.IsNullOrWhiteSpace(joinSqlStulist))
                {
                    stuListsSql = $" and    {andSqlStulist }  ";
                }
               
                if (!string.IsNullOrWhiteSpace(school) && stulist.ToList().IsNotEmpty())
                {
                    string querySchool = $" 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 {joinSqlStulist}   where   {pksql}    {stuListsSql}";
                    //查询数据归属学校的
                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<MQActivity>(querySchool, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{type}-{school}") }))
                    {
                        if (item.progress.Equals("going", StringComparison.OrdinalIgnoreCase))
                        {
                            datas.Add(item);
                        }
                        acount += 1;
                    }
                }
                string queryTeacher = $" 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   {pksql}  ";
                //查询数据归属个人的
                await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<MQActivity>(queryTeacher, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{type}-{id}") }))
                {
                    acount += 1;
                    if (item.progress.Equals("going", StringComparison.OrdinalIgnoreCase))
                    {
                        datas.Add(item);
                    }
                }
                KeyValuePair<string,int> valuePair = new KeyValuePair<string, int>(type, acount);
                count.Add(valuePair);
            }
            return Ok(new { totalCount=count ,goingDatas=datas});
        }



        /// <summary>
        /// 教师端，查询活动所有活动类型的列表，班主任，任课教师等
        /// 执教班级
        /// </summary>
        /// <param name="request">
        /// 教师tmdid                          !userid:"1255868536"   
        ///学校编码                            !school:"hbcn"
        ///执教的班级信息                      !classes:[{"classid":"S-C-00001","scope":"school"},{"classid":"P-C-00004","scope":"private"}]   TODO  需要排查 对象和班级字符串id设计原因 {"classid":"S-C-00001","scope":"school"}
        ///执教的科目                          ?subjects:["subjectid1","subjectid2"]
        ///活动类型                            !"pk":"Vote"/"Exam"/"Homework"/"Learn"/"Survey"" // Vote投票 Survey问卷 Exam评测 Learn学习活动 Homework作业活动
        ///时间筛选范围开始时间 默认30天之前   ?"stime":1608274766154  
        ///时间筛选范围结束时间 默认当前时间   ?"etime":1608274766666 
        ///每页大小     ?"count":10/null/Undefined  
        ///分页Token    ?"continuationToken":Undefined/null/"[{\"token\":\"+RID:~omxMAP3ipcSEEwAAAAAAAA==#RT:2#TRC:20#ISV:2#IEO:65551#QCF:1#FPC:AYQTAAAAAAAAiRMAAAAAAAA=\",\"range\":{\"min\":\"\",\"max\":\"FF\"}}]"
        ///当前状态     ?"progress":Undefined/null/"" 表示两种状态都要查询/ "going"/"finish" 表示查询进行中/ 或者已完成 学生端只能查询正在进行或已经结束 going 已发布|finish 已结束  
        /// </param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [HttpPost("tch-activity")]
        //[AuthToken(Roles = "teacher")]
        public async Task<IActionResult> TchActivity(JsonElement requert)
        {
            var (id, _, _, school) = HttpContext.GetAuthTokenInfo();
            if (string.IsNullOrWhiteSpace(school))
            {
                if (requert.TryGetProperty("school", out JsonElement schoolcode))
                {
                    if (!schoolcode.ValueKind.Equals(JsonValueKind.Undefined) && !schoolcode.ValueKind.Equals(JsonValueKind.Null) && schoolcode.ValueKind.Equals(JsonValueKind.String))
                    {
                        school = schoolcode.GetString();
                    }
                }
            }
            if (string.IsNullOrWhiteSpace(id))
            {
                if (requert.TryGetProperty("userid", out JsonElement userid))
                {
                    if (!userid.ValueKind.Equals(JsonValueKind.Undefined) && !userid.ValueKind.Equals(JsonValueKind.Null) && userid.ValueKind.Equals(JsonValueKind.String))
                    {
                        id = userid.GetString();
                    }
                }
            }
            //var stimestamp = DateTimeOffset.UtcNow.AddDays(-30).ToUnixTimeMilliseconds();
            //if (requert.TryGetProperty("stime", out JsonElement stime))
            //{
            //    if (!stime.ValueKind.Equals(JsonValueKind.Undefined) && !stime.ValueKind.Equals(JsonValueKind.Null) && stime.TryGetInt64(out long data))
            //    {
            //        stimestamp = data;
            //    }
            //}
            //string stimesql = $" c.startTime >= {stimestamp}  ";
            //var etimestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            //string etimesql = $" and c.startTime <= {etimestamp}   ";
            //var progresssql = "";
            //if (requert.TryGetProperty("progress", out JsonElement progress))
            //{
            //    if (!progress.ValueKind.Equals(JsonValueKind.Undefined) && !progress.ValueKind.Equals(JsonValueKind.Null) && progress.ValueKind.Equals(JsonValueKind.String))
            //    {
            //        progresssql = $" and c.progress='{progress}' ";
            //    }
            //}
            var pksql = "";
            string type = null;
            if (requert.TryGetProperty("pk", out JsonElement pk))
            {
                if (!pk.ValueKind.Equals(JsonValueKind.Undefined) && !pk.ValueKind.Equals(JsonValueKind.Null) && pk.ValueKind.Equals(JsonValueKind.String))
                {
                    pksql = $"  c.pk='{pk}' ";
                    type = $"{pk}";
                }
            }
            if (string.IsNullOrEmpty(type)) { return BadRequest("type is required!"); }
            string continuationTokenSchool = null;
            //默认不指定返回大小
            int? topcout = null;
            if (requert.TryGetProperty("count", out JsonElement jcount))
            {
                if (!jcount.ValueKind.Equals(JsonValueKind.Undefined) && !jcount.ValueKind.Equals(JsonValueKind.Null) && jcount.TryGetInt32(out int data))
                {
                    topcout = data;
                }
            }
            //是否需要进行分页查询，默认不分页
            bool iscontinuation = false;
            if (topcout != null && topcout.Value > 0)
            {
                iscontinuation = true;
            }
            //如果指定了返回大小
            if (requert.TryGetProperty("continuationTokenSchool", out JsonElement continuationSchool))
            {
                //指定了cancellationToken continuationSchool
                if (!continuationSchool.ValueKind.Equals(JsonValueKind.Null) && continuationSchool.ValueKind.Equals(JsonValueKind.String))
                {
                    continuationTokenSchool = continuationSchool.GetString();

                }
            }
            //班级
            string joinSqlClasses = "";
            string andSqlClasses = "";

            string joinSqlStulist = "";
            string andSqlStulist = "";
            List<string> classes = null;
            if (requert.TryGetProperty("classes", out JsonElement jclasses))
            {
                if (jclasses.ValueKind is JsonValueKind.Array)
                {
                    classes = jclasses.ToObject<List<string>>();
                    if (classes.IsNotEmpty())
                    { 
                        //行政班
                        joinSqlClasses = " join A1 in c.classes ";
                        List<string> sqlListc = new List<string>();
                        classes.ForEach(x => { sqlListc.Add($" '{x}' "); });
                        string sqlc = string.Join(" , ", sqlListc);
                        andSqlClasses = $"    A1 in ({sqlc}) ";
                        //教学班
                        joinSqlStulist = " join A1 in c.stuLists ";
                        List<string> sqlListl = new List<string>();
                        classes.ForEach(x => { sqlListl.Add($" '{x}' "); });
                        string sqll = string.Join(" , ", sqlListl);
                        andSqlStulist = $"    A1 in ({sqll}) ";
                    }
                }
            }

          
            string classesSql = "";
            if (!string.IsNullOrWhiteSpace(joinSqlClasses))
            {
                classesSql = $" and    {andSqlClasses }  ";
            }
            string stuListsSql = "";
            if (!string.IsNullOrWhiteSpace(joinSqlStulist))
            {
                stuListsSql = $" and    {andSqlStulist }  ";
            }
            List<JsonElement> datas = new List<JsonElement>();
            var client = _azureCosmos.GetCosmosClient();
            //班主任 ，任课教师只需要查询两种校园活动 和班级活动 ，  不查询私人教室创建的活动。  
            if (!string.IsNullOrWhiteSpace(school) && classes.IsNotEmpty())
            {
                //string querySchool = $" SELECT distinct  value c   FROM c {joinSqlClasses} {joinSqlSubjects}  where {stimesql}  {etimesql}  {progresssql}  {typesql}  {andSqlSubjects}  {tgSql}";
                string querySchoolclss = $" 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 {joinSqlClasses}   where   {pksql}    {classesSql}";
                //查询数据归属学校的
                await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(querySchoolclss, continuationToken: continuationTokenSchool, requestOptions: new QueryRequestOptions() { MaxItemCount = topcout, PartitionKey = new PartitionKey($"{type}-{school}") }))
                {
                    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())
                        {
                            datas.Add(obj.ToObject<JsonElement>());
                        }
                        //如果需要分页则跳出
                        if (iscontinuation)
                        {
                            continuationTokenSchool = item.GetContinuationToken();
                            break;
                        }
                    }
                }
                string querySchoollist = $" 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 {joinSqlStulist}   where   {pksql}    {stuListsSql}";
                await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(querySchoollist, continuationToken: continuationTokenSchool, requestOptions: new QueryRequestOptions() { MaxItemCount = topcout, PartitionKey = new PartitionKey($"{type}-{school}") }))
                {
                    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())
                        {
                            datas.Add(obj.ToObject<JsonElement>());
                        }
                        //如果需要分页则跳出
                        if (iscontinuation)
                        {
                            continuationTokenSchool = item.GetContinuationToken();
                            break;
                        }
                    }
                }
            }
            string continuationTokenTeacher = null;
            //如果指定了返回大小
            if (requert.TryGetProperty("continuationTokenTeacher", out JsonElement continuationTeacher))
            {
                //指定了cancellationToken continuationSchool
                if (!continuationTeacher.ValueKind.Equals(JsonValueKind.Null) && continuationTeacher.ValueKind.Equals(JsonValueKind.String))
                {
                    continuationTokenTeacher = continuationTeacher.GetString();

                }
            }
            string queryTeacher = $" 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   {pksql}  ";
            //查询数据归属学校的
            await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryTeacher, continuationToken: continuationTokenSchool, requestOptions: new QueryRequestOptions() { MaxItemCount = topcout, PartitionKey = new PartitionKey($"{type}-{id}") }))
            {
                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())
                    {
                        datas.Add(obj.ToObject<JsonElement>());
                    }
                    //如果需要分页则跳出
                    if (iscontinuation)
                    {
                        continuationTokenTeacher = item.GetContinuationToken();
                        break;
                    }
                }
            }
            return Ok(new { datas, continuationTokenSchool, continuationTokenTeacher });
        }
    }
}
