using Azure.Cosmos;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Text;
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.DI.AzureCosmos.Inner;
using TEAMModelOS.SDK.Extension;
using TEAMModelOS.SDK.Helper.Common.CollectionHelper;
using TEAMModelOS.SDK.Helper.Common.StringHelper;
using TEAMModelOS.Models;
using Microsoft.Extensions.Options;
using TEAMModelOS.SDK.Models.Cosmos;
using Microsoft.AspNetCore.Authorization;
using TEAMModelOS.Filter;
using StackExchange.Redis;
using TEAMModelOS.SDK.Models.Cosmos.Common.Inner;
using TEAMModelOS.Services.Common;
namespace TEAMModelOS.Controllers
{
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    //[Authorize(Roles = "IES5")]
    [Route("school/correct")]
    [ApiController]
    public class CorrectController : ControllerBase
    {
        private readonly AzureRedisFactory _azureRedis;
        private readonly AzureCosmosFactory _azureCosmos;
        private readonly SnowflakeId _snowflakeId;
        private readonly AzureServiceBusFactory _serviceBus;
        private readonly DingDing _dingDing;
        private readonly Option _option;
        private readonly AzureStorageFactory _azureStorage;

        public CorrectController(AzureCosmosFactory azureCosmos, AzureServiceBusFactory serviceBus, SnowflakeId snowflakeId, DingDing dingDing, IOptionsSnapshot<Option> option,
            AzureRedisFactory azureRedis, AzureStorageFactory azureStorage)
        {
            _azureCosmos = azureCosmos;
            _serviceBus = serviceBus;
            _snowflakeId = snowflakeId;
            _dingDing = dingDing;
            _option = option?.Value;
            _azureRedis = azureRedis;
            _azureStorage = azureStorage;
        }

        ///<summary>
        ///查询教师的阅卷任务列表
        /// </summary>
        /// <data>
        ///    ! "code":"tmdid"
        /// </data>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [HttpPost("find-task")]
        public async Task<IActionResult> FindTask(JsonElement requert) {
            List<CorrectTask> tasks = new List<CorrectTask>();
            try
            {
                var client = _azureCosmos.GetCosmosClient();
                
                //活动分区
                if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
                await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<CorrectTask>(queryText: $"select value(c) from c ",
                requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"CorrectTask-{code}") }))
                {
                    tasks.Add(item);
                }
                return Ok(new { tasks = tasks });
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，common/Correct/find-task()\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
                return Ok(new { tasks = tasks });
            }
        }
        /*
        {
            "id":"uuid",//新增为null或者空
            "code":"hbcn",
            "owner":"school",
            "name":"xxx评测-阅卷",
            "creatorId":"1558635535",
            "progress":"pending 待发布|going 已发布|finish 已结束",
            "scope":"school",
            "startTime":158556666658,//评测结束的时间
            "createTime":158556666658,//当前时间
            "endTime":158556666658,//指定一个结束时间
            "examType":"评测活动的类型",
            "scode":"评测的源数据code值",
            "mode":"阅卷模式,1 按题目，0 按人/学生",
            "corSubs":[//科目的设置
                {
                    "id":"科目id",
                    "corTmdids":[//设置的醍摩豆账号
                        {
                            "tmdid":"1558635535,评卷教师的id",
                            "corCount":100
                        },
                    
                    ]
                }    
            ]
        }
         */
        /// <summary>
        /// 新增 或 修改阅卷设置
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [HttpPost("upsert")]
        public async Task<IActionResult> Upsert(Correct request)
        {
            try
            {
                //新增阅卷活动设置
                var client = _azureCosmos.GetCosmosClient();
                request.pk = $"Correct";
                request.code = $"Correct-{request.code}" ;
                request.ttl = -1;
                long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                request.createTime = now;
                //如果设置的时间是小于当前时间则立即发布
                if (request.startTime <= 0)
                {
                    request.startTime = now;
                }
                if (string.IsNullOrEmpty(request.id))
                {

                    request.id = Guid.NewGuid().ToString();
                    if (request.startTime > now)
                    {
                        request.progress = "pending";
                    }
                    else
                    {
                        request.progress = "going";
                    }
                    request = await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(request, new PartitionKey($"{request.code}"));
                }
                else
                {
                    var response = await client.GetContainer("TEAMModelOS", "Common").ReadItemStreamAsync(request.id, new PartitionKey($"{request.code}"));
                    if (response.Status == 200)
                    {
                        using var json = await JsonDocument.ParseAsync(response.ContentStream);
                        var info = json.ToObject<Correct>();
                        if (info.progress.Equals("going"))
                        {
                            return Ok(new { v = "活动正在进行中" });
                        }
                        if (request.startTime > now)
                        {
                            request.progress = "pending";
                        }
                        else
                        {
                            request.progress = "going";
                        }
                        request.progress = info.progress;
                        request = await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(request, info.id, new PartitionKey($"{info.code}"));
                    }
                    else
                    {
                        if (request.startTime > now)
                        {
                            request.progress = "pending";
                        }
                        else
                        {
                            request.progress = "going";
                        }
                        request = await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(request, new PartitionKey($"{request.code}"));
                    }
                }
                return Ok(new { vote = request });
            }
            catch (Exception e)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，common/Correct/upsert()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
                return BadRequest(e.StackTrace);
            }
        }
        ///<summary>
        ///
        /// </summary>
        /// <data>
        ///    ! "id":"3c075347-75ef-4bcb-ae03-68678d02d5ef", //评测id
        ///    ! "code":"hbcn"//
        /// </data>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [HttpPost("find-id")]
        public async Task<IActionResult> FindById(JsonElement requert)
        {
            try
            {
                var client = _azureCosmos.GetCosmosClient();
                //活动id
                if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
                //活动分区
                if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
                Correct correct = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<Correct>(id.GetString(), new PartitionKey($"Correct-{code}"));
                if (correct != null)
                {
                    return Ok(new { correct });
                }
                else
                {
                    correct = null;
                    return Ok(new { correct = correct }) ;
                }
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，common/Correct/find-id()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
                Correct correct = null;
                return Ok(new { correct = correct });
            }

        }
    }
}
