using Azure.Cosmos;
using Azure.Storage.Sas;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using TEAMModelOS.Filter;
using TEAMModelOS.Models;
using TEAMModelOS.SDK;
using TEAMModelOS.SDK.DI;
using TEAMModelOS.SDK.DI.AzureCosmos.Inner;
using TEAMModelOS.SDK.Extension;
using TEAMModelOS.SDK.Models;
using TEAMModelOS.SDK.Models.Cosmos.Common;
using TEAMModelOS.SDK.Models.Service;

namespace TEAMModelOS.Controllers
{
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    [Route("school/area")]
    [ApiController]
    public class AreaController : ControllerBase
    {
        private readonly AzureCosmosFactory _azureCosmos;
        private readonly SnowflakeId _snowflakeId;
        private readonly AzureServiceBusFactory _serviceBus;
        private readonly DingDing _dingDing;
        private readonly Option _option;
        private readonly AzureStorageFactory _azureStorage;
        private readonly AzureRedisFactory _azureRedis;
        public IConfiguration _configuration { get; set; }
        public AreaController(AzureCosmosFactory azureCosmos, AzureServiceBusFactory serviceBus, SnowflakeId snowflakeId, DingDing dingDing,
            IOptionsSnapshot<Option> option, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis, IConfiguration configuration)
        {
            _azureCosmos = azureCosmos;
            _serviceBus = serviceBus;
            _snowflakeId = snowflakeId;
            _dingDing = dingDing;
            _option = option?.Value;
            _azureStorage = azureStorage;
            _azureRedis = azureRedis;
            _configuration = configuration;
        }

        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "Teacher")]
        [HttpPost("find-group")]
        public async Task<IActionResult> Find(JsonElement requert)
        {
            try
            {
                //区级Id
                if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
                var client = _azureCosmos.GetCosmosClient();
                //获取区级以下所有学校编码和基础信息
                List<string> baseIds = new();
                List<(string id, string name, string picture)> scInfos = new List<(string id, string name, string picture)>();
                await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: $"select c.id,c.name,c.picture from c where c.areaId = '{id}'", 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;
                            baseIds.Add(account.GetProperty("id").GetString());
                            scInfos.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString(), account.GetProperty("picture").GetString()));
                        }
                    }
                }
                List<(string id, List<string> gId, List<string> name)> groups = new List<(string id, List<string> gId, List<string> name)>();
                foreach (string sId in baseIds)
                {
                    List<(string id, string name)> group = new();
                    await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: $"SELECT c.id, c.name FROM c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"TchList-{sId}") }))
                    {
                        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;
                                group.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString()));
                                //group.Add();
                            }
                        }

                    }
                    group = group.Where(g => !string.IsNullOrEmpty(g.id)).ToList();
                    groups.Add((sId, group.Select(s => s.id).ToList(), group.Select(s => s.name).ToList()));
                }
                //var (blob_uri, blob_sas) = _azureStorage.GetBlobContainerSAS("hbcn", BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List);
                var gr = groups.Select(o => new
                {
                    o.id,
                    o.gId,
                    uri = _azureStorage.GetBlobContainerSAS(o.id, BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List).uri,
                    sas = _azureStorage.GetBlobContainerSAS(o.id, BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List).sas,
                    sname = scInfos.FirstOrDefault(c => c.id == o.id).name,
                    o.name
                });
                return Ok(new { gr });
            }
            catch (Exception e)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，school/area/find-group()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }

        }

        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "Teacher")]
        [HttpPost("find")]
        public async Task<IActionResult> FindGroup(JsonElement requert)
        {
            try
            {
                //区级Id
                if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
                var client = _azureCosmos.GetCosmosClient();
                //获取区级以下所有学校编码和基础信息
                List<string> baseIds = new();
                List<(string id, string name, string picture)> scInfos = new List<(string id, string name, string picture)>();
                await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: $"select c.id,c.name,c.picture from c where c.areaId = '{id}'", 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;
                            baseIds.Add(account.GetProperty("id").GetString());
                            scInfos.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString(), account.GetProperty("picture").GetString()));
                        }
                    }
                }
                //获取所有学校人数
                List<(string id, int count)> scCount = new List<(string id, int count)>();
                foreach (string sId in baseIds)
                {
                    List<string> tIds = new();
                    await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryText: $"select c.id from c join A0 in c.schools where A0.schoolId = '{sId}' ", 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;
                                tIds.Add(account.GetProperty("id").GetString());
                            }
                        }
                    }
                    scCount.Add((sId, tIds.Count));
                }
                var info = scInfos.Select(o =>
                                   new
                                   {
                                       o.id,
                                       o.name,
                                       o.picture,
                                       areaId = id,
                                       count = scCount.FirstOrDefault(c => c.id == o.id).count,
                                   }
              );
                return Ok(new { info });
            }
            catch (Exception e)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，school/area/find()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }

        }
        /// <summary>
        /// 保存研修信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "teacher,admin")]
        [HttpPost("save-study")]
        public async Task<IActionResult> SaveStudy(JsonElement request)
        {
            try
            {
                if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
                if (!request.TryGetProperty("para", out JsonElement para)) return BadRequest();
                if (!request.TryGetProperty("study", out JsonElement stu)) return BadRequest();
                List<parameter> parameters = para.ToObject<List<parameter>>();
                var client = _azureCosmos.GetCosmosClient();
                long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                List<Study> studies = new();
                Study areaStudy = stu.ToObject<Study>();
                areaStudy.owner = "area";
                areaStudy.ttl = -1;
                areaStudy.scope = "school";
                areaStudy.code = "Study-" + id.GetString();
                areaStudy.createTime = now;
                if (string.IsNullOrEmpty(areaStudy.id))
                {
                    areaStudy.id = Guid.NewGuid().ToString();
                }
                List<string> allName = new();
                foreach (parameter pa in parameters)
                {
                    Study study = stu.ToObject<Study>();
                    //string code = pa.sId;
                    study.areaId = id.GetString();
                    study.school = pa.sId;
                    study.owner = "area";
                    study.ttl = -1;
                    study.code = "Study-" + pa.sId;
                    study.createTime = now;
                    study.tchLists = pa.gId;
                    study.pId = areaStudy.id;
                    study.scope = "school";
                    study.targetType = "research";
                    if (pa.gName.Count == 0)
                    {
                        string sName = pa.sName + "-" + "所有老师(未分组)";
                        allName.Add(sName);
                        string json = "所有老师(未分组)";
                        study.targets.Add(json.ToJsonString().ToObject<JsonElement>());
                        //study.targets.Add("所有老师(未分组)");

                    }
                    else
                    {
                        //study.targets = pa.gName;
                        var tn = pa.gName.ToJsonString().ToObject<List<JsonElement>>();
                        study.targets = tn;
                        foreach (string name in pa.gName)
                        {
                            //处理区级target
                            string sName = pa.sName + "-" + name;
                            allName.Add(sName);

                        }

                    }
                    foreach (string setting in study.settings)
                    {
                        if (setting.Equals("exam"))
                        {
                            if (!request.TryGetProperty("exam", out JsonElement exam)) return BadRequest();
                            ExamLite trExam = exam.ToObject<ExamLite>();
                            trExam.owner = "area";
                            trExam.school = pa.sId;
                            trExam.areaId = id.GetString();
                            trExam.tchLists = pa.gId;
                            trExam.scope = "school";
                            trExam.targetType = "research";
                            trExam.blob = $"/{trExam.areaId}/exam/{study.pId}/index.json";
                            //处理发布对象
                            await getMoreExam(pa, trExam);
                            //保存更多得评测信息
                            string eId = await ExamService.saveMoreAsync(client, _dingDing, trExam);
                            if (string.IsNullOrEmpty(eId))
                            {
                                return Ok(new { code = (int)HttpStatusCode.BadRequest, msg = "评测信息异常" });
                            }
                            else
                            {
                                study.examId = eId;
                            }
                        }
                        if (setting.Equals("survey"))
                        {
                            if (!request.TryGetProperty("survey", out JsonElement survey)) return BadRequest();
                            Survey trSurvey = survey.ToObject<Survey>();
                            trSurvey.owner = "area";
                            trSurvey.school = pa.sId;
                            trSurvey.areaId = id.GetString();
                            trSurvey.tchLists = pa.gId;
                            trSurvey.scope = "school";
                            trSurvey.targetType = "research";
                            trSurvey.blob = $"/{trSurvey.areaId}/survey/{study.pId}/index.json";
                            await getMoreSurvey(pa, trSurvey);
                            string surveyId = await SurveyService.saveMoreAsync(client, _dingDing, trSurvey);
                            if (string.IsNullOrEmpty(surveyId))
                            {
                                return Ok(new { code = (int)HttpStatusCode.BadRequest, msg = "问卷信息异常" });
                            }
                            else
                            {
                                study.surveyId = surveyId;
                            }
                        }
                        if (setting.Equals("hw"))
                        {
                            if (!request.TryGetProperty("work", out JsonElement work)) return BadRequest();
                            TeacherWork teacherWork = work.ToObject<TeacherWork>();
                            teacherWork.owner = "area";
                            teacherWork.school = pa.sId;
                            teacherWork.areaId = id.GetString();
                            teacherWork.tchLists = pa.gId;
                            teacherWork.scope = "school";
                            teacherWork.targetType = "research";
                            //teacherWork.blob = $"/{teacherWork.areaId}/survey/{study.pId}/index.json";
                            await getMoreWork(pa, teacherWork);
                            string workId = await TeacherWorkService.saveMoreAsync(client, _dingDing, teacherWork);
                            if (string.IsNullOrEmpty(workId))
                            {
                                return Ok(new { code = (int)HttpStatusCode.BadRequest, msg = "作业活动异常" });
                            }
                            else
                            {
                                study.workId = workId;
                            }
                        }
                    }
                    if (string.IsNullOrEmpty(study.id))
                    {
                        study.id = Guid.NewGuid().ToString();
                        await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(study, new PartitionKey($"{study.code}"));
                    }
                    else
                    {
                        await client.GetContainer("TEAMModelOS", "Common").UpsertItemAsync(study, new PartitionKey($"{study.code}"));
                    }
                    studies.Add(study);
                }
                //areaStudy.targets = allName;
                var atn = allName.ToJsonString().ToObject<List<JsonElement>>();
                areaStudy.targets = atn;
                await client.GetContainer("TEAMModelOS", "Common").UpsertItemAsync(areaStudy, new PartitionKey($"{areaStudy.code}"));
                var ids = studies.Select(s => new { s.id, s.school, s.examId, s.surveyId });
                return Ok(new { id, ids, code = (int)HttpStatusCode.OK, acId = areaStudy.id });
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，area/save-study()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }

        }


        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "Teacher")]
        [HttpPost("find-all-study")]
        public async Task<IActionResult> FindAllStudy(JsonElement requert)
        {
            try
            {
                //区级Id
                if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
                var client = _azureCosmos.GetCosmosClient();
                // List<string> baseIds = await getId(client, id.GetString());
                List<object> studies = new();

                var query = $"select c.id,c.img,c.name,c.type,c.startTime,c.endTime,c.presenter,c.topic,c.address,c.owner,c.school from c ";


                await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Study-{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())
                        {
                            studies.Add(obj.ToObject<object>());
                        }
                    }
                }

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

        }

        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "Teacher")]
        [HttpPost("find-all-study-teachers")]
        public async Task<IActionResult> FindAllStudyTeacher(JsonElement requert)
        {
            try
            {
                //区级活动Id
                if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
                if (!requert.TryGetProperty("areaId", out JsonElement areaId)) return BadRequest();
                var client = _azureCosmos.GetCosmosClient();
                List<(string id, string name)> baseIds = await getId(client, areaId.GetString());
                List<Study> studies = new();
                List<(string id, string name)> ps = await getInfo(client, areaId.GetString());
                //List<string> aName = new();
                var query = $"select value(c) from c where c.pId = '{id}'";
                foreach ((string code,string name) in baseIds)
                {
                    await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<Study>(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Study-{code}") }))
                    {
                        studies.Add(item);
                    }
                }

                List<(List<TmdInfo> teac, Survey sur)> trSurveys = new List<(List<TmdInfo> teac, Survey sur)>();
                List<(List<TmdInfo> teac, ExamLite examLite)> trExams = new List<(List<TmdInfo> teac, ExamLite examLite)>();
                List<(List<TmdInfo> teac, Study stu)> moreInfo = new List<(List<TmdInfo> teac, Study stu)>();
                List<(List<TmdInfo> teac, TeacherWork tw)> works = new List<(List<TmdInfo> teac, TeacherWork tw)>();
                foreach (Study study in studies)
                {
                    (List<TmdInfo> tchList, _) = await TriggerStuActivity.GetTchList(client, _dingDing, study.tchLists, study.school);
                    if (!string.IsNullOrEmpty(study.surveyId))
                    {

                        var sresponse = await client.GetContainer("TEAMModelOS", "Common").ReadItemStreamAsync(study.surveyId, new PartitionKey($"Survey-{study.school}"));
                        if (sresponse.Status == 200)
                        {
                            using var json = await JsonDocument.ParseAsync(sresponse.ContentStream);
                            Survey surs = json.ToObject<Survey>();
                            trSurveys.Add((tchList, surs));
                        }
                    }
                    if (!string.IsNullOrEmpty(study.examId))
                    {
                        var sresponse = await client.GetContainer("TEAMModelOS", "Common").ReadItemStreamAsync(study.examId, new PartitionKey($"ExamLite-{study.school}"));
                        if (sresponse.Status == 200)
                        {
                            using var json = await JsonDocument.ParseAsync(sresponse.ContentStream);
                            ExamLite lite = json.ToObject<ExamLite>();
                            trExams.Add((tchList, lite));
                        }
                    }
                    if (!string.IsNullOrEmpty(study.workId))
                    {
                        var sresponse = await client.GetContainer("TEAMModelOS", "Common").ReadItemStreamAsync(study.workId, new PartitionKey($"TeacherWork-{study.school}"));
                        if (sresponse.Status == 200)
                        {
                            using var json = await JsonDocument.ParseAsync(sresponse.ContentStream);
                            TeacherWork work = json.ToObject<TeacherWork>();
                            works.Add((tchList, work));
                        }
                    }
                    moreInfo.Add((tchList, study));
                };
                var survey = trSurveys.Select(s => new
                {
                    count = s.teac.Count,
                    ansCount = s.sur.answers.Count,
                });
                var twork = works.Select(s => new
                {
                    count = s.teac.Count,
                    ansCount = s.tw.teachers.Where(h => !string.IsNullOrEmpty(h.hw)).ToList().Count,
                });
                var exam = trExams.Select(s => new
                {
                    count = s.teac.Count,
                    ansCount = s.examLite.teachers.Where(h => h.answer.Count > 0).ToList().Count,
                });
                var info = moreInfo.Select(s => new
                {
                    s.stu.id,
                    name = ps.FirstOrDefault(c => c.id == s.stu.id).name,
                    count = s.teac.Count,
                    //hwCount = s.teachers.Where(h => h.hwTime > 0).ToList().Count,
                    signCount = s.stu.teachers.Where(h => h.signTime > 0).ToList().Count,
                    lateCount = s.stu.teachers.Where(h => !string.IsNullOrEmpty(h.sign) && h.sign.Equals("1")).ToList().Count,
                    acount = s.stu.teachers.Where(h => h.aTime > 0).ToList().Count
                });
                return Ok(new { survey, work = twork,exam, info, studies = moreInfo.Select(m => new { m.teac, m.stu }) });
            }
            catch (Exception e)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，area/find-all-study-teachers()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }

        }

        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "Teacher")]
        [HttpPost("find-all-vote")]
        public async Task<IActionResult> FindAllVote(JsonElement requert)
        {
            try
            {
                //区级Id
                if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
                var client = _azureCosmos.GetCosmosClient();
                //List<string> baseIds = await getId(client, id.GetString());
                List<object> votes = new();
                //List<string> aName = new();
                var query = $"select c.id,c.name,c.startTime,c.progress,c.owner,c.school from c ";
                await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Vote-{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())
                        {
                            votes.Add(obj.ToObject<object>());
                        }
                    }
                }


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

        }
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "Teacher")]
        [HttpPost("find-vote-id")]
        public async Task<IActionResult> FindAllVoteTeacher(JsonElement requert)
        {
            try
            {
                //区级活动Id
                if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
                if (!requert.TryGetProperty("areaId", out JsonElement areaId)) return BadRequest();
                var client = _azureCosmos.GetCosmosClient();
                List<(string id, string name)> baseIds = await getId(client, areaId.GetString());
                //List<object> votes = new();
                List<(string id, string name)> ps = await getInfo(client, areaId.GetString());
                //List<string> aName = new();
                List<Vote> votes = new List<Vote>();
                Vote vote = null;
                List<(string code,string name, string url, int count)> recordUrl = new List<(string code, string name, string url, int count)>();
                var response = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.GetString(), new PartitionKey($"Vote-{areaId}"));
                if (response.Status == 200)
                {
                    using var json = await JsonDocument.ParseAsync(response.ContentStream);
                    vote = json.ToObject<Vote>();
                    var query = $"select  c.tchLists,c.recordUrl from c where c.pId = '{id}'";
                    foreach ((string code, string name) in baseIds)
                    {
                        await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Vote-{code}") }))
                        {
                            using var sjson = await JsonDocument.ParseAsync(item.ContentStream);
                            if (sjson.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
                            {
                                var accounts = sjson.RootElement.GetProperty("Documents").EnumerateArray();
                                while (accounts.MoveNext())
                                {
                                    JsonElement account = accounts.Current;
                                    List<string> tcs = account.GetProperty("tchLists").ToObject<List<string>>();
                                    (List<TmdInfo> tchList, _) = await TriggerStuActivity.GetTchList(client, _dingDing, tcs, code);
                                    recordUrl.Add((code,name, account.GetProperty("recordUrl").GetString(), tchList.Count));
                                }
                            }
                        }
                    }
                }

                //var info = ps.Select(p => new { p.id, p.name });
                return Ok(new { vote, code = recordUrl.Select(r => new { r.code,r.name, r.url, r.count }) });
            }
            catch (Exception e)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，area/find-all-vote-teachers()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }

        }

        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "Teacher")]
        [HttpPost("find-all-survey")]
        public async Task<IActionResult> FindAllSurvey(JsonElement requert)
        {
            try
            {
                //区级Id
                if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
                var client = _azureCosmos.GetCosmosClient();
                //List<string> baseIds = await getId(client, id.GetString());
                List<object> surveys = new();
                // List<string> aName = new();
                var query = $"select c.id,c.name,c.startTime,c.progress,c.sType,c.owner,c.school from c ";

                await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Survey-{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())
                        {
                            surveys.Add(obj.ToObject<object>());
                        }
                    }
                }


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

        }
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "Teacher")]
        [HttpPost("find-survey-id")]
        public async Task<IActionResult> FindAllSurveyTeacher(JsonElement requert)
        {
            try
            {
                if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
                if (!requert.TryGetProperty("areaId", out JsonElement areaId)) return BadRequest();
                var client = _azureCosmos.GetCosmosClient();
                List<(string id, string name)> baseIds = await getId(client, areaId.GetString());
                List<object> surveys = new();
                Survey survey = null;
                List<(string code, string name,string url, int count)> recordUrl = new List<(string code, string name,string url, int count)>();
                var response = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(id.GetString(), new PartitionKey($"Survey-{areaId}"));
                if (response.Status == 200)
                {
                    using var json = await JsonDocument.ParseAsync(response.ContentStream);
                    survey = json.ToObject<Survey>();
                    var query = $"select  c.tchLists,c.recordUrl from c where c.pId = '{id}'";
                    foreach ((string code, string name) in baseIds)
                    {
                        await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Survey-{code}") }))
                        {
                            using var sjson = await JsonDocument.ParseAsync(item.ContentStream);
                            if (sjson.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
                            {
                                var accounts = sjson.RootElement.GetProperty("Documents").EnumerateArray();
                                while (accounts.MoveNext())
                                {
                                    JsonElement account = accounts.Current;
                                    List<string> tcs = account.GetProperty("tchLists").ToObject<List<string>>();
                                    (List<TmdInfo> tchList, _) = await TriggerStuActivity.GetTchList(client, _dingDing, tcs, code);
                                    recordUrl.Add((code, name,account.GetProperty("recordUrl").GetString(), tchList.Count));
                                }
                            }
                        }
                    }
                }

                //var info = ps.Select(p => new { p.id, p.name });
                return Ok(new { survey, code = recordUrl.Select(r => new { r.code,r.name, r.url, r.count }) });
            }
            catch (Exception e)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，area/find-all-survey-teachers()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }

        }

        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "Teacher")]
        [HttpPost("find-all-Exam")]
        public async Task<IActionResult> FindAllExam(JsonElement requert)
        {
            try
            {
                //区级Id
                if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
                var client = _azureCosmos.GetCosmosClient();
                //List<string> baseIds = await getId(client, id.GetString());
                List<object> exams = new();
                // List<string> aName = new();
                var query = $"select c.id,c.name,c.createTime,c.sType,c.owner,c.school from c ";


                await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamLite-{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())
                        {
                            exams.Add(obj.ToObject<object>());
                        }
                    }
                }


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

        }
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "Teacher")]
        [HttpPost("find-all-exam-teachers")]
        public async Task<IActionResult> FindAllExamTeacher(JsonElement requert)
        {
            try
            {
                //区级活动Id
                if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
                if (!requert.TryGetProperty("areaId", out JsonElement areaId)) return BadRequest();
                var client = _azureCosmos.GetCosmosClient();
                List<(string id, string name)> baseIds = await getId(client, areaId.GetString());
                List<object> exams = new();
                List<(string id, string name)> ps = await getInfo(client, areaId.GetString());
                //List<string> aName = new();
                var query = $"select c.school,c.teachers from c where c.acId = '{id}'";
                foreach ((string code, string name) in baseIds)
                {
                    await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"TrExam-{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())
                            {
                                exams.Add(obj.ToObject<object>());
                            }
                        }
                    }
                }
                var info = ps.Select(p => new { p.id, p.name });
                return Ok(new { info, exams });
            }
            catch (Exception e)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，area/find-all-exam-teachers()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }

        }


        /// <summary>
        /// 保存投票信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "teacher,admin")]
        [HttpPost("save-vote")]
        public async Task<IActionResult> SaveVote(JsonElement request)
        {
            try
            {
                if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
                if (!request.TryGetProperty("para", out JsonElement para)) return BadRequest();
                if (!request.TryGetProperty("vote", out JsonElement vote)) return BadRequest();
                List<parameter> parameters = para.ToObject<List<parameter>>();
                List<Vote> votes = new();
                long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                var client = _azureCosmos.GetCosmosClient();
                Vote areaVote = vote.ToObject<Vote>();
                areaVote.owner = "area";
                areaVote.ttl = -1;
                areaVote.code = "Vote-" + id.GetString();
                areaVote.createTime = now;
                if (areaVote.startTime <= 0)
                {
                    areaVote.startTime = now;
                }
                if (areaVote.startTime > now)
                {
                    areaVote.progress = "pending";
                }
                else
                {
                    areaVote.progress = "going";
                }
                if (string.IsNullOrEmpty(areaVote.id))
                {
                    areaVote.id = Guid.NewGuid().ToString();
                }
                List<string> allName = new();
                foreach (parameter pa in parameters)
                {
                    Vote trVote = vote.ToObject<Vote>();
                    string code = pa.sId;
                    trVote.school = code;
                    trVote.ttl = -1;
                    trVote.code = "Vote-" + code;
                    trVote.createTime = now;
                    trVote.areaId = id.GetString();
                    trVote.owner = "area";
                    trVote.pId = areaVote.id;
                    trVote.tchLists = pa.gId;
                    trVote.targetType = "research";
                    if (trVote.startTime <= 0)
                    {
                        trVote.startTime = now;
                    }
                    if (trVote.startTime > now)
                    {
                        trVote.progress = "pending";
                    }
                    else
                    {
                        trVote.progress = "going";
                    }

                    if (pa.gName.Count == 0)
                    {
                        string sName = pa.sName + "-" + "所有老师(未分组)";
                        allName.Add(sName);
                        string json = "所有老师(未分组)";
                        //var json = new { name = "所有老师(未分组)" };
                        trVote.targets.Add(json.ToJsonString().ToObject<JsonElement>());
                    }
                    else
                    {
                        var tn = pa.gName.ToJsonString().ToObject<List<JsonElement>>();
                        trVote.targets = tn;
                        foreach (string name in pa.gName)
                        {
                            //处理区级target
                            string sName = pa.sName + "-" + name;
                            allName.Add(sName);
                        }

                    }
                    if (string.IsNullOrEmpty(trVote.id))
                    {
                        trVote.id = Guid.NewGuid().ToString();
                        string url = $"/vote/{trVote.id}/record.json";
                        trVote.recordUrl = url;
                        await _azureStorage.UploadFileByContainer(code, new { options = new List<string>(), records = new List<VoteRecord>() }.ToJsonString(), "vote", $"{trVote.id}/record.json");
                        await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(trVote, new PartitionKey($"{trVote.code}"));
                    }
                    else
                    {
                        await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(trVote, trVote.id, new PartitionKey($"{trVote.code}"));
                    }
                    votes.Add(trVote);
                }
                var atn = allName.ToJsonString().ToObject<List<JsonElement>>();
                /*List<JsonElement> atn = new List<JsonElement>();
                foreach (string agn in allName)
                {
                    atn.Add(agn.ToObject<JsonElement>());
                }*/
                areaVote.targets = atn;
                await client.GetContainer("TEAMModelOS", "Common").UpsertItemAsync(areaVote, new PartitionKey($"{areaVote.code}"));
                var ids = votes.Select(s => new { s.id, s.school });
                return Ok(new { id, ids, code = (int)HttpStatusCode.OK });
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，area/save-vote()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }

        }


        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "Teacher")]
        [HttpPost("delete")]
        public async Task<IActionResult> Delete(JsonElement request)
        {
            try
            {
                //区级活动Id
                if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
                //区级id
                if (!request.TryGetProperty("areaId", out JsonElement code)) return BadRequest();
                if (!request.TryGetProperty("pk", out JsonElement pk)) return BadRequest();
                var client = _azureCosmos.GetCosmosClient();
                var response = await client.GetContainer("TEAMModelOS", "Common").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"{pk}-{code}"));
                List<(string id, string name)> bascId = await getId(client, code.GetString());
                List<(string id, string name)> ids = new();
                foreach ((string sId, string name) in bascId)
                {
                    await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: $"select c.id,c.code from c where c.pId = '{id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{pk}-{sId}") }))
                    {

                        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;
                                ids.Add((account.GetProperty("id").GetString(), account.GetProperty("code").GetString()));
                            }
                        }

                    }
                }
                if (ids.Count > 0)
                {
                    foreach ((string s, string c) in ids)
                    {
                        if (c.Contains("Study"))
                        {
                            var sresponse = await client.GetContainer("TEAMModelOS", "Common").ReadItemStreamAsync(s.ToString(), new PartitionKey($"{c}"));
                            if (sresponse.Status == 200)
                            {
                                using var json = await JsonDocument.ParseAsync(sresponse.ContentStream);
                                Study study = json.ToObject<Study>();
                                if (!string.IsNullOrEmpty(study.examId))
                                {
                                    await client.GetContainer("TEAMModelOS", "Common").DeleteItemStreamAsync(study.examId, new PartitionKey($"ExamLite-{study.school}"));
                                }
                                if (!string.IsNullOrEmpty(study.surveyId))
                                {
                                    await client.GetContainer("TEAMModelOS", "Common").DeleteItemStreamAsync(study.surveyId, new PartitionKey($"Survey-{study.school}"));
                                }
                                if (!string.IsNullOrEmpty(study.workId))
                                {
                                    await client.GetContainer("TEAMModelOS", "Common").DeleteItemStreamAsync(study.workId, new PartitionKey($"TeacherWork-{study.school}"));
                                }
                            }
                        }
                        await client.GetContainer("TEAMModelOS", "Common").DeleteItemStreamAsync(s.ToString(), new PartitionKey($"{c}"));
                    }
                }
                return Ok(new { id, code = response.Status });
            }
            catch (Exception e)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，area/delete()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }
        }

        /// <summary>
        /// 保存问卷信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "teacher,admin")]
        [HttpPost("save-survey")]
        public async Task<IActionResult> SaveSurvey(JsonElement request)
        {
            try
            {
                if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
                if (!request.TryGetProperty("para", out JsonElement para)) return BadRequest();
                if (!request.TryGetProperty("survey", out JsonElement survey)) return BadRequest();
                List<parameter> parameters = para.ToObject<List<parameter>>();
                List<Survey> surveys = new();
                long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                var client = _azureCosmos.GetCosmosClient();
                Survey areaSurvey = survey.ToObject<Survey>();
                areaSurvey.owner = "area";
                areaSurvey.ttl = -1;
                areaSurvey.code = "Survey-" + id.GetString();
                areaSurvey.createTime = now;
                if (areaSurvey.startTime <= 0)
                {
                    areaSurvey.startTime = now;
                }
                if (areaSurvey.startTime > now)
                {
                    areaSurvey.progress = "pending";
                }
                else
                {
                    areaSurvey.progress = "going";
                }
                if (string.IsNullOrEmpty(areaSurvey.id))
                {
                    areaSurvey.id = Guid.NewGuid().ToString();
                }
                List<string> allName = new();
                foreach (parameter pa in parameters)
                {
                    Survey trSurvey = survey.ToObject<Survey>();
                    string code = pa.sId;
                    trSurvey.ttl = -1;
                    trSurvey.school = code;
                    trSurvey.code = "Survey-" + code;
                    trSurvey.createTime = now;
                    trSurvey.areaId = id.GetString();
                    trSurvey.owner = "area";
                    trSurvey.tchLists = pa.gId;
                    trSurvey.pId = areaSurvey.id;
                    trSurvey.targetType = "research";
                    if (trSurvey.startTime <= 0)
                    {
                        trSurvey.startTime = now;
                    }
                    if (trSurvey.startTime > now)
                    {
                        trSurvey.progress = "pending";
                    }
                    else
                    {
                        trSurvey.progress = "going";
                    }

                    if (pa.gName.Count == 0)
                    {
                        string sName = pa.sName + "-" + "所有老师(未分组)";
                        allName.Add(sName);
                        string json = "所有老师(未分组)";
                        trSurvey.targets.Add(json.ToJsonString().ToObject<JsonElement>());
                    }
                    else
                    {
                        var tn = pa.gName.ToJsonString().ToObject<List<JsonElement>>();
                        trSurvey.targets = tn;
                        foreach (string name in pa.gName)
                        {
                            //处理区级target
                            string sName = pa.sName + "-" + name;
                            allName.Add(sName);
                        }

                    }
                    await getMoreSurvey(pa, trSurvey);

                        trSurvey.id = Guid.NewGuid().ToString();
                        trSurvey.recordUrl = $"/survey/{trSurvey.id}/record.json";
                        var cods = new { records = new List<string>(), userids = new List<string>(), question = new List<QuestionRecord>() };
                        await _azureStorage.UploadFileByContainer(code, cods.ToJsonString(), "survey", $"{trSurvey.id}/record.json");
                        // trSurvey.blob = SurveyService.getBlob(trSurvey.id);
                        await client.GetContainer("TEAMModelOS", "Common").UpsertItemAsync(trSurvey, new PartitionKey($"{trSurvey.code}"));
                    
                    surveys.Add(trSurvey);
                }
                //areaSurvey.targets = allName;
                var atn = allName.ToJsonString().ToObject<List<JsonElement>>();
                areaSurvey.targets = atn;
                await client.GetContainer("TEAMModelOS", "Common").UpsertItemAsync(areaSurvey, new PartitionKey($"{areaSurvey.code}"));
                var ids = surveys.Select(s => new { s.id, s.school });
                return Ok(new { id, ids, code = (int)HttpStatusCode.OK });
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，area/save-survey()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }

        }

        /// <summary>
		/// 保存评测信息
		/// </summary>
		/// <param name="request"></param>
		/// <returns></returns>
		[ProducesDefaultResponseType]
        //[AuthToken(Roles = "teacher,admin")]
        [HttpPost("save-exam")]
        public async Task<IActionResult> SaveExam(JsonElement request)
        {
            try
            {
                if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
                if (!request.TryGetProperty("para", out JsonElement para)) return BadRequest();
                if (!request.TryGetProperty("exam", out JsonElement exam)) return BadRequest();
                List<parameter> parameters = para.ToObject<List<parameter>>();
                List<ExamLite> exams = new();
                long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                var client = _azureCosmos.GetCosmosClient();
                ExamLite areaExam = exam.ToObject<ExamLite>();
                areaExam.owner = "area";
                areaExam.ttl = -1;
                areaExam.code = "TrExam-" + id.GetString();
                areaExam.createTime = now;
                if (string.IsNullOrEmpty(areaExam.id))
                {
                    areaExam.id = Guid.NewGuid().ToString();
                }
                List<string> allName = new();

                foreach (parameter pa in parameters)
                {
                    ExamLite trExam = exam.ToObject<ExamLite>();
                    string code = pa.sId;
                    trExam.ttl = -1;
                    trExam.school = code;
                    trExam.code = "TrExam-" + code;
                    trExam.createTime = now;
                    trExam.areaId = id.GetString();
                    trExam.owner = "area";
                    trExam.pId = areaExam.id;
                    trExam.targetType = "research";
                    if (pa.gName.Count == 0)
                    {
                        string sName = pa.sName + "-" + "所有老师(未分组)";
                        allName.Add(sName);
                    }
                    else
                    {
                        foreach (string name in pa.gName)
                        {
                            //处理区级target
                            string sName = pa.sName + "-" + name;
                            allName.Add(sName);
                        }

                    }
                    await getMoreExam(pa, trExam);
                    if (string.IsNullOrEmpty(trExam.id))
                    {
                        trExam.id = Guid.NewGuid().ToString();
                        //  trExam.blob = ExamService.getBlob(trExam.id);
                        await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(trExam, new PartitionKey($"{trExam.code}"));
                    }
                    else
                    {
                        //trExam.blob = ExamService.getBlob(trExam.id);
                        await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(trExam, trExam.id, new PartitionKey($"{trExam.code}"));
                    }
                    exams.Add(trExam);
                }
                //areaExam.targets = allName;
                await client.GetContainer("TEAMModelOS", "Common").UpsertItemAsync(areaExam, new PartitionKey($"{areaExam.code}"));
                var ids = exams.Select(s => new { s.id, s.school });
                return Ok(new { id, ids, code = (int)HttpStatusCode.OK });
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，area/save-exam()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }

        }

        private async Task<List<(string id, string name)>> getId(CosmosClient client, string id)
        {
            //获取区级以下所有学校编码和基础信息
            List<(string id,string name)> baseIds = new();
            await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: $"select c.id,c.name from c where c.areaId = '{id}'", 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;
                        baseIds.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString()));

                    }
                }
            }
            return baseIds;
        }
        private async Task<List<teacherInfo>> GetTeacherAll(string name, string code)
        {
            var client = _azureCosmos.GetCosmosClient();
            string query = string.Empty;
            List<teacherInfo> teachers = new List<teacherInfo>();
            if (string.IsNullOrEmpty(name))
            {
                query = $"SELECT c.id, c.name, c.groupName FROM c ";

            }
            else
            {
                query = $"SELECT c.id, c.name, c.groupName FROM c where c.groupName = '{name}'";
            }
            await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<teacherInfo>(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{code}") }))
            {
                teachers.Add(item);
            }


            return teachers;
        }
        private Task<ExamLite> getMoreExam(parameter pa, ExamLite trExam)
        {
            if (pa.gName.Count == 0)
            {

                string json = "所有老师(未分组)";
                trExam.targets.Add(json.ToJsonString().ToObject<JsonElement>());

            }
            else
            {
                var tn = pa.gName.ToJsonString().ToObject<List<JsonElement>>();
                trExam.targets = tn;

            }
            return Task.FromResult(trExam);
        }
        private Task<Survey> getMoreSurvey(parameter pa, Survey trSurvey)
        {
            if (pa.gName.Count == 0)
            {

                //trSurvey.targets.Add("所有老师(未分组)");
                string json = "所有老师(未分组)";
                trSurvey.targets.Add(json.ToJsonString().ToObject<JsonElement>());
            }
            else
            {
                var tn = pa.gName.ToJsonString().ToObject<List<JsonElement>>();
                trSurvey.targets = tn;

            }
            return Task.FromResult(trSurvey);
        }
        private Task<TeacherWork> getMoreWork(parameter pa, TeacherWork work)
        {
            if (pa.gName.Count == 0)
            {

                //trSurvey.targets.Add("所有老师(未分组)");
                string json = "所有老师(未分组)";
                work.targets.Add(json.ToJsonString().ToObject<JsonElement>());
            }
            else
            {
                var tn = pa.gName.ToJsonString().ToObject<List<JsonElement>>();
                work.targets = tn;

            }
            return Task.FromResult(work);
        }

        private async Task<List<(string id, string name)>> getInfo(CosmosClient client, string id)
        {
            List<(string id, string name)> scInfos = 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.areaId = '{id}'", 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;
                        scInfos.Add((account.GetProperty("id").GetString(), account.GetProperty("name").GetString()));
                    }
                }
            }
            return scInfos;
        }

        public class parameter
        {
            public string sId { get; set; }
            public string sName { get; set; }
            public List<string> gName { get; set; }
            public List<string> gId { get; set; }
        }


        public class teacherInfo
        {
            public string id { get; set; }
            public string name { get; set; }
            public string groupName { get; set; }
        }

    }
}
