using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using TEAMModelOS.SDK.DI;

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

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

//        /// <summary>
//        /// 保存或更新学习任务
//        /// </summary>
//        /// <param name="request"></param>
//        /// <returns></returns>
//        [ProducesDefaultResponseType]
//        [HttpPost("upsert-task")]
//        public async Task<IActionResult> UpsertTask(LearnTask request)
//        {
//            /*//if (!requert.TryGetProperty("id_token", out JsonElement id_token)) return BadRequest();
//            if (!requert.TryGetProperty("id", out JsonElement id)) 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 client = _azureCosmos.GetCosmosClient();
//            var response = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync(id.ToString(), new PartitionKey($"LearnTask-{id}"));
//            if (response.Status == 200)
//            {
//                using var json = await JsonDocument.ParseAsync(response.ContentStream);
              
//            }
//            else
//            {
//                //如果沒有，則初始化LearnTask
//                requert.TryGetProperty("endTime", out JsonElement endTime);
//                requert.TryGetProperty("status", out JsonElement status);
//                requert.TryGetProperty("type", out JsonElement type);
//                requert.TryGetInt64(out long createTime);
//                requert.TryGetProperty("stage", out JsonElement stage);
//                requert.TryGetProperty("passScore", out JsonElement passScore);

//                if (createTime <= 0)
//                {
//                    createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
//                }

//                if (endTime.GetInt64() > 0)
//                {
//                    //设定结束时间
//                    string msgEndId = _snowflakeId.NextId() + "";
//                    await _serviceBus.GetServiceBusClient().SendLeamMessage<LearnTask>(Constants.TopicName, id, $"LearnTask-{id}", endTime.GetInt64(), 300, msgEndId);
//                }

//                using var stream = new MemoryStream();
//                using var writer = new Utf8JsonWriter(stream); //new JsonWriterOptions() { Indented = true }
//                writer.WriteStartObject();
//                writer.WriteString("code", $"LearnTask-{id}");
//                writer.WriteString("id", id.ToString());
//                writer.WriteNumber("endTime", endTime.GetInt64());
//                writer.WriteNumber("status", status.GetInt32());
//                writer.WriteNumber("type", type.GetInt32());
//                writer.WriteNumber("stage", stage.GetInt32());
//                writer.WriteNumber("createTime", createTime);
//                writer.WriteNumber("passScore", passScore.GetInt32());
//                writer.WriteEndObject();
//                writer.Flush();
//                //Debug
//                //string teacher = Encoding.UTF8.GetString(stream.ToArray());
//                response = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher").CreateItemStreamAsync(stream, new PartitionKey($"LearnTask-{id}"));
//            }*/
//            var client = _azureCosmos.GetCosmosClient();
//            LearnTask learnTask;            
//            request.pk = typeof(LearnTask).Name;
//            if (string.IsNullOrEmpty(request.id))
//            {
//                request.id = _snowflakeId.NextId() + "";
//                request.code = typeof(LearnTask).Name + "-" + request.code;
//                request.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
//                learnTask = await client.GetContainer("TEAMModelOS", "Teacher").CreateItemAsync(request, new PartitionKey($"{request.code}"));
//                //await _azureCosmos.Save(request);
//            }
//            else
//            {
//                learnTask = await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync(request, request.id, new PartitionKey($"{request.code}"));
//                //await _azureCosmos.Update(request);
//            }

//            return Ok(new { learnTask });

//            /* ResponseBuilder builder = ResponseBuilder.custom();
//             if (request.createTime <= 0) {
//                 request.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
//             }

//             if (request.endTime > 0) {
//                 //设定结束时间
//                 string msgEndId = _snowflakeId.NextId()+"";
//                 await _serviceBus.GetServiceBusClient().SendLeamMessage<LearnTask>(Constants.TopicName, request.id, request.code, request.endTime, 300, msgEndId);
//             }
//             await _azureCosmos.Save(request);
//             return builder.Data(request).build();*/
//        }

//        /// <summary>
//        /// 查询学习任务
//        /// </summary>
//        /// <param name="request"></param>
//        /// <returns></returns>
//        [ProducesDefaultResponseType]
//        [HttpPost("find-task")]
//        public async Task<IActionResult> FindTask(JsonElement requert)
//        {

//            var client = _azureCosmos.GetCosmosClient();
//            if (!requert.TryGetProperty("id", out JsonElement id)) 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> tasks = new List<object>();
//            var query = $"select c.id,c.endTime,c.status, c.type,c.createTime,c.stage,c.passScore from c";
//            await foreach (var item in client.GetContainer("TEAMModelOS", "Student").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LearnTask-{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())
//                    {
//                        tasks.Add(obj.ToObject<object>());
//                    }
//                }
//            }

//            return Ok(new { tasks });
//            /*ResponseBuilder builder = ResponseBuilder.custom();
//            if (request.TryGetProperty("id",out _) || request.TryGetProperty("code",out _))
//            {
//                List<LearnTask> tasks = await _azureCosmos.FindByDict<LearnTask>(request);
//                return builder.Data(tasks).build();
//            }
//            else {
//                return builder.Error(ResponseCode.PARAMS_ERROR, "参数异常！").build(); 
//            }*/

//        }
//        /// <summary>
//        /// 删除学习任务
//        /// </summary>
//        /// <param name="request"></param>
//        /// <returns></returns>
//        [ProducesDefaultResponseType]
//        [HttpPost("delete-task")]
//        public async Task<IActionResult> DeleteTask(IdPk request)
//        {
//            ResponseBuilder builder = ResponseBuilder.custom();
//            return Ok(await _azureCosmos.DeleteAsync<LearnTask>(request));
//        }

//        /// <summary>
//        /// 保存或更新学习单元单元
//        /// </summary>
//        /// <param name="request"></param>
//        /// <returns></returns>
//        [ProducesDefaultResponseType]
//        [HttpPost("upsert-unit")]
//        public async Task<IActionResult> UpsertUnit(LearnUnit request)
//        {

//            var client = _azureCosmos.GetCosmosClient();
//            LearnUnit learnUnit;            
//            request.pk = typeof(LearnUnit).Name;
//            if (string.IsNullOrEmpty(request.id))
//            {
//                request.id = _snowflakeId.NextId() + "";               
//                request.code = typeof(LearnUnit).Name + "-" + request.code;
//                request.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
//                learnUnit = await client.GetContainer("TEAMModelOS", "Teacher").CreateItemAsync(request, new PartitionKey($"{request.code}"));
//                //await _azureCosmos.Save(request);
//            }
//            else
//            {
//                request.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
//                learnUnit = await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync(request, request.id, new PartitionKey($"{request.code}"));
//                //await _azureCosmos.Update(request);
//            }

//            return Ok(new { learnUnit });
//            /*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 client = _azureCosmos.GetCosmosClient();
//            var response = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync(id, new PartitionKey($"LearnUnit-{id}"));
//            if (response.Status == 200)
//            {
//                using var json = await JsonDocument.ParseAsync(response.ContentStream);

//            }
//            else
//            {
//                //如果沒有，則初始化LearnTask
//                requert.TryGetProperty("endTime", out JsonElement endTime);
//                requert.TryGetProperty("status", out JsonElement status);
//                requert.TryGetProperty("type", out JsonElement type);
//                //requert.TryGetInt64(out long createTime);
//                requert.TryGetProperty("stage", out JsonElement stage);
//                requert.TryGetProperty("passScore", out JsonElement passScore);
//                long createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
//                using var stream = new MemoryStream();
//                using var writer = new Utf8JsonWriter(stream); //new JsonWriterOptions() { Indented = true }
//                writer.WriteStartObject();
//                writer.WriteString("code", $"LearnUnit-{id}");
//                writer.WriteString("id", id);
//                writer.WriteNumber("endTime", endTime.GetInt64());
//                writer.WriteNumber("status", status.GetInt32());
//                writer.WriteNumber("type", type.GetInt32());
//                writer.WriteNumber("stage", stage.GetInt32());
//                writer.WriteNumber("createTime", createTime);
//                writer.WriteNumber("passScore", passScore.GetInt32());
//                writer.WriteEndObject();
//                writer.Flush();
//                //Debug
//                //string teacher = Encoding.UTF8.GetString(stream.ToArray());
//                response = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Teacher").CreateItemStreamAsync(stream, new PartitionKey($"LearnUnit-{id}"));
//            }

//            return Ok();*/
//            /*ResponseBuilder builder = ResponseBuilder.custom();
//            if (string.IsNullOrEmpty(request.id))
//            {
//                request.id = _snowflakeId.NextId() + "";
//                request.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
//                await _azureCosmos.Save(request);
//            }
//            else
//            {
//                await _azureCosmos.Update(request);
//            }
//            return builder.Data(request).build();*/
//        }



//        /// <summary>
//        /// 查询学习单元
//        /// </summary>
//        /// <param name="request"></param>
//        /// <returns></returns>
//        [ProducesDefaultResponseType]
//        [HttpPost("find-unit")]
//        public async Task<IActionResult> FindUnit(JsonElement requert)
//        {

//            var client = _azureCosmos.GetCosmosClient();
//            if (!requert.TryGetProperty("code", out JsonElement 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> units = new List<object>();
//            var query = $"select c.id,c.resource,c.item, c.name,c.createTime from c";
//            await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LearnUnit-{code}") }))
//            {
//                using var json = await JsonDocument.ParseAsync(item.ContentStream);

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

//            return Ok(new { units });

//            /*ResponseBuilder builder = ResponseBuilder.custom();

//            if (StringHelper.getKeyCount(request) > 0)
//            {
//                return builder.Data(await _azureCosmos.FindByDict<LearnUnit>(request)).build();
//            }
//            else {
//                return builder.build();
//            }*/

//        }
//        /// <summary>
//        /// 删除学习单元
//        /// </summary>
//        /// <param name="request"></param>
//        /// <returns></returns>
//        [ProducesDefaultResponseType]
//        [HttpPost("delete-unit")]
//        public async Task<IActionResult> DeleteUnit(IdPk request)
//        {
//            ResponseBuilder builder = ResponseBuilder.custom();
//            return Ok(await _azureCosmos.DeleteAsync<LearnUnit>(request));
//        }

//        /// <summary>
//        /// 保存或新增编序学习活动
//        /// </summary>
//        /// <param name="request"></param>
//        /// <returns></returns>
//        [ProducesDefaultResponseType]
//        [HttpPost("upsert-process")]
//        public async Task<IActionResult> UpsertProcess(LearnProcess request) {
//            //ResponseBuilder builder = ResponseBuilder.custom();
//            var client = _azureCosmos.GetCosmosClient();
//            LearnProcess learnProcess;            
//            request.pk = typeof(LearnProcess).Name;
//            if (string.IsNullOrEmpty(request.id))
//            {
//                request.id = _snowflakeId.NextId() + "";
//                request.code = typeof(LearnProcess).Name + "-" + request.code;
//                request.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
//                learnProcess = await client.GetContainer("TEAMModelOS", "Teacher").CreateItemAsync(request, new PartitionKey($"LearnProcess-{request.code}"));
//               // await _azureCosmos.Save<LearnProcess>(request);
//            }
//            else {
//                learnProcess = await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync(request, request.id,new PartitionKey($"{request.code}"));
//                //await _azureCosmos.Update<LearnProcess>(request);
//            }
           
//            return Ok(new { learnProcess });
//        }

//        /// <summary>
//        /// 查询编序学习活动
//        /// </summary>
//        /// <param name="request"></param>
//        /// <returns></returns>
//        [ProducesDefaultResponseType]
//        [HttpPost("find-process")]
//        public async Task<IActionResult> FindProcess(JsonElement requert)
//        {

//            var client = _azureCosmos.GetCosmosClient();
//            if (!requert.TryGetProperty("id", out JsonElement id)) 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> process = new List<object>();
//            var query = $"select c.id,c.name,c.subjectCode, c.periodCode,c.Introduce from c where id = {id}";
//            await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LearnProcess-{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())
//                    {
//                        process.Add(obj.ToObject<object>());
//                    }
//                }
//            }

//            return Ok(new { process });
//            /* ResponseBuilder builder = ResponseBuilder.custom();

//            if (StringHelper.getKeyCount(request) > 0) {

//                builder.Data(await _azureCosmos.FindByDict<LearnProcess>(request));
//            }

//            return builder.build();*/
//        }

//        /// <summary>
//        /// 删除编序学习活动
//        /// </summary>
//        /// <param name="request"></param>
//        /// <returns></returns>
//        [ProducesDefaultResponseType]
//        [HttpPost("delete-process")]
//        public async Task<IActionResult> DeleteProcess(IdPk request)
//        {
//            //ResponseBuilder builder = ResponseBuilder.custom();
//            if (request != null)
//            {
//                await _azureCosmos.DeleteAsync<LearnProcess>(request);
//            }
//            return Ok(request);
//        }

//        /// <summary>
//        /// 保存或新增作答记录
//        /// </summary>
//        /// <param name="request"></param>
//        /// <returns></returns>
//        [ProducesDefaultResponseType]
//        [HttpPost("upsert-record")]
//        public async Task<IActionResult> UpsertRecord(List<LearnRecord> request)
//        {
//            //ResponseBuilder builder = ResponseBuilder.custom();
//            List<LearnRecord> leanProcesses = null;
//            if (ValidateHelper.IsValid(request))
//            {
//                request.ForEach(c => {
//                    if (string.IsNullOrEmpty(c.id)) {
//                        c.code = typeof(LearnRecord).Name + "-" + c.code;
//                    }
//                });
//                leanProcesses = await _azureCosmos.SaveOrUpdateAll<LearnRecord>(request);
//                //builder.Data(leanProcesses);
//            }
//            return Ok(leanProcesses);
//        }

//        /// <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("id", out JsonElement id)) 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.steps from c where id = {id}";
//            await foreach (var item in client.GetContainer("TEAMModelOS", "Student").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LearnRecord-{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();
//            if (StringHelper.getKeyCount(request) > 0)
//            {
//                builder.Data(await _azureCosmos.FindByDict<LearnRecord>(request));
//            }
//            return builder.build();*/
//        }


//        /// <summary>
//        /// 删除作答记录
//        /// </summary>
//        /// <param name="request"></param>
//        /// <returns></returns>
//        [ProducesDefaultResponseType]
//        [HttpPost("delete-record")]
//        public async Task<IActionResult> DeleteRecord(IdPk request)
//        {
//            //ResponseBuilder builder = ResponseBuilder.custom();
//            if (request != null)
//            {
//               await _azureCosmos.DeleteAsync<LearnRecord>(request);
//            }
//            return Ok(request);
//        }
    }
}
