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;

namespace TEAMModelOS.Controllers.Research
{
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    //[Authorize(Roles = "IES5")]
    [Route("research/class-video")]
    [ApiController]
    public class ClassVideoController : ControllerBase
    {
        private readonly AzureCosmosFactory _azureCosmos;
        private readonly SnowflakeId _snowflakeId;
        private readonly DingDing _dingDing;
        private readonly Option _option;
        public ClassVideoController(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("get-group")]
        public async Task<IActionResult> GetGroup(JsonElement request)
        {
            try
            {
                var client = _azureCosmos.GetCosmosClient();
                if (!request.TryGetProperty("tmdid", out JsonElement _tmdid)) return BadRequest();
                if (!request.TryGetProperty("school", out JsonElement _school)) return BadRequest(); 
                //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  join A1 in c.teachers where A1='{_tmdid}'",
                    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}");
                if (classInfos.IsNotEmpty())
                {
                    List<dynamic> groupMembers = new List<dynamic>();
                    foreach (var classinfo in classInfos)
                    {
                        foreach (var t in classinfo.tmdInfos)
                        {
                            //排除自己
                            if (t.id.Equals($"{_tmdid}")) { continue; }
                            try
                            {
                                ClassVideo classVideo = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher").ReadItemAsync<ClassVideo>(t.id, partitionKey: new PartitionKey($"ClassVideo-{_school}"));
                                if (classVideo.files.IsNotEmpty())
                                {
                                    foreach (var file in classVideo.files)
                                    {
                                        groupMembers.Add(new
                                        {
                                            tmdname = t.name,
                                            tmdid = t.id,
                                            picture = t.picture,
                                            groupName = classinfo.name,
                                            groupId = classinfo.id,
                                            // roles = t.roles,
                                            school = $"{_school}",
                                            score = file.score,
                                            vid = file.id,
                                            vurl = file.url,
                                            vname = file.name,
                                            vsize = file.size,
                                            vtime = file.time
                                        });
                                    }
                                }
                            }
                            catch (CosmosException ex)
                            {

                            }
                        }
                    }
                    return Ok(new { groupMembers });
                }
                else {
                    return Ok(new { });
                }

                //var teacer = teachers.Find(x => x.id .Equals($"{_tmdid}"));
                //if (teacer != null ) 
                //{
                //    if (!string.IsNullOrEmpty(teacer.groupId))
                //    {
                //        List<dynamic> groupMembers = new List<dynamic>();
                //        var tecs = teachers.Where(x => !string.IsNullOrEmpty(x.groupId) && x.groupId.Equals(teacer.groupId)).ToList();
                //        foreach (var t in tecs)
                //        {
                //            //排除自己
                //            if (t.id.Equals($"{_tmdid}")) { continue; }
                //            try
                //            {
                //                ClassVideo classVideo = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher").ReadItemAsync<ClassVideo>(t.id, partitionKey: new PartitionKey($"ClassVideo-{_school}"));
                //                if (classVideo.files.IsNotEmpty())
                //                {
                //                    foreach (var file in classVideo.files) {
                //                        groupMembers.Add(new
                //                        {
                //                            tmdname = t.name,
                //                            tmdid = t.id,
                //                            picture = t.picture,
                //                            groupName = t.groupName,
                //                            groupId = t.groupId,
                //                            roles=t.roles,
                //                            school = $"{_school}",
                //                            score = file.score,
                //                            vid = file.id,
                //                            vurl = file.url,
                //                            vname = file.name,
                //                            vsize = file.size,
                //                            vtime = file.time
                //                        });
                //                    }
                //                }
                //            }
                //            catch (CosmosException ex)
                //            {

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

        [ProducesDefaultResponseType]
        [HttpPost("get-all")]
        public async Task<IActionResult> GetAll(JsonElement request)
        {
            try
            {
                var client = _azureCosmos.GetCosmosClient();
                if (!request.TryGetProperty("school", out JsonElement _school)) return BadRequest();
                
                //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}") }))
                //{
                //    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<dynamic> classVideos = new();
                string code = $"ClassVideo-{_school}";
                foreach (var listInfo in classInfos) {
                    try
                    {
                        await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher")
                            .GetItemQueryIterator<ClassVideo>(queryText: $"select value(c) from c where c.id in ({string.Join(",", listInfo.tmdInfos.Select(o => $"'{o.id}'"))})", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(code) }))
                        {
                            TmdInfo info= listInfo.tmdInfos.Find(x => x.id.Equals(item.id));
                            if (info != null) {
                                dynamic t = new { id=info.id,name=info.name, picture=info.picture, groupId= listInfo.id, groupName=listInfo.name };
                                foreach (var vids in item.files)
                                {
                                    classVideos.Add(new { videos = vids, teacher = t, school = item.school });
                                }
                            }
                            
                        }
                    }
                    catch (CosmosException ex) { }
                }

                //foreach (var t in teachers) {
                //    try
                //    {
                //        await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher")
                //            .GetItemQueryIterator<ClassVideo>(queryText: $"select value(c) from c where c.id='{t.id}' ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(code) }))
                //        {
                //            foreach (var vids in item.files)
                //            {
                //                classVideos.Add(new { videos = vids, teacher = t, school = item.school });
                //            }
                //        }
                //    }
                //    catch (CosmosException ex) { }
                //}
                return Ok(new { classVideos });
            }
            catch (Exception ex) { 
            }
            return Ok();
        }

        /// <summary>
        ///课堂实录操作接口
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [HttpPost("opt")]
        public async Task<IActionResult> Opt(JsonElement request)
        {
            try
            {
                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();
                string code = $"ClassVideo-{_school}";
                switch ($"{_opt}") {
                    case "Score":
                        if (!request.TryGetProperty("videoId", out JsonElement _videoId)) return BadRequest();
                        if (!request.TryGetProperty("score", out JsonElement _score)) return BadRequest();
                        ClassVideo videoRd=null;
                        try
                        {
                            videoRd = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemAsync<ClassVideo>($"{_tmdid}", new PartitionKey(code));
                            var fid= videoRd.files.Find(x => x.id.Equals($"{_videoId}"));
                            fid.score = int.Parse($"{_score}");
                            await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<ClassVideo>(videoRd,videoRd.id, new PartitionKey(code));
                            return Ok(new { status = 1 });
                        }
                        catch (CosmosException ex)
                        {
                            if (ex.Status == 404)
                            {
                                return Ok(new { status = 0 });
                            }
                        }
                        return BadRequest();
                    case "Upload":
                        if (!request.TryGetProperty("files", out JsonElement _files)) return BadRequest();
                        List<AbilityFile> files = _files.ToObject<List<AbilityFile>>();
                        if (files.IsNotEmpty()) {
                            foreach (var up in files) {
                                up.id = string.IsNullOrEmpty(up.id)? Guid.NewGuid().ToString():up.id;
                                up.time = up.time <= 0? DateTimeOffset.UtcNow.ToUnixTimeMilliseconds():up.time;
                            }
                            ClassVideo classVideo = null;
                            try
                            {
                                classVideo = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemAsync<ClassVideo>($"{_tmdid}", new PartitionKey(code));
                                foreach (var up in files) {
                                    var vd=  classVideo.files.Find(x => x.id.Equals(up.id));
                                    if (vd != null)
                                    {
                                        vd.url = up.url;
                                        vd.name = up.name;
                                        vd.time = up.time;
                                        vd.size = up.size;
                                    }
                                    else {
                                        classVideo.files.Add(up);
                                    }
                                }
                                await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<ClassVideo>(classVideo, $"{_tmdid}", new PartitionKey(code));
                                return Ok(new { classVideo });
                            }
                            catch (CosmosException ex)
                            {
                                if (ex.Status == 404) {
                                    classVideo = new ClassVideo { id = $"{_tmdid}", pk = "ClassVideo", code = code, school = $"{_school}", creatorId = $"{_tmdid}", files = files };
                                    await client.GetContainer("TEAMModelOS", "Teacher").CreateItemAsync<ClassVideo>(classVideo, new PartitionKey(code));
                                    return Ok(new { classVideo });
                                }
                            }
                            return Ok(new { classVideo });
                        }
                        else {
                            return BadRequest();
                        }
                        
                    case "Delete":
                        if (!request.TryGetProperty("ids", out JsonElement _ids)) return BadRequest();
                        List<string> ids = _ids.ToObject<List<string>>();
                        try
                        {
                            ClassVideo delvideo = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemAsync<ClassVideo>($"{_tmdid}", new PartitionKey(code));
                            if (delvideo.files.IsNotEmpty()) {
                                ids.ForEach(id => {
                                  var video=   delvideo.files.Find(x => x.id.Equals(id) );
                                    if (video != null) { 
                                        
                                        delvideo.files.Remove(video); 
                                    }
                                });
                            }
                            await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<ClassVideo>(delvideo, $"{_tmdid}", new PartitionKey(code));

                            //TODO同时删除话题和点评记录
                            return Ok(new { classVideo = delvideo });
                        }
                        catch (CosmosException ex)
                        {
                            return BadRequest();
                        }
                    case "Read":
                        ClassVideo video = new ClassVideo { id = $"{_tmdid}", pk = "ClassVideo", code = code, school = $"{_school}", creatorId = $"{_tmdid}", files = new List<AbilityFile>() };
                        try {
                            video = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemAsync<ClassVideo>($"{_tmdid}", new PartitionKey(code));
                        }
                        catch (CosmosException ex)
                        {
                            if (ex.Status == 404)
                            {
                                await client.GetContainer("TEAMModelOS", "Teacher").CreateItemAsync<ClassVideo>(video, new PartitionKey(code));
                                return Ok(new { classVideo= video });
                            }
                        }
                        return Ok(new { classVideo= video });
                    case "Appraise":
                       //TODO课堂实录个人查看别人的评价
                    default:
                        return BadRequest($"{_opt}  is undefined!");
                }
            }
            catch (Exception ex) {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，ClassVideoController/Opt()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }
        }
    }
}
