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.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using TEAMModelOS.Models;
using TEAMModelOS.Models.Dto;
using TEAMModelOS.SDK.Models;
using TEAMModelOS.SDK;
using TEAMModelOS.SDK.DI;
using TEAMModelOS.SDK.DI.AzureCosmos.Inner;
using TEAMModelOS.SDK.Extension;
using TEAMModelOS.SDK.Helper.Common.StringHelper;
using System.Dynamic;
using Azure;
using TEAMModelOS.SDK.Models.Cosmos.Common;
using Azure.Messaging.ServiceBus;
using Microsoft.Extensions.Configuration;
using TEAMModelOS.Filter;
using Azure.Storage.Blobs.Models;
using HTEXLib.COMM.Helpers;

namespace TEAMModelOS.Controllers
{
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    //[Authorize(Roles = "IES5")]
    [Route("school/course")]
    [ApiController]
    public class CourseController : 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 CourseController(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;
        }

        /// <summary>
        /// 更新保存课程
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [AuthToken(Roles = "teacher")]
        [HttpPost("upsert")]
        public async Task<IActionResult> upsert(JsonElement requert)
        {
            try
            {
                (string id, _, _, string school) = HttpContext.GetAuthTokenInfo();
                Course course = new Course();
                if (!requert.TryGetProperty("course", out JsonElement _course)) return BadRequest();
                if (!requert.TryGetProperty("option", out JsonElement option)) return BadRequest();
                if (!requert.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
                course = _course.ToObject<Course>();
                var client = _azureCosmos.GetCosmosClient();
                course.pk = typeof(Course).Name;
                if (course.scope.Equals("school", StringComparison.OrdinalIgnoreCase))
                {
                    course.school = school;
                    course.creatorId = id;
                }
                else
                {
                    course.creatorId = id;
                }
                string code = course.code;
                course.code = typeof(Course).Name + "-" + course.code;
                if (option.ToString().Equals("insert"))
                {
                    if (scope.ToString().Equals("school", StringComparison.OrdinalIgnoreCase))
                    {
                        var response = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(course.id, new PartitionKey($"Course-{code}"));
                        if (response.Status == 200)
                        {
                            return Ok(new { error = ResponseCode.DATA_EXIST, V = "课程编码已经存在！" });
                        }
                        else
                        {
                            CourseChange courseChange = new CourseChange { id = course.id, code = course.code, name = course.name, scope = course.scope, school = course.school, creatorId = course.creatorId };
                            courseChange.addClass = course.schedule.Select(x => x.classId).ToList();
                            courseChange.addList = course.schedule.Select(x => x.stulist).ToList();
                            course = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync(course, new PartitionKey($"Course-{code}"));
                        }
                    }
                    else
                    {
                        var response = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync(course.id, new PartitionKey($"Course-{code}"));
                        if (response.Status == 200)
                        {
                            return Ok(new { error = ResponseCode.DATA_EXIST, V = "课程编码已经存在！" });
                        }
                        else
                        {
                            CourseChange courseChange = new CourseChange { id = course.id, code = course.code, name = course.name, scope = course.scope, school = course.school, creatorId = course.creatorId };
                            courseChange.addClass = course.schedule.Select(x => x.classId).ToList();
                            courseChange.addList = course.schedule.Select(x => x.stulist).ToList();
                            var messageBlob = new ServiceBusMessage(courseChange.ToJsonString()); ;
                            messageBlob.ApplicationProperties.Add("name", "Course");
                            var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
                            await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
                            course = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync(course, new PartitionKey($"Course-{code}"));
                        }
                    }
                }
                else
                {
                    if (scope.ToString().Equals("school", StringComparison.OrdinalIgnoreCase))
                    {

                        Course odlCourse = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<Course>(course.id, new PartitionKey($"Course-{code}"));
                        CourseChange courseChange = new CourseChange { id = course.id, code = course.code, name = course.name, scope = course.scope, school = code };
                        var oldCls = odlCourse.schedule.Select(x => x.classId).ToList();
                        var oldLst = odlCourse.schedule.Select(x => x.stulist).ToList();
                        var newCls = course.schedule.Select(x => x.classId).ToList();
                        var newLst = course.schedule.Select(x => x.stulist).ToList();
                        List<string> addCls = new List<string>();
                        List<string> addLst = new List<string>();
                        List<string> delCls = new List<string>();
                        List<string> delLst = new List<string>();
                        oldCls.ForEach(x =>
                        {
                            if (!newCls.Contains(x))
                            {
                                delCls.Add(x);
                            }
                        });
                        newCls.ForEach(x =>
                        {
                            if (!oldCls.Contains(x))
                            {
                                addCls.Add(x);
                            }
                        });
                        oldLst.ForEach(x =>
                        {
                            if (!newLst.Contains(x))
                            {
                                delLst.Add(x);
                            }
                        });
                        newLst.ForEach(x =>
                        {
                            if (!oldLst.Contains(x))
                            {
                                addLst.Add(x);
                            }
                        });
                        courseChange.addClass = addCls;
                        courseChange.addList = addLst;
                        courseChange.delClass = delCls;
                        courseChange.delList = delLst;
                        course = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync(course, course.id, new PartitionKey($"Course-{code}"));
                        var messageBlob = new ServiceBusMessage(courseChange.ToJsonString()); ;
                        messageBlob.ApplicationProperties.Add("name", "Course");
                        var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
                        await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
                    }
                    else
                    {
                        Course odlCourse = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Course>(course.id, new PartitionKey($"Course-{code}"));
                        CourseChange courseChange = new CourseChange { id = course.id, code = course.code, name = course.name, scope = course.scope, creatorId = code };
                        var oldCls = odlCourse.schedule.Select(x => x.classId).ToList();
                        var oldLst = odlCourse.schedule.Select(x => x.stulist).ToList();
                        var newCls = course.schedule.Select(x => x.classId).ToList();
                        var newLst = course.schedule.Select(x => x.stulist).ToList();
                        List<string> addCls = new List<string>();
                        List<string> addLst = new List<string>();
                        List<string> delCls = new List<string>();
                        List<string> delLst = new List<string>();
                        oldCls.ForEach(x =>
                        {
                            if (!newCls.Contains(x))
                            {
                                delCls.Add(x);
                            }
                        });
                        newCls.ForEach(x =>
                        {
                            if (!oldCls.Contains(x))
                            {
                                addCls.Add(x);
                            }
                        });
                        oldLst.ForEach(x =>
                        {
                            if (!newLst.Contains(x))
                            {
                                delLst.Add(x);
                            }
                        });
                        newLst.ForEach(x =>
                        {
                            if (!oldLst.Contains(x))
                            {
                                addLst.Add(x);
                            }
                        });
                        courseChange.addClass = addCls;
                        courseChange.addList = addLst;
                        courseChange.delClass = delCls;
                        courseChange.delList = delLst;
                        course = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(course, course.id, new PartitionKey($"Course-{code}"));
                        var messageBlob = new ServiceBusMessage(courseChange.ToJsonString()); ;
                        messageBlob.ApplicationProperties.Add("name", "Course");
                        var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
                        await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
                    }
                }
                return Ok(new { course });
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，course/upsert()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }

        }


        [ProducesDefaultResponseType]
        [HttpPost("check")]
        public async Task<IActionResult> check(JsonElement json)
        {
            try
            {
                if (!json.TryGetProperty("tId", out JsonElement tId)) return BadRequest();
                if (!json.TryGetProperty("timeId", out JsonElement timeId)) return BadRequest();
                if (!json.TryGetProperty("code", out JsonElement code)) return BadRequest();
                if (!json.TryGetProperty("week", out JsonElement week)) return BadRequest();
                if (!json.TryGetProperty("cId", out JsonElement cId)) return BadRequest();
                var client = _azureCosmos.GetCosmosClient();
                var query = $"SELECT A0.room,A0.classId,A0.teacherId,A0.stulist,A0.time FROM c join A0 in c.schedule join A1 in A0.time where A0.teacherId = '{tId}'and A1.id = '{timeId}' and A1.week = '{week}' ";
                List<Schedule> teachers = new();
                await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{code}") }))
                {
                    using var jsonCheck = await JsonDocument.ParseAsync(item.ContentStream);
                    if (jsonCheck.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
                    {
                        foreach (var obj in jsonCheck.RootElement.GetProperty("Documents").EnumerateArray())
                        {
                            teachers.Add(obj.ToObject<Schedule>());
                        }
                    }
                }
                if (teachers.Count > 0)
                {
                    return Ok(new { msg = "该教师已有课程安排", code = 1 });
                }
                else
                {
                    var queryClass = $"SELECT A0.room,A0.classId,A0.teacherId,A0.stulist,A0.time FROM c join A0 in c.schedule join A1 in A0.time where A1.id = '{timeId}' and A1.week = '{week}' and (A0.classId = '{cId}' or A0.stulist = '{cId}')";
                    List<Schedule> courses = new();
                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: queryClass, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{code}") }))
                    {
                        using var jsonCheck = await JsonDocument.ParseAsync(item.ContentStream);
                        if (jsonCheck.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
                        {
                            foreach (var obj in jsonCheck.RootElement.GetProperty("Documents").EnumerateArray())
                            {
                                courses.Add(obj.ToObject<Schedule>());
                            }
                        }
                    }
                    if (courses.Count > 0)
                    {
                        return Ok(new { msg = "该名单已有课程安排", code = 2 });
                    }
                }
                return Ok(new { code = 0 });
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，course/check()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }
        }
        
        /// <summary>
        /// 查询课程
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "Teacher")]
        [HttpPost("find")]
        public async Task<IActionResult> Find(JsonElement requert)
        {
            if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
            if (!requert.TryGetProperty("scope", out JsonElement scope)) return BadRequest();

            try
            {
                var client = _azureCosmos.GetCosmosClient();
                List<object> courses = new List<object>();

                /*string continuationToken = string.Empty;
                string token = default;
                //是否需要进行分页查询，默认不分页
                //bool iscontinuation = false;
                if (requert.TryGetProperty("token", out JsonElement token_1))
                {
                    token = token_1.GetString();
                    //iscontinuation = true;
                };
                //默认不指定返回大小
                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;
                    }
                }*/
                var query = $"select c.code,c.id,c.no,c.name,c.period,c.subject,c.scope 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($"Course-{code.GetString()}") }))
                    {
                        //continuationToken = item.GetContinuationToken();
                        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())
                            {
                                courses.Add(obj.ToObject<object>());
                            }
                        }
                        //break;
                    }
                }
                else
                {

                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{code.GetString()}") }))
                    {
                        //continuationToken = item.GetContinuationToken();
                        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())
                            {
                                courses.Add(obj.ToObject<object>());
                            }
                        }
                        //break;
                    }
                    if (requert.TryGetProperty("schoolId", out JsonElement schoolId))
                    {
                        var querySchool = $"select distinct c.code,c.id,c.no,c.name,c.period,c.subject,c.scope from c join A0 in c.schedule where A0.teacherId = '{code}'";
                        await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: querySchool, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{schoolId.GetString()}") }))
                        {
                            //continuationToken = item.GetContinuationToken();
                            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())
                                {
                                    courses.Add(obj.ToObject<object>());
                                }
                            }
                            //break;
                        }
                    };
                }
                return Ok(new { courses, courses.Count });
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，course/find()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }


            /* List<Course> data = new List<Course>();
             if (StringHelper.getKeyCount(request) > 0) {
                 data = await _azureCosmos.FindByDict<Course>(request);
             }
             return builder.Data(data).Extend(new Dictionary<string, object> { { "count", data.Count } }).build();*/
        }


        /// <summary>
        /// 查询课程
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "Teacher")]
        [HttpPost("find-all-by-teacher")]
        public async Task<IActionResult> FindByTeacher(JsonElement requert)
        {
            if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
            //if (!requert.TryGetProperty("tId", out JsonElement tId)) return BadRequest();
            //if (!requert.TryGetProperty("scope", out JsonElement scope)) return BadRequest();

            try
            {
                var client = _azureCosmos.GetCosmosClient();
                List<object> courses = new List<object>();
                List<(string id, string name, string scope)> teacherCourse = new();
                List<(string id, string name, string scope)> tcCourse = new();
                List<(string id, string name, string scope, List<(string id, string name, string type)> stuName)> ps = new();
                var query = $"select c.id,c.name,c.scope from c";

                await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{code.GetString()}") }))
                {
                    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;
                            teacherCourse.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString(), account.GetProperty("scope").GetString()));
                        }
                    }
                }
                foreach ((string s, string n, string sc) in teacherCourse)
                {
                    List<(string id, string name, string type)> sName = new();
                    List<Schedule> schedules = new List<Schedule>();
                    var querySc = $"SELECT A0.room,A0.classId,A0.teacherId,A0.stulist,A0.time FROM c join A0 in c.schedule where c.id = '{s}'";
                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<Schedule>(queryText: querySc, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{code.GetString()}") }))
                    {
                        schedules.Add(item);
                    }
                    if (schedules.Count > 0)
                    {
                        var queryInfo = $"select c.id ,c.name from c where c.id in ({string.Join(",", schedules.Select(o => $"'{o.stulist}'"))})";
                        await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIterator(queryText: queryInfo, 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)
                            {
                                var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
                                while (accounts.MoveNext())
                                {
                                    JsonElement account = accounts.Current;
                                    sName.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString(), "stuList"));
                                }
                            }
                        }
                    }
                    ps.Add((s, n, sc, sName));
                }
                if (requert.TryGetProperty("schoolId", out JsonElement schoolId))
                {
                    var querySchool = $"select distinct c.code,c.id,c.no,c.name,c.scope from c join A0 in c.schedule where A0.teacherId = '{code}'";
                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: querySchool, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{schoolId.GetString()}") }))
                    {
                        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;
                                tcCourse.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString(), account.GetProperty("scope").GetString()));
                            }
                        }
                    }
                    foreach ((string s, string n, string sc) in tcCourse)
                    {
                        List<Schedule> schedules = new List<Schedule>();
                        var querySc = $"SELECT A0.room,A0.classId,A0.teacherId,A0.stulist,A0.time FROM c join A0 in c.schedule where c.id = '{s}' and A0.teacherId = '{code}'";
                        await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<Schedule>(queryText: querySc, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{schoolId.GetString()}") }))
                        {
                            schedules.Add(item);
                        }
                        List<(string id, string name, string type)> sName = new();
                        if (schedules.Count > 0)
                        {
                            var queryInfo = $"select c.id ,c.name from c where c.id in ({string.Join(",", schedules.Select(o => $"'{o.stulist}'"))})";
                            await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: queryInfo, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"StuList-{schoolId.GetString()}") }))
                            {
                                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;
                                        sName.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString(), "stuList"));
                                    }
                                }
                            }
                            var queryClass = $"select c.id ,c.name from c where c.id in ({string.Join(",", schedules.Select(o => $"'{o.classId}'"))})";
                            await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: queryClass, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{schoolId.GetString()}") }))
                            {
                                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;
                                        sName.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString(), "class"));
                                    }
                                }
                            }
                        }
                        ps.Add((s, n, sc, sName));
                    }
                }



                var obj = ps.Select(p => new
                {
                    p.id,
                    p.name,
                    p.scope,
                    classes = p.stuName.Select(s => new { s.id, s.name, s.type })
                });


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


        /// <summary>
        /// 查询课程详情
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "Teacher")]
        [HttpPost("find-summary")]
        public async Task<IActionResult> FindSummary(JsonElement requert)
        {

            if (!requert.TryGetProperty("code", out JsonElement school_code)) return BadRequest();
            if (!requert.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
            if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
            try
            {
                var client = _azureCosmos.GetCosmosClient();
                List<object> courses = new List<object>();
                List<Course> courseList = new List<Course>();
                var query = $"select value(c) from c where c.id = '{id}'";
                //List<(string id, string code, string name)> listCourse = new List<(string id, string code, string name)>();
                if (scope.ToString().Equals("school", StringComparison.OrdinalIgnoreCase))
                {
                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<Course>(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{school_code.GetString()}") }))
                    {
                        courseList.Add(item);
                    }

                }
                else
                {
                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<Course>(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{school_code.GetString()}") }))
                    {
                        courseList.Add(item);
                    }
                }
                foreach (Course course in courseList)
                {
                    dynamic courseExtobj = new ExpandoObject();
                    courseExtobj.id = course.id;
                    courseExtobj.name = course.name;
                    courseExtobj.id = course.id;
                    courseExtobj.subject = course.subject;
                    courseExtobj.desc = course.desc;
                    courseExtobj.period = course.period;
                    courseExtobj.scope = course.scope;
                    courseExtobj.no = course.no;
                    courseExtobj.code = course.code;
                    List<object> scheList = new List<object>();
                    foreach (Schedule schedule in course.schedule)
                    {
                        dynamic scheduleExtobj = new ExpandoObject();
                        scheduleExtobj.classId = schedule.classId;
                        scheduleExtobj.teacherId = schedule.teacherId;
                        if (!string.IsNullOrEmpty(schedule.teacherId))
                        {
                            var response = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync(schedule.teacherId, new PartitionKey("Base"));
                            if (response.Status == 200)
                            {
                                using var json = await JsonDocument.ParseAsync(response.ContentStream);
                                Teacher teacher = json.ToObject<Teacher>();
                                scheduleExtobj.teacherName = teacher.name;
                            }
                        }
                        scheduleExtobj.stulist = schedule.stulist;
                        scheduleExtobj.time = schedule.time;
                        scheduleExtobj.room = schedule.room;
                        scheList.Add(scheduleExtobj);
                    }
                    courseExtobj.schedule = scheList;
                    courses.Add(courseExtobj);
                }

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


            /* List<Course> data = new List<Course>();
             if (StringHelper.getKeyCount(request) > 0) {
                 data = await _azureCosmos.FindByDict<Course>(request);
             }
             return builder.Data(data).Extend(new Dictionary<string, object> { { "count", data.Count } }).build();*/
        }
        /// <summary>
        /// 删除课程
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "Teacher")]
        [HttpPost("delete")]
        public async Task<IActionResult> Delete(JsonElement request)
        {
            try
            {
                if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
                if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
                if (!request.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
                //string school_code = code.ToString().Substring(typeof(Course).Name.Length + 1);
                var client = _azureCosmos.GetCosmosClient();
                if (scope.ToString().Equals("school"))
                {
                    Course course = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<Course>(id.ToString(), new PartitionKey($"Course-{code}"));
                    CourseChange courseChange = new CourseChange { id = course.id, code = course.code, name = course.name, scope = course.scope, school = course.school, creatorId = course.creatorId };
                    courseChange.delClass = course.schedule.Select(x => x.classId).ToList();
                    courseChange.delList = course.schedule.Select(x => x.stulist).ToList();
                    var messageBlob = new ServiceBusMessage(courseChange.ToJsonString()); ;
                    messageBlob.ApplicationProperties.Add("name", "Course");
                    var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
                    await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
                    await client.GetContainer(Constant.TEAMModelOS, "School").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"Course-{code}"));
                }
                else
                {
                    Course course = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Course>(id.ToString(), new PartitionKey($"Course-{code}"));
                    CourseChange courseChange = new CourseChange { id = course.id, code = course.code, name = course.name, scope = course.scope, school = course.school, creatorId = course.creatorId };
                    courseChange.delClass = course.schedule.Select(x => x.classId).ToList();
                    courseChange.delList = course.schedule.Select(x => x.stulist).ToList();
                    var messageBlob = new ServiceBusMessage(courseChange.ToJsonString()); ;
                    messageBlob.ApplicationProperties.Add("name", "Course");
                    var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
                    await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
                    await client.GetContainer(Constant.TEAMModelOS, "Teacher").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"Course-{code}"));
                }
                return Ok(new { id });
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"CN，{_option.Location}，course/delete()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }

        }
        /// <summary>
        /// 删除课程
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "Teacher")]
        [HttpPost("delete-all")]
        public async Task<IActionResult> DeleteAll(BatchOption request)
        {
            try
            {
                /*                if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
                                if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();*/
                var client = _azureCosmos.GetCosmosClient();
                if (request == null) return BadRequest();

                string school_code = request.code;

                if (request.scope.Equals("school", StringComparison.OrdinalIgnoreCase))
                {
                    List<Response> res = await client.GetContainer(Constant.TEAMModelOS, "School").DeleteItemsStreamAsync(request.ids, $"Course-{school_code}");
                }
                else
                {
                    List<Response> res = await client.GetContainer(Constant.TEAMModelOS, "Teacher").DeleteItemsStreamAsync(request.ids, $"Course-{school_code}");
                }

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

        /// <summary>
        /// 更新保存排课管理
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        //[ProducesDefaultResponseType]
        ////[AuthToken(Roles = "Teacher")]
        //[HttpPost("upsert-management")]
        //public async Task<IActionResult> upsertCourseManagement(CourseManagement requert)
        //{
        //    try
        //    {
        //        CourseManagement course = new CourseManagement();
        //        //course = room.ToObject<CourseManagement>();
        //        var client = _azureCosmos.GetCosmosClient();
        //        string code = requert.code;
        //        requert.code = "CourseManagement-" + requert.code;
        //        /*                if (requert.scope.Equals) { 

        //                        }*/
        //        var response = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(requert.id, new PartitionKey($"CourseManagement-{code}"));
        //        if (response.Status == 200)
        //        {
        //            course = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync(requert, requert.id, new PartitionKey($"CourseManagement-{code}"));
        //        }
        //        else
        //        {
        //            course = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync(requert, new PartitionKey($"CourseManagement-{code}"));
        //        }
        //        return Ok(new { course });
        //    }
        //    catch (Exception ex)
        //    {
        //        await _dingDing.SendBotMsg($"CoreAPI2，{_option.Location}，management/upsert()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
        //        return BadRequest();
        //    }

        //}

        /// <summary>
        /// 查询排课管理
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        //[ProducesDefaultResponseType]
        ////[AuthToken(Roles = "Teacher")]
        //[HttpPost("find-management")]
        //public async Task<IActionResult> FindManagement(JsonElement requert)
        //{
        //    //if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
        //    if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
        //    var client = _azureCosmos.GetCosmosClient();
        //    List<object> courses = new List<object>();
        //    StringBuilder sql = new StringBuilder();
        //    sql.Append("select c.code,c.id,c.name,c.courses,c.scope,c.teacher from c ");
        //    Dictionary<string, object> dict = new Dictionary<string, object>();
        //    var emobj = requert.EnumerateObject();
        //    while (emobj.MoveNext())
        //    {
        //        dict[emobj.Current.Name] = emobj.Current.Value;
        //    }
        //    //处理code
        //    if (dict.TryGetValue("code", out object _))
        //    {
        //        dict.Remove("code");
        //    }
        //    AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql);
        //    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"CourseManagement-{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())
        //            {
        //                courses.Add(obj.ToObject<object>());
        //            }
        //        }
        //    }
        //    return Ok(new { courses });
        //}
        //[ProducesDefaultResponseType]
        ////[AuthToken(Roles = "Teacher")]
        //[HttpPost("find-course")]
        //public async Task<IActionResult> FindCourse(JsonElement requert)
        //{
        //    if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
        //    if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
        //    var client = _azureCosmos.GetCosmosClient();
        //    List<object> courses = new List<object>();
        //    var query = $"select c.code,c.id,c.name,A0.course.id courseId,A0.course.name courseName ,A0.course.notice notice ,A1,c.scope,c.teacher from c  join A0  in c.courses join A1  in A0.teachers where A1.id = '{id}' ";
        //    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"CourseManagement-{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())
        //            {
        //                courses.Add(obj.ToObject<object>());
        //            }
        //        }
        //    }
        //    return Ok(new { courses });
        //}
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "Teacher")]
        [HttpPost("find-course-by-room")]
        public async Task<IActionResult> FindCourseByRoom(JsonElement requert)
        {
            if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
            if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
            if (!requert.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
            var client = _azureCosmos.GetCosmosClient();
            HashSet<Course> courseList = new HashSet<Course>();
            List<object> courses = new List<object>();
            //var query = $"select c.code,c.id,c.name from c join A0 in c.schedule where A0.classId = '{id}'";
            //此处存在不同老师在同一间教室上相同的课程
            if (scope.ToString().Equals("school", StringComparison.OrdinalIgnoreCase))
            {
                var query = $"select distinct value(c) from c join A0 in c.schedule where A0.room = '{id}'";
                await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<Course>(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{code}") }))
                {
                    courseList.Add(item);
                }
            }
            else
            {
                var query = $"select distinct value(c) from c join A0 in c.schedule where A0.room = '{id}'";
                await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<Course>(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{code}") }))
                {
                    courseList.Add(item);
                }
            }
            HashSet<string> teacherIds = new HashSet<string>();
            foreach (Course course in courseList)
            {
                foreach (Schedule schedule in course.schedule)
                {
                    teacherIds.Add(schedule.teacherId);
                }
            }
            List<(string id, string name)> teachers = new List<(string id, string name)>();
            if (teacherIds.Count > 0)
            {
                await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIterator(
                                    queryText: $"select c.id,c.name from c where c.id in ({ string.Join(",", teacherIds.Select(o => $"'{o}'"))})", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
                {
                    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;
                            teachers.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString()));
                        }
                    }
                }
            }
            foreach (Course course in courseList)
            {
                dynamic courseExtobj = new ExpandoObject();
                courseExtobj.id = course.id;
                courseExtobj.name = course.name;
                courseExtobj.subject = course.subject;
                courseExtobj.desc = course.desc;
                courseExtobj.period = course.period;
                courseExtobj.scope = course.scope;
                courseExtobj.no = course.no;
                courseExtobj.code = course.code;
                courseExtobj.pk = course.pk;
                List<object> scheList = new List<object>();
                foreach (Schedule schedule in course.schedule)
                {
                    dynamic scheduleExtobj = new ExpandoObject();
                    scheduleExtobj.classId = schedule.classId;
                    scheduleExtobj.teacherId = schedule.teacherId;
                    if (!string.IsNullOrEmpty(schedule.teacherId))
                    {
                        scheduleExtobj.teacherName = teachers.FirstOrDefault(c => c.id == schedule.teacherId).name;
                    }
                    scheduleExtobj.stulist = schedule.stulist;
                    scheduleExtobj.time = schedule.time;
                    scheduleExtobj.room = schedule.room;
                    scheList.Add(scheduleExtobj);
                }
                courseExtobj.schedule = scheList;
                courses.Add(courseExtobj);
            }
            return Ok(new { courses });
        }

        //[ProducesDefaultResponseType]
        ////[AuthToken(Roles = "Teacher")]
        //[HttpPost("upsert-notice")]
        //public async Task<IActionResult> upsertNotice(JsonElement requert)
        //{
        //    if (!requert.TryGetProperty("courseId", out JsonElement courseId)) return BadRequest();
        //    if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
        //    if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
        //    if (!requert.TryGetProperty("notice", out JsonElement notice)) return BadRequest();
        //    if (!requert.TryGetProperty("A1", out JsonElement teacherInfo)) return BadRequest();
        //    Teachers teachers = teacherInfo.ToObject<Teachers>();
        //    var client = _azureCosmos.GetCosmosClient();
        //    List<CourseManagement> courseManagements = new List<CourseManagement>();

        //    StringBuilder sql = new StringBuilder();
        //    sql.Append("select value(c) from c");
        //    Dictionary<string, object> dict = new Dictionary<string, object>();
        //    //dict.Add("id", id);
        //    dict.Add("courses[*].course.id", courseId);
        //    dict.Add("courses[*].teachers[*].id", teachers.id);
        //    //dict.Add("id", classroom.id);
        //    AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql);
        //    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"CourseManagement-{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())
        //            {
        //                courseManagements.Add(obj.ToObject<CourseManagement>());
        //            }
        //        }
        //    }
        //    for (int i = 0; i < courseManagements.Count; i++)
        //    {
        //        for (int j = 0; j < courseManagements[i].courses.Count; j++)
        //        {
        //            if (courseManagements[i].courses[j].course.id.Equals(courseId.ToString()))
        //            {
        //                courseManagements[i].courses[j].course.notice = notice.ToString();
        //                await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync(courseManagements[i], courseManagements[i].id, new PartitionKey($"{courseManagements[i].code}"));
        //                break;
        //            }
        //        }
        //    }
        //    return Ok(new { id });
        //}




        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "Teacher")]
        [HttpPost("upsert-teacher-course")]
        public async Task<IActionResult> upsertCourse(JsonElement requert)
        {
            try
            {
                TeacherCourse course = new TeacherCourse();
                if (!requert.TryGetProperty("course", out JsonElement room)) return BadRequest();
                if (!requert.TryGetProperty("option", out JsonElement option)) return BadRequest();
                course = room.ToObject<TeacherCourse>();
                var client = _azureCosmos.GetCosmosClient();
                course.pk = typeof(Course).Name;
                string code = course.code;
                course.code = typeof(Course).Name + "-" + course.code;
                if (option.ToString().Equals("insert"))
                {
                    var response = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync(course.id, new PartitionKey($"Course-{code}"));
                    if (response.Status == 200)
                    {
                        return Ok(new { error = ResponseCode.DATA_EXIST, V = "课程编码已经存在！" });
                    }
                    else
                    {
                        course = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync(course, new PartitionKey($"Course-{code}"));

                    }
                }
                else
                {
                    if (course.classes.Count > 0)
                    {
                        //TODO 教师创建的个人的校本班级待处理冗余数据
                        foreach (ClassSimple classSimple in course.classes)
                        {
                            if (classSimple.scope.Equals("private", StringComparison.OrdinalIgnoreCase))
                            {
                                Class cla = new Class();
                                cla.id = classSimple.id;
                                cla.code = cla.pk + "-" + code;
                                cla.name = classSimple.name;
                                //cla.scope = classSimple.scope;
                                cla.teacher.id = classSimple.teacher.id;
                                cla.teacher.name = classSimple.teacher.name;
                                await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").UpsertItemAsync(cla, new PartitionKey($"Class-{code}"));
                            }
                            else
                            {

                                var response = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(classSimple.id, new PartitionKey($"Class-{classSimple.code}"));
                                if (response.Status == 200)
                                {
                                    using var json = await JsonDocument.ParseAsync(response.ContentStream);
                                    Class cla = json.ToObject<Class>();
                                    Class newCla = new Class();
                                    newCla.id = cla.id;
                                    newCla.code = cla.pk + "-" + code;
                                    newCla.name = classSimple.name;
                                    // newCla.scope = classSimple.scope;
                                    /*foreach (StudentSimple student in cla.students)
                                    {
                                        StudentSimple studentSimple = new StudentSimple();
                                        studentSimple.id = student.id;
                                        studentSimple.name = student.name;
                                        studentSimple.no = student.no;
                                        newCla.students.Add(studentSimple);
                                    }*/
                                    newCla.teacher.id = classSimple.teacher.id;
                                    newCla.teacher.name = classSimple.teacher.name;
                                    await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").UpsertItemAsync(newCla, new PartitionKey($"Class-{code}"));
                                    classSimple.code = code;
                                }
                                else
                                {
                                    Class cla = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Class>(classSimple.id, new PartitionKey($"Class-{classSimple.code}"));
                                    Class newCla = new Class();
                                    newCla.id = cla.id;
                                    newCla.code = cla.pk + "-" + code;
                                    newCla.name = classSimple.name;
                                    //newCla.scope = classSimple.scope;

                                    //newCla.students = cla.students;
                                    newCla.teacher.id = classSimple.teacher.id;
                                    newCla.teacher.name = classSimple.teacher.name;
                                    await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").UpsertItemAsync(newCla, new PartitionKey($"Class-{code}"));
                                }
                            }
                        }
                    }
                    course = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(course, course.id, new PartitionKey($"Course-{code}"));
                }
                return Ok(new { course });
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"CoreAPI2，{_option.Location}，teacherCourse/upsert()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }
        }
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "Teacher")]
        [HttpPost("find-teacher-course")]
        public async Task<IActionResult> FindTeacherCourse(JsonElement requert)
        {
            if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
            //if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
            var client = _azureCosmos.GetCosmosClient();
            List<object> courses = new List<object>();
            var query = $"select c.code,c.id,c.name,c.subjectId,c.periodId,c.scope,c.notice,c.classes from c ";
            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)
                {
                    foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
                    {
                        courses.Add(obj.ToObject<object>());
                    }
                }
            }
            return Ok(new { courses });
        }

        /// <summary>
        /// 查询执教助教的课程班级
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "Teacher")]
        [HttpPost("find-teach-class")]
        public async Task<IActionResult> FindPlanClass(JsonElement request)
        {

            HashSet<string> data = new HashSet<string>();
            if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
            if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
            var client = _azureCosmos.GetCosmosClient();
            //List<object> courses = new List<object>();
            List<string> classIds = new List<string>();
            List<(string id, string scope)> listClassInfo = new List<(string id, string scope)>();
            var query = $"select distinct c.scope,A0.stulist 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()));
                    }
                }
            }
            var querySchool = $"select distinct c.scope,A0.classId id from c join A0 in c.schedule where A0.teacherId = '{id}'";
            await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIterator(queryText: querySchool, 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()));
                    }
                }
            }
            //List<object> coursesBySchool = new List<object>();
            //var queryBySchool = $"select distinct c.id,c.name,c.scope from c  join A0  in c.courses join A1  in A0.teachers where A1.id = '{id}' ";
            await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{code}") }))
            {
                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 foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: querySchool, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{code}") }))
            {
                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()));
                    }
                }
            }
            List<(string id, string name)> listClassList = new List<(string id, string name)>();
            if (classIds.Count > 0)
            {
                //List<(string id, string name)> listClassList = new List<(string id, string name)>();
                await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(
                                    queryText: $"select c.id,c.name from c where c.id in ({string.Join(",", classIds.Select(o => $"'{o}'"))})", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{code}") }))
                {
                    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;
                            listClassList.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString()));
                            //stuIds.Add(account.GetProperty("id").GetString());                           
                        }
                    }
                }

                await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(
                                    queryText: $"select c.id,c.name from c where c.id in ({string.Join(",", classIds.Select(o => $"'{o}'"))})", 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)
                    {
                        var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
                        while (accounts.MoveNext())
                        {
                            JsonElement account = accounts.Current;
                            listClassList.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString()));
                            //stuIds.Add(account.GetProperty("id").GetString());                           
                        }
                    }
                }

                await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIterator(
                                    queryText: $"select c.id,c.name from c where c.id in ({string.Join(",", classIds.Select(o => $"'{o}'"))})", 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)
                    {
                        var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
                        while (accounts.MoveNext())
                        {
                            JsonElement account = accounts.Current;
                            listClassList.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString()));
                            //stuIds.Add(account.GetProperty("id").GetString());                           
                        }
                    }
                }
            }


            var courses = listClassInfo.Select(o =>
                                    new
                                    {
                                        o.id,
                                        o.scope,
                                        name = listClassList.FirstOrDefault(c => c.id == o.id).name,
                                    }
               );
            //courses.Add(grpBalance);
            //courses = courses.Distinct().ToList();
            return Ok(new { courses });
        }


        public class Student
        {
            public string id { get; set; }
            public string name { get; set; }
            public string scope { get; set; }
        }

        public class ListDistinct : IEqualityComparer<Student>
        {
            public bool Equals(Student s1, Student s2)
            {
                return (s1.id == s2.id);
            }

            public int GetHashCode(Student s)
            {
                return s == null ? 0 : s.ToString().GetHashCode();
            }
        }
    }
    public class BatchOption
    {
        public List<string> ids { get; set; }
        public string code { get; set; }
        public string scope { get; set; }
    }
}