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.CollectionHelper;
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;

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;
        public IConfiguration _configuration { get; set; }
        public CourseController(AzureCosmosFactory azureCosmos, DingDing dingDing, IOptionsSnapshot<Option> option , AzureServiceBusFactory serviceBus, IConfiguration configuration)
        {
            _azureCosmos = azureCosmos;
            _dingDing = dingDing;
            _option = option?.Value;
            _serviceBus = serviceBus;
            _configuration = configuration;
        }

        /// <summary>
        /// 更新保存课程
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "Teacher")]
        [HttpPost("upsert")]
        public async Task<IActionResult> upsert(JsonElement requert)
        {
            try
            {
                Course course = new Course();
                if (!requert.TryGetProperty("course", out JsonElement room)) return BadRequest();
                if (!requert.TryGetProperty("option", out JsonElement option)) return BadRequest();
                if (!requert.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
                course = room.ToObject<Course>();
                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"))
                {
                    if (scope.ToString().Equals("school", StringComparison.OrdinalIgnoreCase))
                    {
                        var response = await client.GetContainer("TEAMModelOS", "School").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("TEAMModelOS", "School").CreateItemAsync(course, new PartitionKey($"Course-{code}"));
                            /*foreach (Schedule schedule in course.schedule)
                            {
                                if (!string.IsNullOrEmpty(schedule.stulist))
                                {
                                    if (requert.TryGetProperty("stuList", out JsonElement stuElement))
                                    {
                                        StuList stu = new StuList();
                                        stu = stuElement.ToObject<StuList>();
                                        stu.course.id = course.id;
                                        stu.course.code = course.code;
                                        await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").CreateItemAsync(stu, new PartitionKey($"StuList-{code}"));
                                    }
                                }

                            }*/
                        }
                    }
                    else
                    {
                        var response = await client.GetContainer("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("TEAMModelOS", "Teacher").CreateItemAsync(course, new PartitionKey($"Course-{code}"));
                            /*foreach (Schedule schedule in course.schedule)
                            {
                                if (!string.IsNullOrEmpty(schedule.stulist))
                                {
                                    if (requert.TryGetProperty("stuList", out JsonElement stuElement))
                                    {
                                        StuList stu = new StuList();
                                        stu = stuElement.ToObject<StuList>();
                                        stu.course.id = course.id;
                                        stu.course.code = course.code;
                                        await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher").CreateItemAsync(stu, new PartitionKey($"StuList"));
                                    }
                                }

                            }*/

                        }
                    }

                }
                else
                {
                    if (scope.ToString().Equals("school", StringComparison.OrdinalIgnoreCase))
                    {
                        course = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").ReplaceItemAsync(course, course.id, new PartitionKey($"Course-{code}"));
                        /*foreach (Schedule schedule in course.schedule)
                        {
                            if (!string.IsNullOrEmpty(schedule.stulist))
                            {
                                if (requert.TryGetProperty("stuList", out JsonElement stuElement))
                                {
                                    StuList stu = new StuList();
                                    stu = stuElement.ToObject<StuList>();
                                    stu.course.id = course.id;
                                    stu.course.code = course.code;
                                    await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").ReplaceItemAsync(stu, stu.id, new PartitionKey($"StuList-{code}"));
                                }
                            }

                        }*/
                    }
                    else
                    {
                        course = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync(course, course.id, new PartitionKey($"Course-{code}"));
                        /*foreach (Schedule schedule in course.schedule)
                        {
                            if (!string.IsNullOrEmpty(schedule.stulist))
                            {
                                if (requert.TryGetProperty("stuList", out JsonElement stuElement))
                                {
                                    StuList stu = new StuList();
                                    stu = stuElement.ToObject<StuList>();
                                    stu.course.id = course.id;
                                    stu.course.code = course.code;
                                    await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync(stu, stu.id, new PartitionKey($"StuList"));
                                }
                            }

                        }*/
                    }

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

        }
        //处理通用名单
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "Teacher")]
        [HttpPost("upsert-list")]
        public async Task<IActionResult> upsertList(JsonElement requert)
        {
            try
            {
                
                StuList stuList = new StuList();
                if (!requert.TryGetProperty("stuList", out JsonElement student)) return BadRequest();
                //if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
                if (!requert.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
                stuList = student.ToObject<StuList>();
                var client = _azureCosmos.GetCosmosClient();
                string originCode = stuList.code;
                stuList.code = stuList.pk + "-" + stuList.code;
              
                if (scope.ToString().Equals("school", StringComparison.OrdinalIgnoreCase))
                {
                    StuListChange change = new StuListChange() { 
                        scope=$"{scope}",
                        originCode= originCode
                    };
                    var query = $"SELECT distinct value(c)  FROM c    where  c.id='{stuList.id}'";
                    List<StuList> odlStus = new List<StuList>();
                    await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<StuList>(queryText: query,
                            requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"StuList-{originCode}") }))
                    {
                        odlStus.Add(item);
                    }
                    if (odlStus.Count > 0) 
                    {
                        if (stuList.students.IsNotEmpty())
                        {

                            if (  odlStus[0].students.IsNotEmpty())
                            {
                                StuList oldStu = odlStus[0];
                                foreach (var stu in stuList.students)
                                {
                                    bool flag = false;
                                    //判断新增名单成员不在已经存在的名单
                                    foreach (var old in oldStu.students)
                                    {
                                        if (old.id == stu.id && old.code == stu.code)
                                        {
                                            flag = true;
                                        }
                                    }
                                    if (flag == false)
                                    {
                                        change.stujoin.Add(stu);
                                    }
                                }
                            }
                        }
                        if (stuList.tmids.IsNotEmpty())
                        {
                            if (  odlStus[0].tmids.IsNotEmpty())
                            {
                                StuList oldStu = odlStus[0];
                                foreach (var tmdid in stuList.tmids)
                                {
                                    bool flag = false;
                                    //判断新增名单成员不在已经存在的名单
                                    foreach (var old in oldStu.tmids)
                                    {
                                        if (old == tmdid)
                                        {
                                            flag = true;
                                        }
                                    }
                                    if (flag == false)
                                    {
                                        change.tmdjoin.Add(tmdid);
                                    }
                                }
                            }
                        }
                        var messageChange = new ServiceBusMessage(change.ToJsonString());
                        messageChange.ApplicationProperties.Add("name", "StuList");
                        var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
                        await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
                    }
                    stuList = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").UpsertItemAsync(stuList, new PartitionKey($"StuList-{originCode}"));
                }
                else
                {
                    StuListChange change = new StuListChange()
                    {
                        scope = $"{scope}",
                        originCode = originCode
                    };
                    var query = $"SELECT distinct value(c)  FROM c    where  c.id='{stuList.id}'";
                    List<StuList> odlStus = new List<StuList>();
                    await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<StuList>(queryText: query,
                            requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"StuList") }))
                    {
                        odlStus.Add(item);
                    }
                    if (odlStus.Count>0) {
                        if (stuList.students.IsNotEmpty())
                        {

                            if (  odlStus[0].students.IsNotEmpty())
                            {
                                StuList oldStu = odlStus[0];
                                foreach (var stu in stuList.students)
                                {
                                    bool flag = false;
                                    //判断新增名单成员不在已经存在的名单
                                    foreach (var old in oldStu.students)
                                    {
                                        if (old.id == stu.id && old.code == stu.code)
                                        {
                                            flag = true;
                                        }
                                    }
                                    if (flag == false)
                                    {
                                        change.stujoin.Add(stu);
                                    }
                                }
                            }
                        }
                        if (stuList.tmids.IsNotEmpty())
                        {
                            if (  odlStus[0].tmids.IsNotEmpty())
                            {
                                StuList oldStu = odlStus[0];
                                foreach (var tmdid in stuList.tmids)
                                {
                                    bool flag = false;
                                    //判断新增名单成员不在已经存在的名单
                                    foreach (var old in oldStu.tmids)
                                    {
                                        if (old == tmdid)
                                        {
                                            flag = true;
                                        }
                                    }
                                    if (flag == false)
                                    {
                                        change.tmdjoin.Add(tmdid);
                                    }
                                }
                            }
                        }
                        var messageChange = new ServiceBusMessage(change.ToJsonString());
                        messageChange.ApplicationProperties.Add("name", "StuList");
                        var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
                        await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
                    }
                    stuList.code = "StuList";
                    stuList = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher").UpsertItemAsync(stuList, new PartitionKey($"StuList"));
                }
                return Ok(new { stuList });
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，course/upsert-list()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }
        }

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

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

        }

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

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

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

                return Ok(new { id });
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，course/get-summary-list()\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("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("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("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});
                //return Ok(new { courses, courses.Count, token = continuationToken });
            }
            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-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("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("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.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("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.notice = schedule.notice;
                        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"))
                {
                    /*List<CourseManagement> managements = new List<CourseManagement>();
                    await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: $"select value(c) from c join A0 in c.courses where A0.course.id = '{id}'", 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())
                            {
                                managements.Add(obj.ToObject<CourseManagement>());
                            }
                        }
                    }

                    for (int i = 0; i < managements.Count; i++)
                    {
                        bool flag = false;
                        for (int j = 0; j < managements[i].courses.Count; j++)
                        {
                            if (!managements[i].courses[j].course.id.Equals(id.ToString()))
                            {
                                flag = true;
                                managements[i].courses.Remove(managements[i].courses[j]);
                                break;
                            }
                        }
                        if (flag)
                        {
                            await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync(managements[i], managements[i].id, new PartitionKey($"{managements[i].code}"));
                        }
                    }*/
                    await client.GetContainer("TEAMModelOS", "School").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"Course-{code}"));
                }
                else
                {
                    await client.GetContainer("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();
                /*                StringBuilder sql = new StringBuilder();
                                sql.Append("select value(c) from c ");*/
                /*Dictionary<string, object> dict = new Dictionary<string, object>();
                //处理id
                if (request.ids.IsNotEmpty())
                {
                    dict.Add("id", request.ids.ToArray());
                }*/
                string school_code = request.code;
                /*AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql);
                List<Course> courses = new List<Course>();
                await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{school_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<Course>());
                        }
                    }
                }*/
                if (request.scope.Equals("school", StringComparison.OrdinalIgnoreCase))
                {
                    List<Response> res = await client.GetContainer("TEAMModelOS", "School").DeleteItemsStreamAsync(request.ids, $"Course-{school_code}");
                }
                else
                {
                    List<Response> res = await client.GetContainer("TEAMModelOS", "Teacher").DeleteItemsStreamAsync(request.ids, $"Course-{school_code}");
                }

                // TODO JJ调整批量删除
                //await _azureCosmos.DeleteAll(courses);
                //List<IdPk> idPk = await _azureCosmos.DeleteAll<Course>(request);
                //await client.GetContainer("TEAMModelOS", "School").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"Class-{code}"));
                //[Jeff] CourseManagement表廢除 刪除預定：以下CourseManagement更新程序
                /*StringBuilder sqlM = new StringBuilder();
                sqlM.Append("select value(c) from c ");
                Dictionary<string, object> dict_management = new Dictionary<string, object>();
                //处理ID
                if (request.ids.IsNotEmpty())
                {
                    dict_management.Add("courses[*].course.id", request.ids.ToArray());
                }
                List<CourseManagement> managements = new List<CourseManagement>();
                AzureCosmosQuery cosmosDbQuery_1 = SQLHelper.GetSQL(dict_management, sqlM);
                await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery_1.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"CourseManagement-{school_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())
                        {
                            managements.Add(obj.ToObject<CourseManagement>());
                        }
                    }
                }

                for (int i = 0; i < managements.Count; i++)
                {
                    bool flag = false;
                    for (int k = 0; k < request.ids.Count; k++)
                    {
                        for (int j = 0; j < managements[i].courses.Count; j++)
                        {
                            if (managements[i].courses[j].course.id.Equals(request.ids[k].ToString()))
                            {
                                managements[i].courses.Remove(managements[i].courses[j]);
                                flag = true;
                            }
                        }
                    }
                    if (flag)
                    {
                        await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync(managements[i], managements[i].id, new PartitionKey($"{managements[i].code}"));
                    }
                }*/
                ////[Jeff] CourseManagement表廢除 刪除預定：以下CourseManagement更新程序
                //IdPk idPk=  await _azureCosmos.DeleteAsync<Course>(request);
                return Ok(new { ids = request.ids });
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"CN，{_option.Location}，course/delete()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }



            //ResponseBuilder builder = ResponseBuilder.custom();
            //return builder.Data(idPk).build();
            //return Ok(new { idPk });
        }

        /// <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("TEAMModelOS", "School").ReadItemStreamAsync(requert.id, new PartitionKey($"CourseManagement-{code}"));
                if (response.Status == 200)
                {
                    /*                    using var json = await JsonDocument.ParseAsync(response.ContentStream);
                                        CourseManagement courseManagement = json.ToObject<CourseManagement>();
                                        courseManagement.courses = requert.courses;*/
                    //return Ok(new { error = ResponseCode.DATA_EXIST, V = "课程编码已经存在！" });
                    course = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").ReplaceItemAsync(requert, requert.id, new PartitionKey($"CourseManagement-{code}"));

                }
                else
                {
                    course = await _azureCosmos.GetCosmosClient().GetContainer("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("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>());
                    }
                }
            }
            /* List<object> courses = new List<object>();
             var response = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(id.ToString(), new PartitionKey($"CourseManagement-{code}"));
             if (response.Status == 200)
             {
                 using var json = await JsonDocument.ParseAsync(response.ContentStream);
                 foreach (var obj in json.RootElement.GetProperty("courseSimples").EnumerateArray())
                 {
                     courses.Add(obj.ToObject<object>());
                 }
                 *//*if (json.RootElement.TryGetProperty("courseSimples", out JsonElement value))
                 {
                     courses = (List<object>)value.ToObject<object>();
                 }*//*
             }
             else {
                 return Ok(new { error = ResponseCode.UNDEFINED, V = "数据未找到！" });
             }*/
            return Ok(new { courses });
            /* var query = $"select c.code,c.id,c.name,c.period,c.subject,c.teachers from c";
             await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{school_code.GetString()}") }))
             {
                 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, courses.Count });

            /* 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();*/
        }
        [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("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("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("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("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.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.notice = schedule.notice;
                    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>();
            /*var sresponse = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(id.ToString(), new PartitionKey($"{code}"));
            if (sresponse.Status == 200)
            {
                using var json = await JsonDocument.ParseAsync(sresponse.ContentStream);
                CourseManagement course = json.ToObject<CourseManagement>();
                for (int i =0; i < course.courses.Count;i++) {
                    if (course.courses[i].course.id.Equals(courseId.ToString())) {
                        course.courses[i].course.notice = notice.ToString();
                        await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync(course, course.id, new PartitionKey($"{course.code}"));
                        break;
                    }                  
                }                

            }*/
            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("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("TEAMModelOS", "School").ReplaceItemAsync(courseManagements[i], courseManagements[i].id, new PartitionKey($"{courseManagements[i].code}"));
                        break;
                    }
                }
            }
            return Ok(new { id });
        }
        internal class valitime
        {
            public string code { get; set; }
            public string courseId { get; set; }
            public string classroomCode { get; set; }
            public string time { get; set; }
            public string day { get; set; }
            public string notice { get; set; }
            public CourseTime courseTime { get; set; }
            /// <summary>
            /// 学生分组
            /// </summary>
            public List<GroupStudent> groups { get; set; }
            /// <summary>
            /// 助教
            /// </summary>
            public List<Assistant> assistant { get; set; }
            /// <summary>
            /// 学期代码
            /// </summary>
            public string semesterCode { get; set; }
        }

        // TODO 前端没在用

        /// <summary>
        /// 教师更新副属信息,助教，分组等。
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        //[ProducesDefaultResponseType]
        ////[AuthToken(Roles = "Teacher")]
        //[HttpPost("upsert-plan")]
        //public async Task<BaseResponse> UpsertPlan(CoursePlan request) {
        //    ResponseBuilder builder = ResponseBuilder.custom();
        //    CoursePlan datas = await _azureCosmos.FindByIdPk<CoursePlan>(request.id,request.code);
        //    if (datas!=null) {
        //        request.semesterCode = datas.semesterCode;
        //        request.classes.ForEach(x => {
        //            datas.classes.ForEach(m => { 
        //            if (m.classroomCode == x.classroomCode) {
        //                x.courseTimes = m.courseTimes;
        //            } }); 
        //        });
        //        await _azureCosmos.Update(request);
        //    }
        //    return builder.Data(request).build();
        //}

        [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("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("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("TEAMModelOS", "Teacher").UpsertItemAsync(cla, new PartitionKey($"Class-{code}"));
                            }
                            else
                            {

                                var response = await client.GetContainer("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("TEAMModelOS", "Teacher").UpsertItemAsync(newCla, new PartitionKey($"Class-{code}"));
                                    classSimple.code = code;
                                }
                                else
                                {
                                    Class cla = await client.GetContainer("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("TEAMModelOS", "Teacher").UpsertItemAsync(newCla, new PartitionKey($"Class-{code}"));
                                }
                            }
                        }
                    }
                    course = await _azureCosmos.GetCosmosClient().GetContainer("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("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("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("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("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("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("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("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("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});          
        }

        // TODO 前端没在用

        /// <summary>
        /// 删除课程安排
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        //[ProducesDefaultResponseType]
        ////[AuthToken(Roles = "Teacher")]
        //[HttpPost("delete-time")]
        //public async Task<BaseResponse> DeletePlan(JsonElement request)
        //{
        //    ResponseBuilder builder = ResponseBuilder.custom();
        //    if (request.TryGetProperty("id",out JsonElement id) && request.TryGetProperty("code",out JsonElement code) && request.TryGetProperty("classroomCode",out JsonElement classroomCode) 
        //        && request.TryGetProperty("time",out JsonElement time) && request.TryGetProperty("day",out JsonElement day)) {
        //        CoursePlan coursePlan = await _azureCosmos.FindByIdPk<CoursePlan>(id.ToString(), code.ToString());
        //        List<CourseTime> courseTimes = new List<CourseTime>();
        //        coursePlan.classes.ForEach(x=> {
        //            if (x.classroomCode == classroomCode.ToString()) {
        //                x.courseTimes.ForEach(y => {
        //                    if (y.time == time.ToString() && y.day == day.ToString())
        //                    {
        //                        courseTimes.Add(y);
        //                    }
        //                });
        //            }
        //        });
        //       coursePlan.classes.ForEach(x => { if (x.classroomCode == classroomCode.ToString()) {
        //               courseTimes.ForEach(y => { x.courseTimes.Remove(y); });
        //           } });
        //       await _azureCosmos.Update(coursePlan);
        //        return builder.Data(coursePlan).build();
        //    }
        //    return builder.Data(null).build();
        //}

        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; }

    }
}