using Azure.Cosmos;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Text.Json;
using System.Threading.Tasks;
using TEAMModelOS.Models.Dto;
using TEAMModelOS.SDK.Models;
using TEAMModelOS.SDK;
using TEAMModelOS.SDK.DI;
using TEAMModelOS.SDK.Extension;
using TEAMModelOS.SDK.Helper.Common.CollectionHelper;
using TEAMModelOS.SDK.Helper.Common.StringHelper;
using TEAMModelOS.Models;
using Microsoft.Extensions.Options;
using System.Text;

namespace TEAMModelOS.Controllers
{
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    //[Authorize(Roles = "IES5")]
    [Route("teacher/comment")]
    [ApiController]
    public class CommentController :ControllerBase
    {
        private readonly AzureCosmosFactory _azureCosmos;
        private readonly DingDing _dingDing;
        private readonly Option _option;
        private readonly AzureStorageFactory _azureStorage;
        public CommentController(AzureCosmosFactory azureCosmos, DingDing dingDing, IOptionsSnapshot<Option> option, AzureStorageFactory azureStorage)
        {
            _azureCosmos = azureCosmos;
            _dingDing = dingDing;
            _option = option?.Value;
            _azureStorage = azureStorage;
        }

        /// <summary>
        /// 添加教师评语快捷回复
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [HttpPost("add-comment")]
        public async Task<IActionResult> AddComment(JsonElement request)
        {
            //var id = "Comment-" + request.TEAMModelId.Replace("#", "");
            //ResponseBuilder builder = ResponseBuilder.custom();
            //List<Comment> comments = await _azureCosmos.FindByDict<Comment>(new Dictionary<string, object> { { "code", request.TEAMModelId }, { "id", id } });
            //Comment comment = new Comment();
            //if (comments.IsEmpty())
            //{
            //    comment.id = id;
            //    comment.code = request.TEAMModelId;
            //    comment.comment.Add(request.comment);
            //    comments.Add(comment);
            //}
            //else {
            //    comment = comments[0];
            //    comment.comment.Add(request.comment);
            //}
            //builder.Data(await _azureCosmos.SaveOrUpdate(comment));
            //return builder.build();
            //return Ok(await _azureCosmos.SaveOrUpdate(comment));
            return Ok();
        }

        /// <summary>
        /// 查询教师评语罐头
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [HttpPost("find-comment")]
        public async Task<IActionResult> findComment(JsonElement requert)
        {
            //var client = _azureCosmos.GetCosmosClient();
            //if (!requert.TryGetProperty("school_code", out JsonElement school_code)) return BadRequest();
            ////var (id, name, picture, _) = HttpContext.GetAuthTokenInfo();
            //if (!requert.TryGetProperty("id_token", out JsonElement id_token)) return BadRequest();
            //var jwt = new JwtSecurityToken(id_token.GetString());
            //if (!jwt.Payload.Iss.Equals("account.teammodel", StringComparison.Ordinal)) return BadRequest();
            //var id = jwt.Payload.Sub;

            //List<object> comments = new List<object>();
            //var query = $"select c.id,c.comment from c";
            //await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Comment-{id}") }))
            //{
            //    using var json = await JsonDocument.ParseAsync(item.ContentStream);

            //    if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
            //    {
            //        foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
            //        {
            //            comments.Add(obj.ToObject<object>());
            //        }
            //    }
            //}

            return Ok();           
        }
        /// <summary>
        /// 更新保存教师评语罐头,如果评语列表为空则删除
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [HttpPost("upsert-comment")]
        public async Task<IActionResult> UpsertComment(Comment request)
        {
            // request.TryAdd("PartitionKey", request.lang);
            //ResponseBuilder builder = ResponseBuilder.custom();
            //Comment comment = null;
            //if (request.comment.Count > 0)
            //{
            //    if (string.IsNullOrEmpty(request.id)) {
            //        request.id  = "Comment-" + request.code.Replace("#", "");
            //    }
            //    comment = await _azureCosmos.SaveOrUpdate<Comment>(request);
            //}
            //else {
            //    if (!string.IsNullOrEmpty(request.id))
            //    {
            //        IdPk idPk = await _azureCosmos.DeleteAsync<Comment>(request.id, request.code);
            //    }
                   
            //}
            ////return builder.Data(comment).build();
            return Ok();
        }

        //批注
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "Teacher")]
        [HttpPost("upsert-answer")]
        public async Task<IActionResult> upsertAnswer(JsonElement request)
        {

            if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
            if (!request.TryGetProperty("answer", out JsonElement answer)) return BadRequest();
            if (!request.TryGetProperty("studentId", out JsonElement studentId)) return BadRequest();
            if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
            if (!request.TryGetProperty("classId", out JsonElement classId)) return BadRequest();
            //根据不同评测的类型返回对应的编码
            if (!request.TryGetProperty("code", out JsonElement school)) return BadRequest();
            try
            {
                var client = _azureCosmos.GetCosmosClient();
                List<ExamClassResult> examClassResults = new List<ExamClassResult>();
                await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(
                    queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and c.info.id = '{classId}'",
                    requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school}") }))
                {
                    using var json = await JsonDocument.ParseAsync(item.ContentStream);
                    if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
                    {
                        foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
                        {
                            examClassResults.Add(obj.ToObject<ExamClassResult>());
                        }
                    }
                }
                ExamClassResult classResult = new ExamClassResult();              
                List<List<string>> ans = answer.ToObject<List<List<string>>>();
                List<List<string>> standard = new List<List<string>>();
                List<double> points = new List<double>();
                List<Task<string>> tasks = new List<Task<string>>();
                foreach (ExamClassResult result in examClassResults)
                {
                    int index = result.studentIds.IndexOf(studentId.ToString());
                    StringBuilder builder = new StringBuilder();
                    builder.Append(result.examId).Append("/");
                    builder.Append(result.subjectId).Append("/");
                    builder.Append(studentId).Append("mark").Append("/");
                    builder.Append("ans.json");
                    /*string FileName = result.examId + "/" + result.subjectId + "/" + studentId;
                    string blob = FileName + "/" + "ans.json";*/
                    tasks.Add(_azureStorage.UploadFileByContainer(school.ToString(), ans.ToJsonString(), "exam", builder.ToString(), false));
                    //result.studentAnswers[newIndex].Add(builder.ToString());
                    /*string FileName = result.examId + "/" + result.subjectId + "/" + studentId + "mark";
                    string blob = await _azureStorage.UploadFileByContainer(school.ToString(), ans.ToJsonString(), "exam", FileName + "/" + "ans.json");*/
                    //result.studentAnswers[index].Add(blob);
                    if (result.mark == null || result.mark.Count == 0) {
                        List<string> annotation = new List<string>();
                        foreach (string ids in result.studentIds) {
                            annotation.Add("");
                        }
                        result.mark = annotation;
                    }
                    result.mark[index] = builder.ToString();
                    classResult = await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(result, result.id, new PartitionKey($"{result.code}"));
                }

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

        }


    }
}
