using Azure.Cosmos;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using TEAMModelOS.Filter;
using TEAMModelOS.SDK.DI;
using TEAMModelOS.SDK.Extension;
using TEAMModelOS.SDK.Models.Cosmos;
using TEAMModelOS.SDK.Models.Cosmos.Common;
using TEAMModelOS.Services.Common;

namespace TEAMModelOS.Controllers
{
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    //[Authorize(Roles = "IES5")]
    [Route("student")]
    [ApiController]
    public class StudentCommonController :ControllerBase
    {
        private readonly AzureCosmosFactory _azureCosmos;
        private readonly AzureRedisFactory _azureRedis;
        public StudentCommonController(AzureCosmosFactory azureCosmos, AzureRedisFactory azureRedis)
        {
           
            _azureCosmos = azureCosmos;
            _azureRedis = azureRedis;
        }

        /// <summary>
        /// 查询活动所有活动类型的列表，学生端
        /// </summary>
        /// <param name="request">
        ///加入的班级信息                      ?classes:[{"classid":"S-C-00001","scope":"school"},{"classid":"P-C-00004","scope":"private"}]
        ///活动类型                            ?"type":"Vote"/"Exam"/"Homework"/"Learn"/"Survey"" // Vote投票 Survey问卷 Exam评测 Learn学习活动 Homework作业活动
        ///时间筛选范围开始时间 默认30天之前   ?"stime":1608274766154  
        ///时间筛选范围结束时间 默认当前时间   ?"etime":1608274766666 
        ///是否展示列表的 Tips                 ? "tips":true/false
        ///每页大小     ?"count":10/null/Undefined  
        ///分页Token    ?"continuationToken":Undefined/null/"[{\"token\":\"+RID:~omxMAP3ipcSEEwAAAAAAAA==#RT:2#TRC:20#ISV:2#IEO:65551#QCF:1#FPC:AYQTAAAAAAAAiRMAAAAAAAA=\",\"range\":{\"min\":\"\",\"max\":\"FF\"}}]"
        /// 当前状态    ?"progress":Undefined/null/"" 表示两种状态都要查询/ "going"/"finish" 表示查询进行中/ 或者已完成 学生端只能查询正在进行或已经结束 going 已发布|finish 已结束  
        /// </param>
        /// 
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [HttpPost("stu-activity")]
        // [AuthToken(Roles = "student")]
        public async Task<IActionResult> StuActivity(JsonElement request)
        {
            var (id, name, pic, school) = HttpContext.GetAuthTokenInfo();
            (List<StuActivity> datas, string continuationToken) = await ActivityStudentService.FindActivity(request, id, school, _azureCosmos, _azureRedis);
            return Ok(new { datas, continuationToken });
        }
        /// <summary>
        /// 查询活动所有活动类型的列表，学生端
        /// </summary>
        /// <param name="request">
        /// userid
        /// school
        /// </param>
        /// 
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [HttpPost("stu-course")]
        // [AuthToken(Roles = "student")]
        public async Task<IActionResult> StuCourse(JsonElement request)
        {
            var (id, name, pic, school) = HttpContext.GetAuthTokenInfo();
            if (string.IsNullOrWhiteSpace(id))
            {
                if (request.TryGetProperty("userid", out JsonElement userid))
                {
                    if (!userid.ValueKind.Equals(JsonValueKind.Undefined) && !userid.ValueKind.Equals(JsonValueKind.Null) && userid.ValueKind.Equals(JsonValueKind.String))
                    {
                        id = userid.GetString();
                    }
                }
            }
            if (string.IsNullOrWhiteSpace(school))
            {
                if (request.TryGetProperty("school", out JsonElement schooljson)) {
                    if (!schooljson.ValueKind.Equals(JsonValueKind.Undefined) && !schooljson.ValueKind.Equals(JsonValueKind.Null) && schooljson.ValueKind.Equals(JsonValueKind.String))
                    {
                        school = schooljson.GetString();
                    }
                }
               
            }
            string containerId = "Teacher";
            string PartitionKey = $"StuCourse-{id}";
            if (!string.IsNullOrEmpty(school)) {
                  containerId = "Student";
                  PartitionKey = $"StuCourse-{school}-{id}";
            }
            List<StuCourse> stus = new List<StuCourse>();
            await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", containerId).GetItemQueryIterator<StuCourse>(queryText: $"select value(c) from c ",
              requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey(PartitionKey) }))
            {
                stus.Add(item);
            }
            return Ok(new { course=stus });
        }
    }
}
