using Azure.Cosmos;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using TEAMModelOS.SDK.DI;
using TEAMModelOS.SDK.Extension;
using TEAMModelOS.SDK.Helper.Common.CollectionHelper;
using TEAMModelOS.SDK.Models;
using TEAMModelOS.SDK.Models.Cosmos.Common;

namespace TEAMModelOS.Controllers.XTest
{
    [Route("test")]
    [ApiController]
    public class TestController :ControllerBase
    {
        private readonly AzureStorageFactory _azureStorage;
        private readonly AzureRedisFactory _azureRedis;
        private readonly AzureCosmosFactory _azureCosmos;
        private readonly DingDing _dingDing;

        public TestController(AzureCosmosFactory azureCosmos, AzureRedisFactory azureRedis, AzureStorageFactory azureStorage, DingDing dingDing) {
            _azureCosmos = azureCosmos;
            _azureRedis = azureRedis;
            _azureStorage = azureStorage;
            _dingDing = dingDing;
        }
        /// <summary>
        /// 测试blob多线程写入同一个文件
        /// </summary>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [HttpPost("blobroot")]
        public async Task<IActionResult> MultipleBlob(JsonElement jsonMsg) {
            if (jsonMsg.TryGetProperty("name", out JsonElement name) && name.ValueKind == JsonValueKind.String
                    && jsonMsg.TryGetProperty("root", out JsonElement root) && root.ValueKind == JsonValueKind.String)
            {
                List<Dictionary<string, double?>> list = new List<Dictionary<string, double?>>();
                string u = System.Web.HttpUtility.UrlDecode($"{root}", Encoding.UTF8).Split("/")[0];
                var client = _azureStorage.GetBlobContainerClient($"{name}");
                var size = await client.GetBlobsSize(u);
                await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{name}", u);
                await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{name}", u, size.HasValue ? size.Value : 0);
                var scores = await _azureRedis.GetRedisClient(8).SortedSetRangeByRankWithScoresAsync($"Blob:Catalog:{name}");
                double blobsize = 0;
                if (scores != default && scores != null)
                {
                    foreach (var score in scores)
                    {
                        blobsize = blobsize + score.Score;
                        list.Add(new Dictionary<string, double?>() { { score.Element.ToString(), score.Score } });
                    }
                }
                await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", new RedisValue($"{name}"), new RedisValue($"{blobsize}"));

                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,Blob() 容器:{name}使用:{root}，文件分类：{list.ToJsonString()}",
                    GroupNames.成都开发測試群組);
                return Ok(list);
            }
            else {
                return Ok();
            }
            
        }


        /// <summary>
        /// 测试redis通配符
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        [HttpGet("test-redis")]
        public async Task<IActionResult> TestRedis( ) {

           
            var db  = _azureRedis.GetRedisClient(8);

          await  db.StringSetAsync("1111", "111111");
                return Ok() ;
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [ProducesDefaultResponseType]
        //[AuthToken(Roles = "teacher")]
        [HttpPost("delete")]
        public async Task<IActionResult> Delete(JsonElement request)
        {
            try
            {
             
                if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
                if (!request.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
                var client = _azureCosmos.GetCosmosClient();
                List<Task> tasksFiles = new List<Task>();
                var query = $"select c.id from c ";
                if (scope.ToString().Equals("school"))
                {
                    var ids = client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{code}") });
                    await foreach (var id in ids)
                    {
                        using var json = await JsonDocument.ParseAsync(id.ContentStream);
                        var jsonList = json.RootElement.GetProperty("Documents").EnumerateArray();
                        //批量删除
                        foreach (var obj in jsonList)
                        {
                            tasksFiles.Add(client.GetContainer("TEAMModelOS", "School").DeleteItemStreamAsync(obj.GetProperty("id").ToString(), new PartitionKey($"{code}")));
                        }
                    }
                }
                else if (scope.ToString().Equals("teacher")) {
                    var ids = client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{code}") });
                    await foreach (var id in ids)
                    {
                        using var json = await JsonDocument.ParseAsync(id.ContentStream);
                        var jsonList = json.RootElement.GetProperty("Documents").EnumerateArray();
                        //批量删除
                        foreach (var obj in jsonList)
                        {
                            //tasksFiles.Add(client.GetContainer("TEAMModelOS", "Teacher").DeleteItemStreamAsync(obj.GetProperty("id").ToString(), new PartitionKey($"{code}")));
                        }
                    }
                }
                await Task.WhenAll(tasksFiles);
                return Ok(new { code = 1 });
            }
            catch (Exception e)
            {
                return BadRequest(e.StackTrace);
            }
        }
    }
}
