using Azure.Cosmos;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using TEAMModelOS.Filter;
using TEAMModelOS.Models;
using TEAMModelOS.SDK.DI;
using TEAMModelOS.SDK.Models;

namespace TEAMModelOS.Controllers.Common
{
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    //[Authorize(Roles = "IES5")
    [Route("common")]
    [ApiController]
    public class CommonController : ControllerBase
    {
        private readonly AzureCosmosFactory _azureCosmos;
        private readonly SnowflakeId _snowflakeId;
        private readonly AzureServiceBusFactory _serviceBus;
        private readonly DingDing _dingDing;
        private readonly Option _option;
        private readonly AzureStorageFactory _azureStorage;
        private readonly IHttpClientFactory _clientFactory;
        public CommonController(AzureCosmosFactory azureCosmos, AzureServiceBusFactory serviceBus, SnowflakeId snowflakeId, DingDing dingDing, IOptionsSnapshot<Option> option, AzureStorageFactory azureStorage, IHttpClientFactory clientFactory)
        {
            _azureCosmos = azureCosmos;
            _serviceBus = serviceBus;
            _snowflakeId = snowflakeId;
            _dingDing = dingDing;
            _option = option?.Value;
            _azureStorage = azureStorage;
            _clientFactory = clientFactory;
        }

        //立即结束某个活动
        [ProducesDefaultResponseType]
        [AuthToken(Roles = "teacher,admin")]
        [HttpPost("finish")]
        public async Task<IActionResult> finish(JsonElement element)
        {
            //var (id, school) = HttpContext.GetAuthTokenInfo();
            try
            {
                if (!element.TryGetProperty("id", out JsonElement id)) return BadRequest();
                if (!element.TryGetProperty("code", out JsonElement code)) return BadRequest();
                var client = _azureCosmos.GetCosmosClient();
                var data = await client.GetContainer("TEAMModelOS", "Common").ReadItemStreamAsync($"{id}", new Azure.Cosmos.PartitionKey($"{code}"));
                using var json = await JsonDocument.ParseAsync(data.ContentStream);
                long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                Dictionary<string, object> dy = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object>>(json.RootElement.ToString());
                dy["endTime"] = now;
                dy["progress"] = "finish";
                await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync<Dictionary<string, object>>(dy, dy["id"].ToString(), new Azure.Cosmos.PartitionKey(dy["code"].ToString()));
                var httpClient = _clientFactory.CreateClient();
                var content = new { id = $"{id}", code = $"{code}" };
                var response = await httpClient.PostAsJsonAsync($"{_option.HttpTrigger }refresh-stu-activity", content);
                return Ok(await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync()));
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，common/finish\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }
        }

        //更新评测活动size
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "teacher,admin")]
        [HttpPost("exam-size")]
        public async Task<IActionResult> examSize(JsonElement element)
        {
            //var (id, school) = HttpContext.GetAuthTokenInfo();
            try
            {
                //if (!element.TryGetProperty("id", out JsonElement id)) return BadRequest();
                if (!element.TryGetProperty("code", out JsonElement code)) return BadRequest();
                var client = _azureCosmos.GetCosmosClient();
                List<ExamInfo> examInfo = new();
                List<Task<ItemResponse<ExamInfo>>> tasks = new();
                await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamInfo>(queryText: $"select value(c) from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Exam-{code}") }))
                {
                    examInfo.Add(item);
                }
                foreach (ExamInfo info in examInfo)
                {
                    if (info.size == 0)
                    {
                        info.size = await _azureStorage.GetBlobContainerClient(info.school).GetBlobsSize($"exam/{info.id}");
                        tasks.Add(client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(info, info.id, new PartitionKey($"{info.code}")));
                    }
                }
                await Task.WhenAll(tasks);
                return Ok();
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，common/exam-size\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }
        }
        //更新投票活动size
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "teacher,admin")]
        [HttpPost("vote-size")]
        public async Task<IActionResult> voteSize(JsonElement element)
        {
            //var (id, school) = HttpContext.GetAuthTokenInfo();
            try
            {
                //if (!element.TryGetProperty("id", out JsonElement id)) return BadRequest();
                if (!element.TryGetProperty("code", out JsonElement code)) return BadRequest();
                var client = _azureCosmos.GetCosmosClient();
                List<Vote> votes = new();
                List<Task<ItemResponse<Vote>>> tasks = new();
                await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<Vote>(queryText: $"select value(c) from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Vote-{code}") }))
                {
                    votes.Add(item);
                }
                foreach (Vote vote in votes)
                {
                    if (vote.size == 0)
                    {
                        vote.size = await _azureStorage.GetBlobContainerClient(vote.school).GetBlobsSize($"vote/{vote.id}");
                        tasks.Add(client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(vote, vote.id, new PartitionKey($"{vote.code}")));
                    }
                }
                await Task.WhenAll(tasks);
                return Ok();
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，common/vote-size\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }
        }

        //更新问卷活动size
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "teacher,admin")]
        [HttpPost("survey-size")]
        public async Task<IActionResult> surveySize(JsonElement element)
        {
            try
            {
                //if (!element.TryGetProperty("id", out JsonElement id)) return BadRequest();
                if (!element.TryGetProperty("code", out JsonElement code)) return BadRequest();
                var client = _azureCosmos.GetCosmosClient();
                List<Survey> surveys = new();
                List<Task<ItemResponse<Survey>>> tasks = new();
                await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<Survey>(queryText: $"select value(c) from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Survey-{code}") }))
                {
                    surveys.Add(item);
                }
                foreach (Survey survey in surveys)
                {
                    if (survey.size == 0)
                    {
                        survey.size = await _azureStorage.GetBlobContainerClient(survey.school).GetBlobsSize($"vote/{survey.id}");
                        tasks.Add(client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(survey, survey.id, new PartitionKey($"{survey.code}")));
                    }
                }
                await Task.WhenAll(tasks);
                return Ok();
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，common/survey-size\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }
        }


        //更新试题库size
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "teacher,admin")]
        [HttpPost("item-size")]
        public async Task<IActionResult> itemSize(JsonElement element)
        {
            try
            {
                //if (!element.TryGetProperty("id", out JsonElement id)) return BadRequest();
                if (!element.TryGetProperty("code", out JsonElement code)) return BadRequest();
                var client = _azureCosmos.GetCosmosClient();
                List<ItemInfo> items = new();
                List<Task<ItemResponse<ItemInfo>>> tasks = new();
                await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<ItemInfo>(queryText: $"select value(c) from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{code}") }))
                {
                    items.Add(item);
                }
                foreach (ItemInfo info in items)
                {
                    if (info.size == 0)
                    {
                        info.size = await _azureStorage.GetBlobContainerClient(code.ToString()).GetBlobsSize($"item/{info.id}");
                        tasks.Add(client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync(info, info.id, new PartitionKey($"{info.code}")));
                    }
                }
                await Task.WhenAll(tasks);
                return Ok();
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，common/item-size\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }
        }

        //更新试卷库size
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "teacher,admin")]
        [HttpPost("paper-size")]
        public async Task<IActionResult> paperSize(JsonElement element)
        {
            try
            {
                //if (!element.TryGetProperty("id", out JsonElement id)) return BadRequest();
                if (!element.TryGetProperty("code", out JsonElement code)) return BadRequest();
                var client = _azureCosmos.GetCosmosClient();
                List<Paper> papers = new();
                List<Task<ItemResponse<Paper>>> tasks = new();
                await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<Paper>(queryText: $"select value(c) from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Paper-{code}") }))
                {
                    papers.Add(item);
                }
                foreach (Paper paper in papers)
                {
                    if (paper.size == 0)
                    {
                        paper.size = await _azureStorage.GetBlobContainerClient(code.ToString()).GetBlobsSize($"paper/{paper.name}");
                        tasks.Add(client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync(paper, paper.id, new PartitionKey($"{paper.code}")));
                    }
                }
                await Task.WhenAll(tasks);
                return Ok();
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"OS，{_option.Location}，common/paper-size\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }
        }
    }
}
