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

namespace TEAMModelOS.Controllers.Research
{
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    //[Authorize(Roles = "IES5")]
    [Route("research/ability")]
    [ApiController]
    public class AbilityStatisticsController : ControllerBase
    {
        private readonly AzureCosmosFactory _azureCosmos;
        private readonly SnowflakeId _snowflakeId;
        private readonly DingDing _dingDing;
        private readonly Option _option;
        public AbilityStatisticsController(AzureCosmosFactory azureCosmos, SnowflakeId snowflakeId, DingDing dingDing, IOptionsSnapshot<Option> option)
        {
            _azureCosmos = azureCosmos;
            _snowflakeId = snowflakeId;
            _dingDing = dingDing;
            _option = option?.Value; ;
        }
        /// <summary>
        /// 对某个订阅的能力点进行操作
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [HttpPost("statistics-self")]
        [AuthToken(Roles = "teacher,student,admin,area")]
        public async Task<IActionResult> StatisticsSelf(JsonElement request)
        {
            if (!HttpContext.Items.TryGetValue("Standard", out object standard)) return BadRequest();
            var client = _azureCosmos.GetCosmosClient();
            if (!request.TryGetProperty("tmdid", out JsonElement _tmdid)) return BadRequest();
            if (!request.TryGetProperty("school", out JsonElement _school)) return BadRequest();
            int alltime = 0;
            int subCount = 0;
            int allAbilityCount = 0;
            //已通过自测的能力点数量
            int hasAbilityExercise = 0;
            int onlineTime = 0;
            int offlinelTime = 0;
            int schoolScoreTime = 0;
            int classVideoTime = 0;
            int offlineSchoolJoinCount = 0;
            int offlineSchoolDoneCount = 0;
            int offlineAreaJoinCount = 0;
            int offlineAreaDoneCount = 0;
            int uploadTotalCount = 0;
            int uploadDoneCount = 0;

            int surveyJoinCount = 0;
            int voteJoinCount = 0;
            int examJoinCount = 0;
            int surveyDoneCount = 0;
            int voteDoneCount = 0;
            int examDoneCount = 0;

            int surveyAreaJoinCount = 0;
            int voteAreaJoinCount = 0;
            int examAreaJoinCount = 0;
            int surveyAreaDoneCount = 0;
            int voteAreaDoneCount = 0;
            int examAreaDoneCount = 0;


            List<string> abilityIds = new List<string>();
            await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher")
                .GetItemQueryIterator<AbilitySub>(queryText: $"select value(c) from c  ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"AbilitySub-{_school}-{_tmdid}") }))
            {
                if (item.uploads.IsNotEmpty())
                {
                    uploadDoneCount += item.uploads.Count;
                }
                subCount += 1;
                if (item.exerciseScore > 0)
                {
                    hasAbilityExercise += 1;
                }
                allAbilityCount += item.abilityCount;
                onlineTime += item.hour;
                if (item.otherScore.IsNotEmpty())
                {
                    var schoolScore = item.otherScore.Where(x => x.roleType.Equals("school")).FirstOrDefault();
                    if (schoolScore != null && schoolScore.score > 0)
                    {
                        schoolScoreTime += 1;
                    }
                }
                abilityIds.Add(item.id);
            }
            if (abilityIds.IsNotEmpty())
            {
                string queryText = $"SELECT c.stds FROM c WHERE c.id IN ({string.Join(",", abilityIds.Select(o => $"'{o}'"))})";
                await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School")
                .GetItemQueryIterator<Ability>(queryText: queryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Ability-{standard}") }))
                {
                    item.stds.ForEach(x => {
                        if (x.task.IsNotEmpty())
                        {
                            uploadTotalCount += 1;
                        }
                    });
                }
            }
            //owner:  school  area
            //线下 学校研修活动


            await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Common")
            .GetItemQueryIterator<Study>(queryText: $"select c.owner, c.teachers,c.targets  from c  join A0 in c.teachers  where   A0.id='{_tmdid}' ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Study-{_school}") }))
            {

                if (!string.IsNullOrEmpty(item.owner))
                {
                    if (item.owner.Equals("school"))
                    {
                        offlineSchoolJoinCount += 1;
                        var tech = item.teachers.Find(x => x.id.Equals($"{_tmdid}"));
                        if (tech != null && tech.signTime > 0)
                        {
                            offlinelTime += item.hour;
                            offlineSchoolDoneCount += 1;
                        }
                    }
                    else if (item.owner.Equals("area"))
                    {
                        offlineAreaJoinCount += 1;
                        var tech = item.teachers.Find(x => x.id.Equals($"{_tmdid}"));
                        if (tech != null && tech.signTime > 0)
                        {
                            offlinelTime += item.hour;
                            offlineAreaDoneCount += 1;
                        }
                    }
                }
            }



            //问卷调查


            //await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Common")
            // .GetItemQueryIterator<TrSurvey>(queryText: $"select c.teachers,c.targets from c  join A0 in c.teachers   where c.pk='TrSurvey' and c.sType = 'normal'  and A0.id='{_tmdid}' ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"TrSurvey-{_school}") }))
            //{
            //    if (!string.IsNullOrEmpty(item.owner))
            //    {
            //        if (item.owner.Equals("school"))
            //        {
            //            surveyJoinCount += 1;
            //            var record = item.teachers.Find(x => x.id.Equals($"{_tmdid}"));
            //            if (record != null && record.answer.IsNotEmpty())
            //            {
            //                surveyDoneCount += 1;
            //            }
            //        }
            //        else if (item.owner.Equals("area"))
            //        {
            //            surveyAreaJoinCount += 1;
            //            var record = item.teachers.Find(x => x.id.Equals($"{_tmdid}"));
            //            if (record != null && record.answer.IsNotEmpty())
            //            {
            //                surveyAreaDoneCount += 1;
            //            }
            //        }
            //    }
            //}


            //评量检测



            //await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Common")
            // .GetItemQueryIterator<TrExam>(queryText: $"select c.teachers,c.targets from c  join A0 in c.teachers   where c.pk='TrExam' and c.sType = 'normal'  and A0.id='{_tmdid}' ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"TrSurvey-{_school}") }))
            //{
            //    if (!string.IsNullOrEmpty(item.owner))
            //    {
            //        if (item.owner.Equals("school"))
            //        {
            //            examJoinCount += 1;
            //            var record = item.teachers.Find(x => x.id.Equals($"{_tmdid}"));
            //            if (record != null && record.answer.IsNotEmpty())
            //            {
            //                examDoneCount += 1;
            //            }
            //        }
            //        else if (item.owner.Equals("area"))
            //        {
            //            examAreaJoinCount += 1;
            //            var record = item.teachers.Find(x => x.id.Equals($"{_tmdid}"));
            //            if (record != null && record.answer.IsNotEmpty())
            //            {
            //                examAreaDoneCount += 1;
            //            }
            //        }
            //    }

            //}



            //投票活动


            //await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Common")
            // .GetItemQueryIterator<TrVote>(queryText: $"select c.teachers,c.targets from c   join A0 in c.teachers   where c.pk='TrVote'   and A0.id='{_tmdid}' ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"TrVote-{_school}") }))
            //{
            //    if (!string.IsNullOrEmpty(item.owner))
            //    {
            //        if (item.owner.Equals("school"))
            //        {
            //            voteJoinCount += 1;
            //            var record = item.teachers.Find(x => x.id.Equals($"{_tmdid}"));
            //            if (record != null && record.answer.IsNotEmpty())
            //            {
            //                voteDoneCount += 1;
            //            }
            //        }
            //        else if (item.owner.Equals("area"))
            //        {
            //            voteAreaJoinCount += 1;
            //            var record = item.teachers.Find(x => x.id.Equals($"{_tmdid}"));
            //            if (record != null && record.answer.IsNotEmpty())
            //            {
            //                voteAreaDoneCount += 1;
            //            }
            //        }
            //    }

            //}
            string code = $"ClassVideo-{_school}";
            try
            {
                ClassVideo classVideo = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemAsync<ClassVideo>($"{_tmdid}", new PartitionKey(code));
                classVideo.files.ForEach(x => {
                    if (x.score > 0)
                    {
                        classVideoTime += 1;
                    }
                });
            }
            catch (Exception ex)
            {
            }
            //处理单项 超标准 学时 
            alltime += onlineTime >= 20 ? 20 : onlineTime;
            alltime += offlinelTime >= 10 ? 10 : offlinelTime;
            alltime += schoolScoreTime >= 15 ? 15 : schoolScoreTime;
            alltime += classVideoTime >= 5 ? 5 : classVideoTime;
            return Ok(new
            {
                alltime,
                subCount,
                allAbilityCount,
                onlineTime,
                schoolScoreTime,
                classVideoTime,
                hasAbilityExercise,
                offlinelTime,
                offlineAreaDoneCount,
                offlineAreaJoinCount,
                offlineSchoolDoneCount,
                offlineSchoolJoinCount,
                uploadDoneCount,
                uploadTotalCount,
                surveyDoneCount,
                surveyJoinCount,
                voteDoneCount,
                voteJoinCount,
                examJoinCount,
                examDoneCount,
                surveyAreaDoneCount,
                surveyAreaJoinCount,
                voteAreaDoneCount,
                voteAreaJoinCount,
                examAreaJoinCount,
                examAreaDoneCount,
            });
        }
        /// <summary>
        /// 对某个订阅的能力点进行操作
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [HttpPost("sub-opt")]
        [AuthToken(Roles = "teacher,student,admin,area")]
        public async Task<IActionResult> SubOpt(JsonElement request)
        {
            try
            {
                if (!HttpContext.Items.TryGetValue("Standard", out object standard)) return BadRequest();
                var client = _azureCosmos.GetCosmosClient();
                if (!request.TryGetProperty("tmdid", out JsonElement _tmdid)) return BadRequest();
                if (!request.TryGetProperty("school", out JsonElement _school)) return BadRequest();
                if (!request.TryGetProperty("opt", out JsonElement _opt)) return BadRequest();
                if (!request.TryGetProperty("abilityId", out JsonElement _abilityId)) return BadRequest();
                string code = $"AbilitySub-{_school}-{_tmdid}";
                int status = 0;
                AbilitySub abilitySub = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemAsync<AbilitySub>($"{_abilityId}", new PartitionKey(code));
                Ability abilityA = await client.GetContainer("TEAMModelOS", "School").ReadItemAsync<Ability>($"{_abilityId}", new PartitionKey($"Ability-{standard}"));
                switch ($"{_opt}")
                {
                    case "ReadSelfOnlineRcd":
                        //获取线上学习记录
                        return Ok(new { abilitySub.taskRcds });
                    case "SetOnlineDone":
                        //完成线上学习
                        abilitySub.done = true;
                        //abilitySub.abilityCount = abilityA.abilityCount;
                        //abilitySub.hour = abilityA.hour;
                        await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<AbilitySub>(abilitySub, $"{_abilityId}", new PartitionKey(code));
                        return Ok(new { abilitySub });
                    case "ExerciseScore":
                        //保存自测结果
                        if (!request.TryGetProperty("exercise", out JsonElement _exercise)) return BadRequest();
                        if (!string.IsNullOrEmpty($"{_exercise}"))
                        {
                            //exercise -1未自测  0不合格 1 合格
                            abilitySub.exerciseScore = int.Parse($"{_exercise}");
                            await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<AbilitySub>(abilitySub, $"{_abilityId}", new PartitionKey(code));
                            status = 1;
                            return Ok(new { status });
                        }
                        else
                        {
                            return BadRequest("参数exercise没有值");
                        }
                    case "ExerciseRcd":
                        //获取自测结果
                        return Ok(new { exercise = abilitySub.exerciseScore });
                    case "Upload":
                        long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                        //上传作品和自评
                        if (!request.TryGetProperty("uploads", out JsonElement _uploads)) return BadRequest();
                        if (!request.TryGetProperty("self", out JsonElement _self)) return BadRequest();
                        List<SubUpload> uploads = _uploads.ToObject<List<SubUpload>>();
                        if (!string.IsNullOrEmpty($"{_self}"))
                        {
                            //_self  0 不及格,1及格,2优秀
                            abilitySub.self = int.Parse($"{_self}");
                        }
                        else
                        {
                            return BadRequest();
                        }
                        if (uploads.IsNotEmpty())
                        {
                            abilitySub.abilityCount = abilityA.abilityCount;
                            abilitySub.hour = abilityA.hour;
                            uploads.ForEach(u => {
                                var up = abilitySub.uploads.Find(x => x.stdid.Equals(u.stdid));
                                if (up != null)
                                {
                                    up.urls = u.urls;
                                    up.taskid = u.taskid;
                                    up.titleIds = u.titleIds;
                                    up.time = now;
                                }
                                else
                                {
                                    u.time = now;
                                    abilitySub.uploads.Add(u);
                                }
                            });
                            abilitySub.selfTime = now;
                            await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<AbilitySub>(abilitySub, $"{_abilityId}", new PartitionKey(code));
                            status = 1;
                        }
                        else
                        {
                            return BadRequest();
                        }
                        return Ok(new { status });
                    case "YouRateSomone":
                        //你对别人的某个能力点的学习进行评价,不能评价自己的,
                        if (!request.TryGetProperty("otherScore", out JsonElement _other)) return BadRequest();
                        RoleScore other = _other.ToObject<RoleScore>();
                        string replyId = null;
                        if (other != null)
                        {
                            if (abilitySub.creatorId.Equals(other.tmdid))
                            {
                                return BadRequest("不能评价自己的");
                            }
                            long nowTime = DateTimeOffset.Now.ToUnixTimeMilliseconds();

                            if (!string.IsNullOrEmpty(other.reply))
                            {
                                replyId = Guid.NewGuid().ToString();
                                DebateReply debateReply = new DebateReply
                                {
                                    id = replyId,
                                    pid = abilitySub.comid,
                                    tmdid = other.tmdid,
                                    tmdname = other.tmdname,
                                    comment = other.reply,
                                    atTmdid = $"{_tmdid}",
                                    atTmdname = other.atTmdname,
                                    time = nowTime
                                };
                                try
                                {
                                    Debate debate = await client.GetContainer("TEAMModelOS", "School").ReadItemAsync<Debate>(abilitySub.comid, new PartitionKey($"Debate-{_school}"));
                                    debate.replies.Add(debateReply);
                                    await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<Debate>(debate, abilitySub.comid, new PartitionKey($"Debate-{_school}"));
                                }
                                catch (CosmosException ex)
                                {
                                    if (ex.Status == 404)
                                    {
                                        Debate debate = new Debate
                                        {
                                            comid = $"{abilityA.comid}",
                                            code = $"Debate-{_school}",
                                            id = $"{abilitySub.comid}",
                                            tmdid = abilitySub.creatorId,
                                            tmdname = other.atTmdname,
                                            title = $"{other.atTmdname}-{abilityA.name}",
                                            time = nowTime,
                                            comment = "",
                                            school = $"{_school}",
                                            replies = new List<DebateReply>() { debateReply },
                                            source = "uploadscore",
                                            openType = 0,
                                            ttl = -1,
                                            pk = "Debate"
                                        };
                                        await client.GetContainer("TEAMModelOS", "School").CreateItemAsync<Debate>(debate, new PartitionKey($"Debate-{_school}"));
                                    }
                                }
                            }
                            if (other.roleType.Equals("school"))
                            {
                                //学校的身份不管是谁,只能以学校的身份进行一次评论
                                abilitySub.allDone = true;
                                var otherScore = abilitySub.otherScore.Find(x => x.roleType.Equals(other.roleType));
                                if (otherScore != null)
                                {
                                    otherScore.tmdname = other.tmdname;
                                    otherScore.score = other.score;
                                    if (!string.IsNullOrEmpty(replyId))
                                    {
                                        if (otherScore.replyIds.IsNotEmpty())
                                        {
                                            otherScore.replyIds.Add(replyId);
                                        }
                                        else
                                        {
                                            otherScore.replyIds = new List<string>() { replyId };
                                        }
                                    }
                                    otherScore.scoreUploads = other.scoreUploads;
                                    otherScore.time = nowTime;
                                }
                                else
                                {
                                    abilitySub.otherScore.Add(new OtherScore
                                    {
                                        roleType = other.roleType,
                                        tmdid = other.tmdid,
                                        tmdname = other.tmdname,
                                        score = other.score,
                                        replyIds = new List<string>() { replyId },
                                        scoreUploads = other.scoreUploads,
                                        time = nowTime
                                    });
                                }
                            }
                            else
                            {
                                //其他身份的同一个人可以以不同身份进行点评
                                var otherScore = abilitySub.otherScore.Find(x => x.tmdid.Equals(other.tmdid) && x.roleType.Equals(other.roleType));
                                if (otherScore != null)
                                {
                                    otherScore.tmdname = other.tmdname;
                                    otherScore.score = other.score;
                                    if (!string.IsNullOrEmpty(replyId))
                                    {
                                        if (otherScore.replyIds.IsNotEmpty())
                                        {
                                            otherScore.replyIds.Add(replyId);
                                        }
                                        else
                                        {
                                            otherScore.replyIds = new List<string>() { replyId };
                                        }
                                    }
                                    otherScore.scoreUploads = other.scoreUploads;
                                    otherScore.time = nowTime;
                                }
                                else
                                {
                                    abilitySub.otherScore.Add(new OtherScore
                                    {
                                        roleType = other.roleType,
                                        tmdid = other.tmdid,
                                        tmdname = other.tmdname,
                                        score = other.score,
                                        replyIds = new List<string>() { replyId },
                                        scoreUploads = other.scoreUploads,
                                        time = nowTime
                                    });
                                }
                            }
                            await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<AbilitySub>(abilitySub, $"{_abilityId}", new PartitionKey(code));
                            status = 1;
                        }
                        return Ok(new { status, abilitySub });
                    case "YouGetSomoneRate":
                        //你获取你对别人的某个能力点的学习评价
                        OtherScore score = null;
                        if (!request.TryGetProperty("yourTmdid", out JsonElement _yourTmdid)) return BadRequest();
                        if (string.IsNullOrEmpty($"{_yourTmdid}"))
                        {
                            score = abilitySub.otherScore.Find(x => x.tmdid.Equals($"{_yourTmdid}"));
                            if (score != null)
                            {
                                status = 1;
                                return Ok(new { score, status });
                            }
                            else
                            {
                                return Ok(new { status, score });
                            }
                        }
                        else
                        {
                            return Ok(new { status, score });
                        }
                    case "SaveLearnOnlineRcd":
                        //保存线上学习记录
                        if (!request.TryGetProperty("taskRcds", out JsonElement _taskRcds)) return BadRequest();
                        AbilityTaskRcd taskRcds = _taskRcds.ToObject<AbilityTaskRcd>();
                        if (taskRcds != null)
                        {
                            bool isnew = true;
                            abilitySub.taskRcds.ForEach(x => {
                                if (x.id.Equals(taskRcds.id))
                                {
                                    //重新上传或者覆盖之前
                                    x = taskRcds;
                                    isnew = false;
                                }
                            });
                            if (isnew)
                            {
                                abilitySub.taskRcds.Add(taskRcds);
                            }
                            await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<AbilitySub>(abilitySub, $"{_abilityId}", new PartitionKey(code));
                            status = 1;
                        }
                        return Ok(new { status, abilitySub.taskRcds });
                    default:
                        return Ok(new { status = -1 });
                }
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS,{_option.Location},AbilityController/SubOpt()\n{ex.Message}{ex.StackTrace}{request.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }
        }
        public class RoleScore
        {
            /// <summary>
            /// 角色类型  成员 member   学校 school  专家 expert
            /// </summary>
            public string roleType { get; set; }
            /// <summary>
            /// 评论人的id
            /// </summary>
            public string tmdid { get; set; }
            /// <summary>
            /// 评论人
            /// </summary>
            public string tmdname { get; set; }
            /// <summary>
            /// 被评论人的醍摩豆名称
            /// </summary>
            public string atTmdname { get; set; }
            //总评   -1未评,0未通过,1合格,2优秀
            public int score { get; set; } = -1;
            /// <summary>
            /// 某人对你这个能力点的学习评价的的评语记录的Id集合。
            /// </summary>
            public string reply { get; set; }
            /// <summary>
            /// 根据评判标准进行打分
            /// </summary>
            public List<ScoreUpload> scoreUploads { get; set; } = new List<ScoreUpload>();
        }
        /// <summary>
        /// 获取订阅统计
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [HttpPost("get-subs-statistics")]
        [AuthToken(Roles = "teacher,student,admin,area")]
        public async Task<IActionResult> GetSubsStatistics(JsonElement request)
        {
            try
            {
                if (!HttpContext.Items.TryGetValue("Standard", out object standard)) return BadRequest();
                var client = _azureCosmos.GetCosmosClient();
                if (!request.TryGetProperty("school", out JsonElement _school)) return BadRequest();
                HashSet<string> dimensions = new HashSet<string>();
                HashSet<string> groups = new HashSet<string>();
                HashSet<string> groupNames = new HashSet<string>();
                Dictionary<string, string> groupDict = new Dictionary<string, string>();
                List<Ability> abilities = new List<Ability>();
                await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School")
                           .GetItemQueryIterator<Ability>(queryText: $"select c.id, c.name,c.no,c.dimension, c.env  from c  ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Ability-{standard}") }))
                {
                    dimensions.Add(item.dimension);
                    abilities.Add(item);
                }
                List<string> abilitieIds = abilities.Select(x => x.id).ToList();
               // List<ScTeacher> teachers = new List<ScTeacher>();
                List<ClassVideo> classVideos = new List<ClassVideo>();
                List<AbilitySub> abilitySubs = new List<AbilitySub>();

                string code = $"ClassVideo-{_school}";
                await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher")
                        .GetItemQueryIterator<ClassVideo>(queryText: $"select value(c)  from c  ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(code) }))
                {
                    classVideos.Add(item);
                }
                //await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<ScTeacher>(queryText: $"SELECT c.groupName,c.groupId, c.id, c.name,   c.picture  FROM c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{_school}") }))
                //{
                //    if (string.IsNullOrEmpty(item.groupId))
                //    {
                //        item.groupId = "default";
                //        item.groupName = "默认组别";
                //    }
                //    groups.Add(item.groupName);
                //    groupDict[item.groupName] = item.groupId;
                //    teachers.Add(item);
                //}

                List<TchList> tchLists = new List<TchList>();
                await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<TchList>(queryText: $"SELECT value(c) FROM c  ",
                    requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"TchList-{_school}") }))
                {
                    groups.Add(item.name);
                    groupDict[item.name] = item.id;
                    tchLists.Add(item);
                }
                List<string> ids = tchLists.Select(x => x.id).ToList();
                if (!ids.IsNotEmpty())
                {
                    ids.Add("default");
                }
                (List<TmdInfo> tmdInfos, List<ClassListInfo> classInfos) = await TriggerStuActivity.GetTchList(client, _dingDing, ids, $"{_school}");
                List< GroupMember > teachers= new List<GroupMember>();
                foreach (var classInfo in classInfos) {
                    foreach (var tmdinfo in classInfo.tmdInfos) {
                        teachers.Add(new GroupMember { groupId = classInfo.id, groupName = classInfo.name, tmdid = tmdinfo.id, tmdname = tmdinfo.name, picture = tmdinfo.picture });
                    }
                }
                foreach (var tec in teachers)
                {
                    await foreach (var sub in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher")
                         .GetItemQueryIterator<AbilitySub>(queryText: $"select value(c) from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"AbilitySub-{_school}-{tec.tmdid}") }))
                    {
                        abilitySubs.Add(sub);
                    }
                }
                List<TeacherStatistic> groupMembers = new();


                //List<Study> studies = new List<Study>();
                //List<TrExam> exams = new List<TrExam>();
                //List<TrSurvey> surveys = new List<TrSurvey>();
                //List<TrVote> votes = new List<TrVote>();
                //await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Common")
                //      .GetItemQueryIterator<Study>(queryText: $"select c.owner, c.id, c.hour,c.teachers ,c.targets from c  ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Study-{_school}") }))
                //{
                //    studies.Add(item);
                //}
                //await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Common")
                //     .GetItemQueryIterator<TrExam>(queryText: $"select c.owner, c.teachers ,c.targets from c  ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"TrExam-{_school}") }))
                //{
                //    exams.Add(item);
                //}
                //await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Common")
                //  .GetItemQueryIterator<TrSurvey>(queryText: $"select c.owner, c.teachers,c.targets from c  ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"TrSurvey-{_school}") }))
                //{
                //    surveys.Add(item);
                //}
                //await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Common")
                //  .GetItemQueryIterator<TrVote>(queryText: $"select c.owner, c.teachers,c.targets from c  ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"TrVote-{_school}") }))
                //{
                //    votes.Add(item);
                //}

                //总人数
                int teacherCount = teachers.Count;
                //参与人数
                int joinCount = 0;
                //能力点订阅数量
                int subCount = 0;
                //已完成50个学时的人数
                int ok50TimeCount = 0;
                //已完成能力点的校园评审数量
                int hasScoreCount = 0;
                //已经提交作品的数量
                int hasSubmitCount = 0;
                // 未提交的
                int unSubmitCount = 0;
                //未完成能力点学习未完成的
                int unDoneCount = 0;
                //合格的能力点作品数量
                int okCount = 0;
                foreach (var t in teachers)
                {
                    int alltime = 0;
                    int allAbilityCount = 0;
                    int onlineTime = 0;
                    int offlinelTime = 0;
                    int schoolScoreTime = 0;
                    int classVideoTime = 0;
                    int tchSubmitCount = 0;
                    int tchUnSubmitCount = 0;
                    int hasAbilityExercise = 0;
                    int thcSubCount = 0;
                    int thcSubDoneCount = 0;
                    int offlineSchoolCount = 0;
                    int offlineAreaCount = 0;
                    int offlineSchoolDoneCount = 0;
                    int offlineAreaDoneCount = 0;
                    int examCount = 0;
                    int voteCount = 0;
                    int surveyCount = 0;
                    int examDoneCount = 0;
                    int voteDoneCount = 0;
                    int surveyDoneCount = 0;


                    //foreach (var item in studies)
                    //{
                    //    var tech = item.teachers.Find(x => x.id.Equals(t.id));
                    //    if (tech != null && tech.signTime > 0)
                    //    {
                    //        offlinelTime += item.hour;
                    //    }
                    //    if (!string.IsNullOrEmpty(item.owner))
                    //    {
                    //        if (item.owner.Equals("school"))
                    //        {
                    //            offlineSchoolCount += 1;
                    //            if (tech != null && tech.signTime > 0)
                    //            {
                    //                offlineSchoolDoneCount += 1;
                    //            }
                    //        }
                    //        else if (item.owner.Equals("area"))
                    //        {
                    //            offlineAreaCount += 1;
                    //            if (tech != null && tech.signTime > 0)
                    //            {
                    //                offlineAreaDoneCount += 1;
                    //            }
                    //        }
                    //    }
                    //}
                    //foreach (var item in exams)
                    //{
                    //    var tech = item.teachers.Find(x => x.id.Equals(t.id));
                    //    if (tech != null)
                    //    {
                    //        examCount += 1;
                    //        if (tech.answer.IsNotEmpty())
                    //        {
                    //            examDoneCount += 1;
                    //        }
                    //    }
                    //}
                    //foreach (var item in surveys)
                    //{
                    //    var tech = item.teachers.Find(x => x.id.Equals(t.id));
                    //    if (tech != null)
                    //    {
                    //        surveyCount += 1;
                    //        if (tech.answer.IsNotEmpty())
                    //        {
                    //            surveyDoneCount += 1;
                    //        }
                    //    }
                    //}
                    //foreach (var item in votes)
                    //{
                    //    var tech = item.teachers.Find(x => x.id.Equals(t.id));
                    //    if (tech != null)
                    //    {
                    //        voteCount += 1;
                    //        if (tech.answer.IsNotEmpty())
                    //        {
                    //            voteDoneCount += 1;
                    //        }
                    //    }
                    //}
                    bool isJoinVideo = false;
                    ClassVideo classVideo = classVideos.Find(x => x.id.Equals(t.tmdid));
                    if (classVideo != null && classVideo.files.IsNotEmpty())
                    {
                        isJoinVideo = true;
                        classVideo.files.ForEach(x =>
                        {
                            if (x.score > 0)
                            {
                                classVideoTime += 1;
                            }
                        });
                    }

                    List<SubStatistic> subs = new();
                    abilitySubs.Where(x => x.code.Equals($"AbilitySub-{_school}-{t.tmdid}")).ToList().ForEach(item => {
                        subCount += 1;
                        thcSubCount += 1;
                        if (item.exerciseScore > 0)
                        {
                            hasAbilityExercise += 1;
                        }
                        if (item.uploads.IsNotEmpty())
                        {
                            //已经有作品提交的
                            hasSubmitCount += 1;
                            tchSubmitCount += 1;
                        }
                        else
                        {
                            //未提交作品的
                            unSubmitCount += 1;
                            tchUnSubmitCount += 1;
                        }
                        if (!item.done)
                        {
                            unDoneCount += 1;
                        }
                        else
                        {
                            thcSubDoneCount += 1;
                        }
                        allAbilityCount += item.abilityCount;
                        onlineTime += item.hour;
                        if (item.otherScore.IsNotEmpty())
                        {
                            var schoolScore = item.otherScore.Where(x => x.roleType.Equals("school")).FirstOrDefault();

                            if (schoolScore != null)
                            {
                                if (schoolScore.score > 0)
                                {
                                    okCount += 1;
                                    schoolScoreTime += 1;
                                }
                                else
                                {
                                    hasScoreCount += 1;
                                }
                            }
                        }
                        Ability ability = abilities.Find(x => x.id.Equals(item.id));
                        subs.Add(new SubStatistic
                        {
                            abilityId = item.id,
                            code = item.code,
                            uploadCount = item.uploads.IsNotEmpty() ? item.uploads.Count : 0,
                            otherScoreCount = item.otherScore.IsNotEmpty() ? item.otherScore.Count : 0,
                            comidCount = 0,
                            self = item.self,
                            abilityName = ability.name,
                            no = ability.no,
                            dimension = ability.dimension,
                            env = ability.env
                        });
                    });
                    //处理单项 超标准 学时 
                    alltime += onlineTime >= 20 ? 20 : onlineTime;
                    alltime += offlinelTime >= 10 ? 10 : offlinelTime;
                    alltime += schoolScoreTime >= 15 ? 15 : schoolScoreTime;
                    alltime += classVideoTime >= 5 ? 5 : classVideoTime;
                    if (alltime >= 50)
                    {
                        ok50TimeCount += 1;
                    }
                    //表示有订阅,或者有线下活动参与的,或者有课堂实录视频上传的
                    if (subs.Count > 0 || schoolScoreTime > 0 || isJoinVideo)
                    {
                        //参训人数表示
                        joinCount += 1;
                        groupMembers.Add(new TeacherStatistic
                        {
                            tchSubmitCount = tchSubmitCount,
                            tchUnSubmitCount = tchUnSubmitCount,
                            thcSubCount = thcSubCount,
                            tmdname = t.tmdname,
                            tmdid = t.tmdid,
                            picture = t.picture,
                            groupName = t.groupName,
                            groupId = t.groupId,
                            subs = subs,
                            alltime = alltime,
                            allAbilityCount = allAbilityCount,
                            onlineTime = onlineTime,
                            offlinelTime = offlinelTime,
                            schoolScoreTime = schoolScoreTime,
                            classVideoTime = classVideoTime,
                            hasAbilityExercise = hasAbilityExercise,
                            thcSubDoneCount = thcSubDoneCount,
                            offlineSchoolCount = offlineSchoolCount,
                            offlineAreaCount = offlineAreaCount,
                            offlineSchoolDoneCount = offlineSchoolDoneCount,
                            offlineAreaDoneCount = offlineAreaDoneCount,
                            examCount = examCount,
                            voteCount = voteCount,
                            surveyCount = surveyCount,
                            examDoneCount = examDoneCount,
                            voteDoneCount = voteDoneCount,
                            surveyDoneCount = surveyDoneCount,
                        });
                    }
                }
                List<dynamic> dimensionCount = new List<dynamic>();
                foreach (var dms in dimensions)
                {
                    var list = groupMembers.SelectMany(x => x.subs.Where(y => y.dimension.Equals(dms))).ToList();
                    dimensionCount.Add(new { dimension = dms, count = list.IsNotEmpty() ? list.Count : 0 });
                }
                List<dynamic> abilityCount = new List<dynamic>();
                foreach (var abilityId in abilitieIds)
                {
                    var list = groupMembers.SelectMany(x => x.subs.Where(y => y.abilityId.Equals(abilityId))).ToList();
                    Ability ability = abilities.Find(x => x.id.Equals(abilityId));

                    abilityCount.Add(new { abilityId = abilityId, abilityName = ability.name, dimension = ability.dimension, abilityNo = ability.no, abilityEnv = ability.env, count = list.IsNotEmpty() ? list.Count : 0 });
                }
                List<dynamic> groupDatas = new List<dynamic>();


                foreach (var group in groups)
                {
                    int surveyGroupeCount = 0;
                    int voteGroupeCount = 0;
                    int examGroupeCount = 0;
                    int offlineSchoolGroupCount = 0;
                    int offlineAreaGroupCount = 0;
                    //  var stds = studies.Where(x => x.targets.Contains(group));
                    //if (stds != null)
                    //{
                    //    foreach (var item in stds)
                    //    {
                    //        if (!string.IsNullOrEmpty(item.owner))
                    //        {
                    //            if (item.owner.Equals("school"))
                    //            {
                    //                offlineSchoolGroupCount += 1;

                    //            }
                    //            else if (item.owner.Equals("area"))
                    //            {
                    //                offlineAreaGroupCount += 1;

                    //            }
                    //        }
                    //    }
                    //}
                    //var exms = exams.Where(x => x.targets.Contains(group));
                    //if (exms != null)
                    //{
                    //    examGroupeCount = exms.ToList().Count;
                    //}
                    //var svys = surveys.Where(x => x.targets.Contains(group));
                    //if (svys != null)
                    //{
                    //    surveyGroupeCount = svys.ToList().Count;
                    //}
                    //var vots = votes.Where(x => x.targets.Contains(group));
                    //if (vots != null)
                    //{
                    //    voteGroupeCount = vots.ToList().Count;
                    //}
                    var list = groupMembers.Where(x => x.groupName.Equals(group)).ToList();
                    groupDatas.Add(new
                    {
                        groupMemberCount = list.Count,
                        groupName = group,
                        groupId = groupDict[group],
                        thcSubCount = list.Select(x => x.thcSubCount).Sum(),
                        thcSubDoneCount = list.Select(x => x.thcSubDoneCount).Sum(),
                        offlineSchoolCount = list.Select(x => x.offlineSchoolCount).Sum(),
                        offlineAreaCount = list.Select(x => x.offlineAreaCount).Sum(),
                        offlineSchoolDoneCount = list.Select(x => x.offlineSchoolDoneCount).Sum(),
                        offlineAreaDoneCount = list.Select(x => x.offlineAreaDoneCount).Sum(),
                        examCount = list.Select(x => x.examCount).Sum(),
                        voteCount = list.Select(x => x.voteCount).Sum(),
                        surveyCount = list.Select(x => x.surveyCount).Sum(),
                        examDoneCount = list.Select(x => x.examDoneCount).Sum(),
                        voteDoneCount = list.Select(x => x.voteDoneCount).Sum(),
                        surveyDoneCount = list.Select(x => x.surveyDoneCount).Sum(),
                        surveyGroupeCount,
                        voteGroupeCount,
                        examGroupeCount,
                        offlineSchoolGroupCount,
                        offlineAreaGroupCount
                    });
                }
                return Ok(new { groupMembers, dimensionCount, abilityCount, teacherCount, joinCount, subCount, ok50TimeCount, hasScoreCount, hasSubmitCount, unDoneCount, unSubmitCount, okCount, groupDatas });
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS,{_option.Location},AbilityController/GetSubsStatistics()\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }
        }

        public record TeacherStatistic
        {
            public List<SubStatistic> subs { get; set; }
            public string tmdname { get; set; }
            public string tmdid { get; set; }
            public string picture { get; set; }
            public string groupName { get; set; }
            public string groupId { get; set; }
            public int alltime { get; set; }
            public int allAbilityCount { get; set; }
            public int onlineTime { get; set; }
            public int offlinelTime { get; set; }
            public int schoolScoreTime { get; set; }
            public int classVideoTime { get; set; }
            public int tchSubmitCount { get; set; }
            public int tchUnSubmitCount { get; set; }
            public int thcSubCount { get; set; }
            public int thcSubDoneCount { get; set; }
            public int hasAbilityExercise { get; set; }
            public int onlineCount { get; set; }
            public int offlineSchoolCount { get; set; }
            public int offlineAreaCount { get; set; }
            public int offlineSchoolDoneCount { get; set; }
            public int offlineAreaDoneCount { get; set; }
            public int examCount { get; set; }
            public int voteCount { get; set; }
            public int surveyCount { get; set; }
            public int examDoneCount { get; set; }
            public int voteDoneCount { get; set; }
            public int surveyDoneCount { get; set; }
        }
        public record SubStatistic
        {
            public string abilityId { get; set; }
            public string code { get; set; }
            public int uploadCount { get; set; }
            public int otherScoreCount { get; set; }
            public int self { get; set; }
            public int comidCount { get; set; }
            public string abilityName { get; set; }
            public string no { get; set; }
            public string dimension { get; set; }
            public string env { get; set; }
        }
        /// <summary>
        /// 获取回复详情信息。
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [HttpPost("get-reply-info")]
        [AuthToken(Roles = "teacher,student,admin,area")]
        public async Task<IActionResult> GetReplyInfo(JsonElement request)
        {
            if (!request.TryGetProperty("school", out JsonElement _school)) return BadRequest();
            if (!request.TryGetProperty("replyIds", out JsonElement _replyIds)) return BadRequest();
            List<string> replyIds = _replyIds.ToObject<List<string>>();
            if (replyIds.IsNotEmpty())
            {
                List<dynamic> replies = new List<dynamic>();
                string sql = $"select A1 as replies  from  c join  A1 in  c.replies    where A1.id in({string.Join(",", replyIds.Select(o => $"'{o}'"))})";
                await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School")
                          .GetItemQueryIterator<dynamic>(queryText: sql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Debate-{_school}") }))
                {
                    replies.Add(item);
                }
                return Ok(new { replies });
            }
            return Ok();
        }
        /// <summary>
        /// 获取本小组的订阅
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [HttpPost("get-group-subs")]
        [AuthToken(Roles = "teacher,student,admin,area")]
        public async Task<IActionResult> GetGroupSubs(JsonElement request)
        {
            try
            {
                if (!HttpContext.Items.TryGetValue("Standard", out object standard)) return BadRequest();
                // (string id, _, _, string school) = HttpContext.GetAuthTokenInfo();
                string school = "";
                if (!request.TryGetProperty("school", out JsonElement _school))
                {
                    return BadRequest();
                }
                else
                {
                    school = $"{_school}";
                }
                var client = _azureCosmos.GetCosmosClient();
                if (!request.TryGetProperty("tmdid", out JsonElement _tmdid)) return BadRequest();
                request.TryGetProperty("all", out JsonElement _all);
                List<Ability> abilities = new List<Ability>();
                await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School")
                           .GetItemQueryIterator<Ability>(queryText: $"select value(c) from c where c.status = 1 ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Ability-{standard}") }))
                {
                    abilities.Add(item);
                }
                //List<ScTeacher> teachers = new List<ScTeacher>();
                //await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<ScTeacher>(queryText: $"SELECT c.groupName,c.groupId, c.id, c.name,   c.picture  FROM c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{school}") }))
                //{
                //    if (string.IsNullOrEmpty(item.groupId))
                //    {
                //        item.groupId = "default";
                //        item.groupName = "默认组别";
                //    }
                //    teachers.Add(item);
                //}

                List<TchList> tchLists = new List<TchList>();
                await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<TchList>(queryText: $"SELECT value(c) FROM c  ",
                    requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"TchList-{_school}") }))
                {
                    tchLists.Add(item);
                }
                List<string> ids = tchLists.Select(x => x.id).ToList();
                if (!ids.IsNotEmpty())
                {
                    ids.Add("default");
                }
                (List<TmdInfo> tmdInfos, List<ClassListInfo> classInfos) = await TriggerStuActivity.GetTchList(client, _dingDing, ids, $"{_school}");
                List<GroupMember> teachers = new List<GroupMember>();
                foreach (var classInfo in classInfos)
                {
                    foreach (var tmdinfo in classInfo.tmdInfos)
                    {
                        teachers.Add(new GroupMember { groupId = classInfo.id, groupName = classInfo.name, tmdid = tmdinfo.id, tmdname = tmdinfo.name, picture = tmdinfo.picture });
                    }
                }
                if ($"{_all}".Equals("1"))
                {
                    List<SubGroupMember> groupMembers = new List<SubGroupMember>();
                   // List<Debate> debates = new List<Debate>();
                  //  HashSet<string> comids = new HashSet<string>();
                    foreach (var t in teachers)
                    {
                        try
                        {

                            await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher")
                                .GetItemQueryIterator<AbilitySub>(queryText: $"select value(c) from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"AbilitySub-{school}-{t.tmdid}") }))
                            {
                               // comids.Add(item.comid);
                                groupMembers.Add(new SubGroupMember
                                {
                                    tmdname = t.tmdname,
                                    tmdid = t.tmdid,
                                    picture = t.picture,
                                    groupName = t.groupName,
                                    groupId = t.groupId,
                                    sub = new SubGroup
                                    {
                                        abilityId = item.id,
                                        code = item.code,
                                        uploads = item.uploads,
                                        otherScore = item.otherScore,
                                        comid = item.comid,
                                        self = item.self
                                    }
                                });
                            }




                        }
                        catch (CosmosException ex) { }
                    }
                    //foreach (var comid in comids)
                    //{
                    //    try
                    //    {
                    //        Debate debate = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").ReadItemAsync<Debate>(comid, new PartitionKey($"Debate-{school}"));
                    //        debates.Add(debate);
                    //    }
                    //    catch (CosmosException ex)
                    //    {
                    //        continue;
                    //    }
                    //}
                   // List<DebateReply> debateReplies = debates.SelectMany(x => x.replies).ToList();
                    //groupMembers.ForEach(groupMember =>
                    //{
                    //    groupMember.sub.otherScore.ForEach(y =>
                    //    {
                    //        List<string> replyIds = new List<string>();
                    //        y.replyIds.ForEach(reply =>
                    //        {
                    //            if (reply != null)
                    //            {
                    //                DebateReply replies = debateReplies.Find(x => reply.Equals(x.id));
                    //                if (replies != null)
                    //                {
                    //                    replyIds.Add(replies.comment);
                    //                }
                    //            }
                    //        });
                    //        y.replyIds = replyIds;
                    //    });

                    //});
                    return Ok(new { groupMembers, abilities });
                }
                else
                {
                    var teacer = teachers.Find(x => x.tmdid.Equals($"{_tmdid}"));
                    if (teacer != null)
                    {
                        //List<Debate> debates = new List<Debate>();
                        List<SubGroupMember> groupMembers = new List<SubGroupMember>();
                     //   HashSet<string> comids = new HashSet<string>();
                        var tecs = teachers.Where(x => x.groupId.Equals(teacer.groupId)).ToList();
                        foreach (var t in tecs)
                        {
                            //排除自己
                            if (t.tmdid.Equals($"{_tmdid}")) { continue; }
                            await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher")
                                .GetItemQueryIterator<AbilitySub>(queryText: $"select value(c) from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"AbilitySub-{school}-{t.tmdid}") }))
                            {
                                groupMembers.Add(new SubGroupMember
                                {
                                    tmdname = t.tmdname,
                                    tmdid = t.tmdid,
                                    picture = t.picture,
                                    groupName = t.groupName,
                                    groupId = t.groupId,
                                    sub = new SubGroup
                                    {
                                        abilityId = item.id,
                                        code = item.code,
                                        uploads = item.uploads,
                                        otherScore = item.otherScore,
                                        comid = item.comid,
                                        self = item.self
                                    }
                                });
                            }
                        }
                        //foreach (var comid in comids)
                        //{
                        //    try
                        //    {
                        //        Debate debate = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School").ReadItemAsync<Debate>(comid, new PartitionKey($"Debate-{school}"));
                        //        debates.Add(debate);
                        //    }
                        //    catch (CosmosException ex)
                        //    {
                        //        continue;
                        //    }
                        //}
                        //List<DebateReply> debateReplies = debates.SelectMany(x => x.replies).ToList();
                        //groupMembers.ForEach(groupMember =>
                        //{
                        //    groupMember.sub.otherScore.ForEach(y =>
                        //    {
                        //        List<string> replyIds = new List<string>();
                        //        y.replyIds.ForEach(reply =>
                        //        {
                        //            if (reply != null)
                        //            {
                        //                DebateReply replies = debateReplies.Find(x => reply.Equals(x.id));
                        //                if (replies != null)
                        //                {
                        //                    replyIds.Add(replies.comment);
                        //                }
                        //            }
                        //        });
                        //        y.replyIds = replyIds;
                        //    });

                        //});
                        return Ok(new { groupMembers, abilities });
                    }
                    else
                    {
                        return BadRequest();
                    }
                }
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS,{_option.Location},AbilityController/SaveSubs()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }
        }
        public class SubGroup
        {
            public string comid { get; set; }
            public int self { get; set; }
            public string abilityId { get; set; }
            public string code { get; set; }
            public List<SubUpload> uploads { get; set; }
            public List<OtherScore> otherScore { get; set; }
        }
        public class GroupMember {
            public string tmdname { get; set; }
            public string tmdid { get; set; }
            public string picture { get; set; }
            public string groupName { get; set; }
            public string groupId { get; set; }
        }
        public class SubGroupMember
        {
            public string tmdname { get; set; }
            public string tmdid { get; set; }
            public string picture { get; set; }
            public string groupName { get; set; }
            public string groupId { get; set; }
            public SubGroup sub { get; set; }
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>

        [ProducesDefaultResponseType]
        [HttpPost("save-subs")]
        [AuthToken(Roles = "teacher,student,admin,area")]
        public async Task<IActionResult> SaveSubs(JsonElement request)
        {
            try
            {
                (string id, _, _, string school) = HttpContext.GetAuthTokenInfo();
                if (string.IsNullOrEmpty(school))
                {
                    if (!request.TryGetProperty("school", out JsonElement _school))
                    {
                        return BadRequest();
                    }
                    else
                    {
                        school = $"{_school}";
                    }
                }
                var client = _azureCosmos.GetCosmosClient();
                if (!request.TryGetProperty("tmdid", out JsonElement _tmdid)) return BadRequest();
                if (!request.TryGetProperty("abilityIds", out JsonElement _abilityIds)) return BadRequest();


                List<string> abilityIds = _abilityIds.ToObject<List<string>>();
                foreach (var abilityId in abilityIds)
                {
                    if (!string.IsNullOrEmpty(abilityId))
                    {
                        string code = $"AbilitySub-{school}-{_tmdid}";
                        try
                        {
                            await client.GetContainer("TEAMModelOS", "Teacher").ReadItemAsync<AbilitySub>(abilityId, new PartitionKey(code));
                        }
                        catch (CosmosException ex)
                        {
                            if (ex.Status == 404)
                            {
                                AbilitySub abilitySub = new AbilitySub
                                {
                                    id = abilityId,
                                    code = $"AbilitySub-{school}-{_tmdid}",
                                    school = $"{school}",
                                    creatorId = $"{_tmdid}",
                                    done = false,
                                    hour = 0,
                                    comid = Guid.NewGuid().ToString(),
                                    pk = "AbilitySub"
                                };
                                await client.GetContainer("TEAMModelOS", "Teacher").CreateItemAsync(abilitySub, new PartitionKey(abilitySub.code));
                            }
                        }
                    }
                }
                return Ok(new { abilityIds });
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS,{_option.Location},AbilityController/SaveSubs()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }
        }


        /// <summary>
        ///当前老师 获取没有订阅以及已经订阅的能力点学习课程
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [AuthToken(Roles = "teacher,student,admin,area")]
        [HttpPost("get-subs")]
        public async Task<IActionResult> GetSubs(JsonElement request)
        {
            try
            {
                if (!HttpContext.Items.TryGetValue("Standard", out object standard)) return BadRequest();
                ///没有订阅的
                List<Ability> notSub = new List<Ability>();
                ///已经订阅的
                List<Ability> hadSubs = new List<Ability>();
                ///订阅的学习记录
                List<AbilitySub> rcdSubs = new List<AbilitySub>();

                //tmdid
                if (!request.TryGetProperty("tmdid", out JsonElement tmdid)) return BadRequest();
                //学校编码

                (string id, _, _, string school) = HttpContext.GetAuthTokenInfo();
                if (string.IsNullOrEmpty(school))
                {
                    if (!request.TryGetProperty("school", out JsonElement _school))
                    {
                        return BadRequest();
                    }
                    else
                    {
                        school = $"{_school}";
                    }
                }
                if (!string.IsNullOrEmpty(school))
                {
                    await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School")
                           .GetItemQueryIterator<Ability>(queryText: $"select value(c) from c where c.status = 1 ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Ability-{standard}") }))
                    {
                        notSub.Add(item);
                    }
                    await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher")
                            .GetItemQueryIterator<AbilitySub>(queryText: $"select value(c) from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"AbilitySub-{school}-{tmdid}") }))
                    {
                        var had = notSub.Where(x => x.id.Equals(item.id)).FirstOrDefault();
                        if (had != null)
                        {
                            notSub.Remove(had);
                            hadSubs.Add(had);
                        }
                        rcdSubs.Add(item);
                    }
                }
                else { return BadRequest(); };
                return Ok(new { rcdSubs, hadSubs });
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS,{_option.Location},AbilityController:get-subs\n{ex.Message}{ex.StackTrace}\n{request.ToJsonString()}", GroupNames.成都开发測試群組);
                return BadRequest();
            }
        }
    }
}
