
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.Context.Constant.Common;
using TEAMModelOS.SDK.DI;
using TEAMModelOS.SDK.Extension;
using TEAMModelOS.SDK.Helper.Common.CollectionHelper;
using TEAMModelOS.SDK.Helper.Common.StringHelper;

namespace TEAMModelOS.Controllers.Learn
{
    // TODO 代码优化

    /// <summary>
    /// 作业活动
    /// </summary>
    /// 
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    [Route("common/homework")]
    [ApiController]
    public class HomeworkController : ControllerBase
    {
        private readonly SnowflakeId _snowflakeId;
        private readonly AzureCosmosFactory _azureCosmos;       
        private readonly AzureServiceBusFactory _serviceBus;
        public HomeworkController(AzureCosmosFactory azureCosmos, AzureServiceBusFactory serviceBus , SnowflakeId snowflakeId)
        {
            _azureCosmos = azureCosmos;            
            _snowflakeId = snowflakeId;
            _serviceBus = serviceBus;
        }


    //    /// <summary>
    //    /// 撤消作业
    //    /// </summary>
    //    /// <param name="request"></param>
    //    /// <returns></returns>
    //    [ProducesDefaultResponseType]
    //    [HttpPost("cancel")]
    //    public async Task<IActionResult> Cancel(JsonElement requert)
    //    {
    //        /* if (!requert.TryGetProperty("id_token", out JsonElement id_token)) return BadRequest();
    //         //if (!requert.TryGetProperty("school_code", out JsonElement school_code)) return BadRequest();
    //         var jwt = new JwtSecurityToken(id_token.GetString());
    //         if (!jwt.Payload.Iss.Equals("account.teammodel", StringComparison.Ordinal)) return BadRequest();
    //         var id = jwt.Payload.Sub;
    //         //var id = "03245d02-71ba-4e44-97dd-1e66c91bff6c";
    //         //if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
    //         var client = _azureCosmos.GetCosmosClient();
    //         //權限token
    //        *//* jwt.Payload.TryGetValue("name", out object name);
    //         jwt.Payload.TryGetValue("picture", out object picture);*//*
    //         var response = await client.GetContainer("TEAMModelOSTemp", "Teacher").ReadItemStreamAsync(id, new PartitionKey($"Homework-{id_token}"));
    //         if (response.Status == 200)
    //         {
    //             using var json = await JsonDocument.ParseAsync(response.ContentStream);
    //             int status = json.RootElement.GetProperty("status").GetInt32();
    //         }
    //         return Ok();*/
    //        ResponseBuilder builder = ResponseBuilder.custom();
    //        requert.TryGetProperty("id", out JsonElement homeWorkId);
    //        List<Homework> homeWorks = await _azureCosmos.FindByDict<Homework>(new Dictionary<string, object> { { "id", homeWorkId.ToString() } });

    //        foreach (Homework homeWork in homeWorks)
    //        {
    //            homeWork.status = 100;
    //        }
    //        List<Homework> homeWorks1 = await _azureCosmos.UpdateAll<Homework>(homeWorks);

    //        //查询之前是否有 关联关系表 HomeWorkStudent 有则删除
    //        List<HomeworkRecord> homeWorkStudents = await _azureCosmos.FindByDict<HomeworkRecord>(new Dictionary<string, object> { { "id", homeWorkId.ToString() } });
    //        if (homeWorkStudents.IsNotEmpty())
    //        {

    //            //TODO 删除上传的文件
    //            await _azureCosmos.DeleteAll(homeWorkStudents);
    //        }
    //        //return builder.Data(homeWorks1).build();
    //        return Ok(homeWorks1);
    //    }

    //    /// <summary>
    //    /// 删除作业
    //    /// </summary>
    //    /// <param name="request"></param>
    //    /// <returns></returns>
    //    [ProducesDefaultResponseType]
    //    [HttpPost("delete")]
    //    public async Task<IActionResult> Delete(IdPk request)
    //    {
    //        //ResponseBuilder builder = ResponseBuilder.custom();
    //        //IdPk idPk = await _azureCosmos.DeleteAsync<Homework>(request);
    //        ////按作业id删除提交记录
    //        //List<HomeworkRecord> homeWorkStudents =  await _azureCosmos.FindByDict<HomeworkRecord>(new Dictionary<string, object> { { "id", idPk.id } });
    //        ////TODO 删除上传的文件
    //        //await _azureCosmos.DeleteAll<HomeworkRecord>(homeWorkStudents);
    //        ////return builder.Data(idPk).build();
    //        //return Ok(idPk);
    //    }


    //    /// <summary>
    //    /// 新增或修改 作业活动 同时创建关联关系表
    //    /// </summary>
    //    /// <param name="request"></param>
    //    /// <returns></returns>
    //    [ProducesDefaultResponseType]
    //    [HttpPost("upsert")]
    //    public async Task<IActionResult> Upsert(HomeworkDto request)
    //    {
    //        ResponseBuilder builder = ResponseBuilder.custom();
    //        //新增
    //        var (id, name, picture, _) = HttpContext.GetAuthTokenInfo();
    //        if (string.IsNullOrEmpty(request.homeWork.id))

    //        {
    //            request.homeWork.code = "Homework-" + id;
    //            request.homeWork.id = _snowflakeId.NextId()+"";
    //            request.homeWork.status = 100;
    //            request.reset = true;
    //            request.homeWork.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
    //        }

            
    //        /*if (request.homeWork.publishModel.Equals("0"))
    //        {
    //            request.homeWork.startTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
    //            request.homeWork.status = 200;
    //        }
    //        else if (request.homeWork.publishModel.Equals("1"))
    //        {
    //            //TimerWork<HomeWork>(request.@params.homeWork.startTime,new Dictionary<string, object> { { "id", request.@params.homeWork.id } });
    //            //设定开始时间
    //            string msgId = _snowflakeId.NextId() + "";
    //            long SequenceNumber =  await _serviceBus.GetServiceBusClient().SendLeamMessage<Homework>(Constants.TopicName, request.homeWork.id, request.homeWork.code, request.homeWork.startTime,"going", msgId);
    //            request.homeWork.sequenceNumber = SequenceNumber;

    //            //serviceBusReviceService.ReciveMessageAsync();
    //            //await _serviceBus.ReciveMessageAsync<Homework>(Constants.SubName);
    //            //_timerWorkService.TimerWork<Homework>(request.@params.homeWork.startTime,200, new Dictionary<string, object> { { "id", request.@params.homeWork.id } });
    //        }*/

    //        if (request.homeWork.status == 0) {

    //            if (request.homeWork.startTime < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()) request.homeWork.status = 200;
    //            else  request.homeWork.status = 100;
    //        }

    //        Homework homeWork = await _azureCosmos.SaveOrUpdate<Homework>(request.homeWork);

    //        //设定结束时间
    //        /*string msgEndId = _snowflakeId.NextId() + "";
    //        await _serviceBus.GetServiceBusClient().SendLeamMessage<Homework>(Constants.TopicName, request.homeWork.id, request.homeWork.code, request.homeWork.endTime);*/
    //        //_timerWorkService.TimerWork<Homework>(request.@params.homeWork.endTime, 300, new Dictionary<string, object> { { "id", request.@params.homeWork.id } });
    //        //清除作业
    //        if (request.reset)
    //        {
    //            //根据作业发布对象查找到每一个具体学生生成关联关系表 HomeWorkStudent
    //          //  List<Target> targets = request.@params.homeWork.target;
    //            //List<HomeworkRecord> homeWorkStudents = new List<HomeworkRecord>();
    //           // foreach (Target target in targets)
    //           // {
    //                //查询之前是否有 关联关系表 HomeWorkStudent 有则删除
    //                List<HomeworkRecord> homeWorks = await _azureCosmos.FindByDict<HomeworkRecord>(new Dictionary<string, object> { { "id", request.homeWork.id } });
    //                if (homeWorks.IsNotEmpty())
    //                {
    //                    await _azureCosmos.DeleteAll(homeWorks);
    //                }
    //                //List<ClassStudent> classroom = await _cosmos.FindByDict<ClassStudent>(new Dictionary<string, object> { { "id", target.classroomCode }});
    //                //if (classroom.IsNotEmpty())
    //                //{
                        
    //                //    foreach (ClassStudent student in classroom)
    //                //    {
    //                //        HomeworkRecord homeWorkStudent = new HomeworkRecord();
    //                //        homeWorkStudent.code = student.code;
    //                //        homeWorkStudent.id = request.@params.homeWork.id;
    //                //        homeWorkStudent.classroom.code = target.classroomCode;
    //                //        homeWorkStudent.classroom.name = target.classroomName;
    //                //        homeWorkStudents.Add(homeWorkStudent);
    //                //    }
                        
    //                //}
    //            //}
    //            //if (homeWorkStudents.IsNotEmpty())
    //            //{
    //            //    foreach (HomeworkRecord homeWorkStudents1 in homeWorkStudents)
    //            //    {
    //            //        List<Student> student = await _cosmos.FindById<Student>(homeWorkStudents1.code);//FindByDict<Student>(new Dictionary<string, object> { { "id", homeWorkStudents1.studentId } });
    //            //        if (student.IsNotEmpty())
    //            //        {
                          
    //            //            homeWorkStudents1.code = student[0].studentId;
    //            //          //  homeWorkStudents1.nativeroom.code = student[0].classroomCode;
    //            //        }
    //            //    }
    //            //    await _cosmos.SaveOrUpdateAll<HomeworkRecord>(homeWorkStudents);
    //            //}
    //        }
    //        //return builder.Data(homeWork).build();
    //        return Ok(homeWork);
    //    }

    //    /// <summary>
    //    /// 新增或修改学生作业关联表
    //    /// </summary>
    //    /// <param name="request"></param>
    //    /// <returns></returns>
    //    [ProducesDefaultResponseType]
    //    [HttpPost("upsert-record")]
    //    public async Task<IActionResult> UpsertRecord(List<HomeworkRecord> request)
    //    {
    //        //ResponseBuilder builder = ResponseBuilder.custom();
    //        await _azureCosmos.SaveOrUpdateAll<HomeworkRecord>(request);
    //        //return builder.Data(request).build();
    //        return Ok(request);
    //    }

    //    /// <summary>
    //    /// 查询作业活动
    //    /// </summary>
    //    /// <param name="request"></param>
    //    /// <returns></returns>
    //    [ProducesDefaultResponseType]
    //    [HttpPost("find")]
    //    public async Task<IActionResult> Find(JsonElement request)
    //    {

    //        ResponseBuilder builder = ResponseBuilder.custom();
    //        List<Homework> data = new List<Homework>();
    //        List<HomeworkFindDto> homeWorkFindDtos = new List<HomeworkFindDto>();
    //        if (StringHelper.getKeyCount(request) > 0)
    //        {
    //            data = await _azureCosmos.FindByDict<Homework>(request);
    //            //判断作业提交信息
    //            if (data.IsNotEmpty())
    //            {
    //                foreach (Homework homeWork in data)
    //                {
    //                    //HomeworkFindDto homeWorkFindDto = new HomeworkFindDto();
    //                    List<string> pro = new List<string>();
    //                    pro.Add("submit");
    //                    List<HomeworkRecord> homeWorkStudents = await _azureCosmos.FindByDict<HomeworkRecord>(dict: new Dictionary<string, object> { { "id", homeWork.id } }, propertys: pro);
    //                    int sub = 0;
    //                    Dictionary<string, object> dict = new Dictionary<string, object>();
    //                    dict.Add("Sum", homeWorkStudents.Count);
    //                    dict.Add("Finish", sub);
    //                    HomeworkFindDto homeWorkFindDto = homeWork.ToJsonString().ToObject<HomeworkFindDto>();
    //                    homeWorkFindDto.statistics = dict;
    //                    homeWorkFindDtos.Add(homeWorkFindDto);
    //                }
    //            }
    //        }
    //        else
    //        {
    //            ///return builder.Error(ResponseCode.PARAMS_ERROR, "参数异常！").build();
    //            return Ok("参数异常！");
    //        }
    //        //return builder.Data(homeWorkFindDtos).Extend(new Dictionary<string, object> { { "count", data.Count } }).build();
    //        return Ok(new { homeWorkFindDtos, data.Count });
    //    }

    //    /// <summary>
    //    /// 查询作业学生关联
    //    /// </summary>
    //    /// <param name="request"></param>
    //    /// <returns></returns>
    //    [ProducesDefaultResponseType]
    //    [HttpPost("find-record")]
    //    public async Task<IActionResult> FindRecord(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> records = new List<object>();
    //        var query = $"select c.id,c.classroom,c.submit, c.submitTime,c.score,c.content,c.stuCmt,c.tchCmt from c where id = {id}";
    //        await foreach (var item in client.GetContainer("TEAMModelOS", "Student").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"HomeworkRecord-{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())
    //                {
    //                    records.Add(obj.ToObject<object>());
    //                }
    //            }
    //        }

    //        return Ok(new { records });
    //        /*ResponseBuilder builder = ResponseBuilder.custom();
    //        List<HomeworkRecord> data = new List<HomeworkRecord>();

    //        if (StringHelper.getKeyCount(request) > 0)
    //        {
    //            data = await _azureCosmos.FindByDict<HomeworkRecord>(request);
    //        }
    //        else
    //        {
    //            return builder.Error(ResponseCode.PARAMS_ERROR, "参数异常！").build();
    //        }
    //        return builder.Data(data).Extend(new Dictionary<string, object> { { "count", data.Count } }).build();*/
    //    }




    //    /// <summary>
    //    /// 教师作业打分评论
    //    /// </summary>
    //    /// <param name="request"></param>
    //    /// <returns></returns>
    //    [ProducesDefaultResponseType]
    //    [HttpPost("tch-score")]
    //    public async Task<IActionResult> TchScore(HomeworkScoringDto request)
    //    {
    //        ResponseBuilder builder = ResponseBuilder.custom();
    //        List<HomeworkRecord> homeWorkStudents = await _azureCosmos.FindByDict<HomeworkRecord>(new Dictionary<string, object> { { "code", request.studentId }, { "id", request.homeWorkId } });
    //        HomeworkRecord data = new HomeworkRecord();
    //        if (homeWorkStudents.IsNotEmpty())
    //        {

    //            homeWorkStudents[0].score = request.score ?? homeWorkStudents[0].score;
    //            HomeWorkComment homeWorkComment = new HomeWorkComment
    //            {
    //                comment = request.comments,
    //                createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
    //                TEAMModelId = request.TEAMModelId
    //            };

    //            homeWorkStudents[0].tchCmt = homeWorkComment;
    //            data = await _azureCosmos.SaveOrUpdate(homeWorkStudents[0]);
    //        }
    //        //return builder.Data(data).build();
    //        return Ok(data);
    //    }



    //    /// <summary>
    //    /// 学生作业打分评论
    //    /// </summary>
    //    /// <param name="request"></param>
    //    /// <returns></returns>
    //    [ProducesDefaultResponseType]
    //    [HttpPost("stu-score")]
    //    public async Task<IActionResult> StuScore(HomeworkCommentDto request)
    //    {
    //        ResponseBuilder builder = ResponseBuilder.custom();
    //        List<HomeworkRecord> homeWorkStudents = await _azureCosmos.FindByDict<HomeworkRecord>(new Dictionary<string, object> { { "code", request.studentId }, { "id", request.homeWorkId } });
    //        List<Homework> homeWorks = await _azureCosmos.FindByDict<Homework>(new Dictionary<string, object> { { "id", request.homeWorkId } });
    //        HomeworkRecord data = new HomeworkRecord();
    //        if (homeWorks.IsNotEmpty() && homeWorks[0].other.Contains("comment"))
    //        {
    //            if (homeWorkStudents.IsNotEmpty())
    //            {
    //                if (string.IsNullOrEmpty(request.commentid))
    //                {
    //                    //评论
    //                    StudentComment homeWorkComment = new StudentComment
    //                    {
    //                        commentid = _snowflakeId.NextId() + "",
    //                        comment = request.comment,
    //                        createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
    //                        fromId = request.fromId,
    //                        score = request.score
    //                    };


    //                    homeWorkStudents[0].stuCmt.Add(homeWorkComment);
    //                }
    //                else
    //                {
    //                    //回复评论
    //                    foreach (StudentComment comment in homeWorkStudents[0].stuCmt)
    //                    {
    //                        if (comment.commentid == request.commentid)
    //                        {
    //                            Reply reply = new Reply();
    //                            reply.fromId = request.fromId;
    //                            reply.toId = request.toId;
    //                            reply.identity = request.identity;
    //                            reply.comment = request.comment;
    //                            reply.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
    //                            comment.reply.Add(reply);
    //                        }
    //                    }
    //                }
    //                data = await _azureCosmos.Update(homeWorkStudents[0]);
    //            }
    //            //return builder.Data(data).build();
    //            return Ok(data);
    //        }
    //        else {
    //            //return builder.Error(ResponseCode.FAILED, "未开放互评！").build();
    //            return Ok("未开放互评！");
    //        } 
    //    }
    }
}