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;

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;

        public CourseController(AzureCosmosFactory azureCosmos, DingDing dingDing, IOptionsSnapshot<Option> option)
        {
            _azureCosmos = azureCosmos;
            _dingDing = dingDing;
            _option = option?.Value;
        }

        /// <summary>
        /// 更新保存课程
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "Teacher")]
        [HttpPost("upsert")]
        public async Task<IActionResult> upsert(JsonElement requert)
        {
            try {
                /*//ResponseBuilder builder = ResponseBuilder.custom();
                if (!string.IsNullOrEmpty(requert.id))
                {
                    List<int> count = await _azureCosmos.FindCountByDict<Course>(new Dictionary<string, object> { { "courseCode", requert.courseCode }, { "code", requert.code } });
                    if (count.IsNotEmpty() && count[0] > 0)
                    {
                       // return builder.Error(ResponseCode.DATA_EXIST, "课程编码已经存在！").build();
                    }
                    requert.id = requert.code.Replace("#", "") + "-" + requert.courseCode;
                }
                Course response = await _azureCosmos.SaveOrUpdate<Course>(requert);
                return Ok(new { requert });*/
                Course course = new Course();
                if (!requert.TryGetProperty("course", out JsonElement room)) return BadRequest();
                if (!requert.TryGetProperty("option", out JsonElement option)) 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"))
                {
                    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}"));

                    }
                }
                else
                {
                    course = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").UpsertItemAsync(course, new PartitionKey($"Course-{code}"));
                }
                return Ok(new { course });
            }
            catch (Exception ex) {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，course/upsert()\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)
        {
            //ResponseBuilder builder = ResponseBuilder.custom();

            //if (!requert.TryGetProperty("id_token", out JsonElement id_token)) return BadRequest();
            if (!requert.TryGetProperty("school_code", out JsonElement school_code)) return BadRequest();
            //var jwt = new JwtSecurityToken(id_token.GetString());
            //if (!jwt.Payload.Iss.Equals("account.teammodel", StringComparison.Ordinal)) return BadRequest();
            //var id = jwt.Payload.Sub;
            //var id = "TBLCOURSE700";
            try {
                var client = _azureCosmos.GetCosmosClient();
                List<object> courses = new List<object>();
                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 });
            } catch (Exception ex) {
                await _dingDing.SendBotMsg($"CoreAPI2，{_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("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}"));
                        }
                    }
                    } else {
                    await client.GetContainer("TEAMModelOS", "Teacher").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"Course-{code}"));
                }                                             
                //IdPk idPk=  await _azureCosmos.DeleteAsync<Course>(request);
                return Ok(new { id });
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"CoreAPI2，{_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>());
                        }
                    }
                }*/
                List<Response> res =  await client.GetContainer("TEAMModelOS", "School").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($"CoreAPI2，{_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("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)
        {
            ResponseBuilder builder = ResponseBuilder.custom();
            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<Student> courses = new List<Student>();
            var query = $"select A0.id,A0.name,A0.scope from c join A0 in c.classes";
            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<Student>());
                    }
                }
            }
            //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: queryBySchool, 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<Student>());
                    }
                }
            }
            courses = courses.Distinct(new ListDistinct()).ToList();
            //courses = courses.Distinct().ToList();
            return Ok(new { courses ,courses.Count});
            //request.TryGetProperty("assistant[*]", out JsonElement element);
            /*List<dynamic> room = new List<dynamic>();
            var prop = new List<string> { "classes" };
            if (request.TryGetProperty("code", out JsonElement code))
            {
                var teachers = await _azureCosmos.FindByDict<CoursePlan>(new Dictionary<string, object> { { "code", code.ToString() } }, prop);
                if (teachers.IsNotEmpty()) {
                    teachers.Select(x => x.classes).ToList().ForEach(x => { x.ForEach(y => { data.Add(y.classroomCode); }); });

                }
            }
            if (request.TryGetProperty("assistant[*]", out JsonElement element)) { 
                var assistant = await _azureCosmos.FindByDict<CoursePlan>(new Dictionary<string, object> { { "assistant[*]", element.ToString() } }, prop);
                if (assistant.IsNotEmpty()) {
                    assistant.Select(x => x.classes).ToList().ForEach(x => { x.ForEach(y => { data.Add(y.classroomCode); }); });
                }
            }
            if (data.Count > 0) { 
                var classRoom=  await _azureCosmos.FindByDict<Classroom>(new Dictionary<string, object> { { "id",data.ToArray() } } );
                if (classRoom.IsNotEmpty()) {
                    classRoom.ForEach(x => {
                        room.Add(x);
                    });
                }
            }*/
            //return builder.Data(room).Extend(new Dictionary<string, object> { { "count", room.Count } }).build();
        }

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

    }
}