using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using TEAMModelOS.SDK.Context.Configuration;
using TEAMModelOS.SDK;
using TEAMModelOS.SDK.Helper.Common.JsonHelper;
using TEAMModelOS.SDK.Module.AzureBlob.Configuration;
using TEAMModelOS.SDK.DI;
using System.Net.Http;
using TEAMModelOS.SDK.Helper.Security.ShaHash;
using TEAMModelOS.SDK.Extension;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.AspNetCore.Authorization;
using TEAMModelOS.Filter;
using StackExchange.Redis;
using Azure.Messaging.ServiceBus;
using static TEAMModelOS.SDK.DI.AzureStorageBlobExtensions;
using System.Linq;
using Microsoft.AspNetCore.Http;
using HTEXLib.COMM.Helpers;
using TEAMModelOS.Models;
using Microsoft.Extensions.Options;
using TEAMModelOS.SDK.Models;
using Azure.Cosmos;
using Azure;
using System.IO;
using Azure.Storage.Blobs.Models;
using Azure.Storage.Sas;
using ContentTypeDict = TEAMModelOS.SDK.ContentTypeDict;

namespace TEAMModelOS.Controllers.Core
{
    [Route("blob")]
    [ApiController]
    public class BlobController : ControllerBase
    {

        private readonly AzureStorageFactory _azureStorage;
        private readonly IHttpClientFactory _clientFactory;
        private readonly AzureRedisFactory _azureRedis;
        private readonly AzureServiceBusFactory _serviceBus;
        private readonly DingDing _dingDing;
        private readonly Option _option;
        private readonly AzureCosmosFactory _azureCosmos;
        public IConfiguration _configuration { get; set; }
        public BlobController(AzureStorageFactory azureStorage, AzureServiceBusFactory serviceBus, IHttpClientFactory clientFactory, AzureRedisFactory azureRedis, IConfiguration configuration,
            DingDing dingDing,
            IOptionsSnapshot<Option> option, AzureCosmosFactory azureCosmos)
        {
            _azureStorage = azureStorage;
            _clientFactory = clientFactory;
            _serviceBus = serviceBus;
            _azureRedis = azureRedis;
            _configuration = configuration; 
            _dingDing = dingDing;
            _option = option?.Value;
            _azureCosmos = azureCosmos;
        }
        /// <summary>
        /// 上传文件到指定的0-public
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("public-upload")]
        [AuthToken(Roles = "teacher,admin")]
        [RequestSizeLimit(102_400_000_00)] //最大10000m左右
        public async Task<IActionResult> PublicUpload([FromForm] IFormFile file)
        {
            var (id, _, _, school) = HttpContext.GetAuthTokenInfo();
            string fileExt = FileType.GetExtention(file.FileName).ToLower();
            if (ContentTypeDict.dict.ContainsKey($".{fileExt}"))
            {
                var url=  await _azureStorage.UploadFileByContainer("0-public", file.OpenReadStream(), "school", $"{Guid.NewGuid()}.{fileExt}", false);
                return Ok(new { url });
            }
            else {
                return BadRequest();
            }
            
        }
        /// <summary>
        /// 获取某个容器的只读权限
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("sas-r")]
        public IActionResult BlobSasR(BlobSas request)
        {
            ///返回金钥过期时间 
            // Dictionary<string, object> dict = await azureBlobDBRepository.GetBlobSasUri(request.@params,true);
            // dict.Add(d.Key, d.Value);
            return Ok(_azureStorage.GetContainerSasUri(request, true));
        }
        /// <summary>
        /// 某个文件的上传SAS rcw权限
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("sas-rcwld")]
        public IActionResult BlobSasRCW(BlobSas request)
        {
            ///返回金钥过期时间
            // Dictionary<string,object> dict=  await azureBlobDBRepository.GetBlobSasUri(request.@params,false);
            //   Dictionary<string, object> dict = ;
            //dict.Add(d.Key, d.Value);
            return Ok(_azureStorage.GetContainerSasUri(request, false));
        }
        /// <summary>
        /// 链接只读（读）
        /// </summary>
        /// <param name="azureBlobSASDto"></param>
        /// <returns></returns>
        [HttpPost("sas-url-r")]
        public IActionResult GetContainerSASRead(JsonElement azureBlobSASDto)
        {
            azureBlobSASDto.TryGetProperty("url", out JsonElement azureBlobSAS);
            //string azureBlobSAS = azureBlobSASDto;
            (string, string) a = BlobUrlString(azureBlobSAS.ToString());
            string ContainerName = a.Item1;
            string BlobName = a.Item2;
            bool flg = IsBlobName(BlobName);
            if (flg)
            {
                return Ok(_azureStorage.GetBlobSasUriRead(ContainerName, BlobName));
            }
            else
            {
                return BadRequest("文件名错误");
            };
        }     
      

        
        /// <summary>
        /// 获取文件内容
        /// </summary>
        /// <param name="azureBlobSASDto"></param>
        /// <returns></returns>
        [HttpPost("get-text")]
        public async Task<IActionResult> GetText(JsonElement request)
        {
            request.TryGetProperty("code", out JsonElement code); 
            string azureBlobSAS = System.Web.HttpUtility.UrlDecode(code.ToString(), Encoding.UTF8);
            (string, string) a = BlobUrlString(azureBlobSAS);
            string ContainerName = a.Item1;
            string BlobName = a.Item2;
            bool flg = IsBlobName(BlobName);
            if (flg)
            {
                //TODO 需驗證
                BlobAuth blobAuth= _azureStorage.GetBlobSasUriRead(ContainerName, BlobName);
                var  response= await _clientFactory.CreateClient().GetAsync(new Uri(blobAuth.url + blobAuth.sas));
                response.EnsureSuccessStatusCode();
                using var json = await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync());                
                return  Ok(json.RootElement);
            }
            else
            {
                return BadRequest("文件名错误");
            };
        }

        /// <summary>
        ///     {"containerName":"hbcn","scope":"school"}
        /// 获取容器的 分类及总量
        /// </summary>
        /// <param name="azureBlobSASDto"></param>
        /// <returns></returns>
        [HttpPost("used-space")]
        public async Task<ActionResult> UsedSpace(JsonElement request)
        {
            try
            {
                //学校已经分配给所有教师的空间大小GB。
                long teach = 0;
                request.TryGetProperty("scope", out JsonElement _scope);
                request.TryGetProperty("containerName", out JsonElement containerName);
                if (_scope.ValueKind.Equals(JsonValueKind.String) && _scope.GetString().Equals("school")) {
                    var client = _azureCosmos.GetCosmosClient();
                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: $"SELECT sum(c.size) as size FROM c ",
                        requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{containerName}") })) {
                        var json = await JsonDocument.ParseAsync(item.ContentStream);
                        foreach (var elmt in json.RootElement.GetProperty("Documents").EnumerateArray())
                        {
                            if (elmt.TryGetProperty("size", out JsonElement _size) && _size.ValueKind.Equals(JsonValueKind.Number))
                            {
                                teach = _size.GetInt32();
                                break;
                            }
                        }
                    }
                }
                var name =containerName.GetString();
                long blobsize = 0;
                RedisValue value = default;
                value = _azureRedis.GetRedisClient(8).HashGet($"Blob:Record", name);
                if (value != default && !value.IsNullOrEmpty)
                {
                    JsonElement record = value.ToString().ToObject<JsonElement>();
                    if (record.TryGetInt64(out blobsize))
                    {
                    }
                }
                else
                {
                    var client = _azureStorage.GetBlobContainerClient(name);
                    var size = await client.GetBlobsCatalogSize();
                    await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", name, size.Item1);
                    foreach (var key in size.Item2.Keys)
                    {
                        await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{name}", key);
                        await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{name}", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
                    }
                    return Ok(new { size = size.Item1, catalog = size.Item2 ,teach });
                }
                Dictionary<string, double> catalog = new Dictionary<string, double>();
                SortedSetEntry[] Scores = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Blob:Catalog:{name}");
                if (Scores != null)
                {
                    foreach (var score in Scores)
                    {
                        double val = score.Score;
                        string key = score.Element.ToString();
                        catalog.Add(key, val);
                    }
                    return Ok(new { size = blobsize, catalog = catalog, teach });
                }
                else {
                    var client = _azureStorage.GetBlobContainerClient(name);
                    var size = await client.GetBlobsCatalogSize();
                    await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", name, size.Item1);
                    foreach (var key in size.Item2.Keys)
                    {
                        await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{name}", key);
                        await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{name}", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
                    }
                    return Ok(new { size = size.Item1, catalog = size.Item2, teach });
                }
            }
            catch (Exception  ex){
                await _dingDing.SendBotMsg($"IES5，{_option.Location}，blon/used-space()\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
            }
            return BadRequest();
        }



        private static (string, string) BlobUrlString(string sasUrl)
        {
            sasUrl = sasUrl.Substring(8);
            string[] sasUrls = sasUrl.Split("/");
            string ContainerName;
            ContainerName = sasUrls[1].Clone().ToString();
            string item = sasUrls[0] + "/" + sasUrls[1] + "/";
            string blob = sasUrl.Replace(item, "");
            return (ContainerName, blob);
        }
        public static bool IsBlobName(string BlobName)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(BlobName,
             @"(?!((^(con)$)|^(con)\\..*|(^(prn)$)|^(prn)\\..*|(^(aux)$)|^(aux)\\..*|(^(nul)$)|^(nul)\\..*|(^(com)[1-9]$)|^(com)[1-9]\\..*|(^(lpt)[1-9]$)|^(lpt)[1-9]\\..*)|^\\s+|.*\\s$)(^[^\\\\\\:\\<\\>\\*\\?\\\\\\""\\\\|]{1,255}$)");
        }



        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("bloblog-list")]
        public async Task<ActionResult> BloblogList(JsonElement request)
        {
            List<Bloblog> bloblogs = new List<Bloblog>();
            try
            {
                request.TryGetProperty("name", out JsonElement name);
                request.TryGetProperty("type", out JsonElement type);
                request.TryGetProperty("scope", out JsonElement scope);
                request.TryGetProperty("periodId", out JsonElement periodId);
                var client = _azureCosmos.GetCosmosClient();

                if (scope.GetString().Equals("school"))
                {
                    var queryslt = new StringBuilder($"SELECT  value(c) FROM c join A1 in  c.periodId  WHERE c.type='{type}' and  A1 in ('{periodId}') ");

                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<Bloblog>(queryText: queryslt.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Bloblog-{name}") }))
                    {
                        bloblogs.Add(item);
                    }
                }
                else if (scope.GetString().Equals("private"))
                {
                    var queryslt = new StringBuilder($"SELECT  value(c) FROM c   WHERE c.type='{type}'  ");
                    await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<Bloblog>(queryText: queryslt.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Bloblog-{name}") }))
                    {
                        bloblogs.Add(item);
                    }
                }
                return Ok(new { bloblogs = bloblogs });
            }
            catch (Exception ex)
            {
                return Ok(new { bloblogs = bloblogs });
            }
        }
      
        /// <summary>
        /// 重命名
        /// {"scope":"school","cntr":"hbcn","id":"bbf24ca7-487e-4196-8c99-b2c418a2d1b1","newName":"video/核能1.mp4"}
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        [HttpPost("bloblog-rename")]
        public async Task<ActionResult> BloblogRename(JsonElement request)
        {
            var client = _azureCosmos.GetCosmosClient();
            if (!request.TryGetProperty("scope", out JsonElement _scope)) return BadRequest();
            if(!request.TryGetProperty("cntr", out JsonElement _cntr))return BadRequest();
            if (!request.TryGetProperty("id", out JsonElement _id))return BadRequest();
            if (!request.TryGetProperty("newName", out JsonElement _newName))return BadRequest();
            string tbname= $"{_scope}".Equals("school",StringComparison.OrdinalIgnoreCase) ? "School": "Teacher";
            try
            {
                Bloblog bloblog = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemAsync<Bloblog>($"{_id}", new PartitionKey($"Bloblog-{_cntr}"));
                string oldUrl = bloblog.url;
                if (oldUrl.Equals($"{_newName}")) {
                    return Ok();
                }
                if (oldUrl.StartsWith("res", StringComparison.OrdinalIgnoreCase) && oldUrl.EndsWith(".htex", StringComparison.OrdinalIgnoreCase)) {
                    oldUrl = oldUrl.Replace(".htex", "", StringComparison.OrdinalIgnoreCase);
                }
                string newName = $"{_newName}";
                if (newName.StartsWith("res", StringComparison.OrdinalIgnoreCase) && newName.EndsWith(".htex", StringComparison.OrdinalIgnoreCase))
                {
                    newName = newName.Replace(".htex", "", StringComparison.OrdinalIgnoreCase);
                }
                bloblog.name = $"{_newName}";
                bloblog.url = $"{_newName}";
                var bcc = _azureStorage.GetBlobContainerClient($"{_cntr}");
                string px = oldUrl;

                if (oldUrl.StartsWith("/"))
                {
                    px = oldUrl.Substring(1);
                }
                List<BlobItem> blobItems = new List<BlobItem>();
                await foreach (var item in bcc.GetBlobsAsync(BlobTraits.None, BlobStates.None, px)) {
                    blobItems.Add(item);
                }
                foreach (var item in blobItems)
                {
                    if (item.Name.StartsWith("image") || item.Name.StartsWith("video"))
                    {
                        var thum = $"thum{ item.Name.Substring(5)}";
                        var tnewName = $"thum{ newName.Substring(5)}";
                        var tpx = $"thum{ px.Substring(5)}";
                        string tname = thum.Replace(tpx, tnewName);
                        if (item.Name.StartsWith("video")) {
                            string fileexturl = thum.Substring(thum.LastIndexOf(".") > 0 ? thum.LastIndexOf(".") : 0);
                            thum = thum.Replace(fileexturl, ".png");
                            string fileextname = tname.Substring(tname.LastIndexOf(".") > 0 ? tname.LastIndexOf(".") : 0);
                            tname = tname.Replace(fileextname, ".png");
                        }
                        var turl = _azureStorage.GetBlobSAS($"{_cntr}", thum, BlobSasPermissions.Read | BlobSasPermissions.List);
                        bcc.GetBlobClient(tname).SyncCopyFromUri(new Uri(turl));
                        await _azureStorage.GetBlobServiceClient().DeleteBlobs(_dingDing, $"{_cntr}", new List<string> { thum });
                    }
                    string targetName = item.Name.Replace(px, newName);
                    var url = _azureStorage.GetBlobSAS($"{_cntr}", item.Name, BlobSasPermissions.Read | BlobSasPermissions.List);
                    bcc.GetBlobClient(targetName).SyncCopyFromUri(new Uri(url));

                };
                await _azureStorage.GetBlobServiceClient().DeleteBlobs(_dingDing, $"{_cntr}", new List<string> { px });
                await client.GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync<Bloblog>(bloblog, $"{_id}", new PartitionKey($"Bloblog-{_cntr}"));
                string u = "";
                string[] uls = System.Web.HttpUtility.UrlDecode(px, Encoding.UTF8).Split("/");
                if (uls != null)
                {
                    u = !string.IsNullOrEmpty(uls[0]) ? uls[0] : uls[1];
                }
                if (!string.IsNullOrEmpty(u)) {
                    var messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", root = u, name = $"{_cntr}" }.ToJsonString()); ;
                    messageBlob.ApplicationProperties.Add("name", "BlobRoot");
                    var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
                    await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
                }
                return Ok(new { status = true });
            }
            catch (CosmosException ex)
            {
                return BadRequest();
            }
            catch (Exception ex )
            { 
                return BadRequest();
            }
        }

        /*
         新增 编辑接口
        {
            "periodId": "",
            "scope": "school",
            "name": "hbcn",
            "url": "video/xxx.png",
            "opt": "add",
        }
         */
        /*
         {
            "scope": "school",
            "name": "hbcn",
            "opt": "del",
            "id": "19ccce98-c524-4ea7-aabc-887d1391e551"
        }
         */
        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("bloblog-upsert")]
        public async Task<ActionResult> BloblogOpt(JsonElement request) {

            try
            {
                request.TryGetProperty("periodId", out JsonElement periodId);
                request.TryGetProperty("subjectId", out JsonElement subjectId);
                request.TryGetProperty("gradeId", out JsonElement gradeId);
                request.TryGetProperty("scope", out JsonElement scope);
                request.TryGetProperty("name", out JsonElement name);
                request.TryGetProperty("url", out JsonElement jurls);
                //request.TryGetProperty("id", out JsonElement ids);
                //获取文件的大小
                var client = _azureCosmos.GetCosmosClient();
                List<string> urls = jurls.ToObject<List<string>>();
                HashSet<string> root = new HashSet<string>();
                List<Bloblog> bloblog = new List<Bloblog>();
                foreach (var uri in urls) {
                    var url = System.Web.HttpUtility.UrlDecode(uri, Encoding.UTF8);
                    string[] uls = url.Split("/");
                    var u = "";
                    if (uls != null)
                    {
                        u = !string.IsNullOrEmpty(uls[0]) ? uls[0] : uls[1];
                        root.Add(u);
                    }
                    long? size = 0;
                    if (url.StartsWith("res/") && url.EndsWith("/index.json"))
                    {
                        var prefix=  url.Substring(0, url.Length - 11);
                        size = await _azureStorage.GetBlobContainerClient($"{name}").GetBlobsSize(prefix);
                    }
                    else {
                        size = await _azureStorage.GetBlobContainerClient($"{name}").GetBlobsSize(url);
                    }
                    
                    long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                    //地址相同的，直接更新
                    bool exsit = false;
                       
                    try
                    {
                        var queryslt = $"SELECT  value(c) FROM c WHERE c.url='{url}'";
                        if (scope.GetString().Equals("school"))
                        {
                            await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<Bloblog>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Bloblog-{name}") }))
                            {
                                item.time = now;
                                item.size = size != null && size.HasValue ? size.Value : 0;
                                item.periodId = periodId.ValueKind.Equals(JsonValueKind.Array) ? periodId.ToObject<List<string>>() : new List<string> { "" };
                                item.subjectId = subjectId.ValueKind.Equals(JsonValueKind.Array) ? subjectId.ToObject<List<string>>() : new List<string> { "" };
                                item.gradeId = gradeId.ValueKind.Equals(JsonValueKind.Array) ? gradeId.ToObject<List<string>>() : new List<string> { "" };
                                await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<Bloblog>(item, item.id, new Azure.Cosmos.PartitionKey(item.code));
                                bloblog.Add(item);
                                exsit = true;
                            }
                        }
                        else if (scope.GetString().Equals("private"))
                        {
                            await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<Bloblog>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Bloblog-{name}") }))
                            {
                                item.time = now;
                                item.size = size != null && size.HasValue ? size.Value : 0;
                                item.periodId = periodId.ValueKind.Equals(JsonValueKind.Array) ? periodId.ToObject<List<string>>() : new List<string> { "" };
                                item.subjectId = subjectId.ValueKind.Equals(JsonValueKind.Array) ? subjectId.ToObject<List<string>>() : new List<string> { "" };
                                item.gradeId = gradeId.ValueKind.Equals(JsonValueKind.Array) ? gradeId.ToObject<List<string>>() : new List<string> { "" };
                                await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Bloblog>(item, item.id, new Azure.Cosmos.PartitionKey(item.code));
                                bloblog.Add(item);
                                exsit = true;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        await _dingDing.SendBotMsg($"IES5，{_option.Location}，blob/bloblog-blob()\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
                    }
                    if (!exsit)
                    {
                        var blob = new Bloblog
                        {
                            id = Guid.NewGuid().ToString(),
                            pk = "Bloblog",
                            code = $"Bloblog-{name}",
                            url = url,
                            time = now,
                            size = size != null && size.HasValue ? size.Value : 0,
                            periodId = periodId.ValueKind.Equals(JsonValueKind.Array) ? periodId.ToObject<List<string>>() : new List<string> { "" },
                            subjectId = subjectId.ValueKind.Equals(JsonValueKind.Array) ? subjectId.ToObject<List<string>>() : new List<string> { "" },
                            gradeId = gradeId.ValueKind.Equals(JsonValueKind.Array) ? gradeId.ToObject<List<string>>() : new List<string> { "" },
                            type = u
                        };
                        if (scope.GetString().Equals("school"))
                        {
                            await client.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync(blob, new Azure.Cosmos.PartitionKey(blob.code));
                        }
                        else if (scope.GetString().Equals("private"))
                        {
                            await client.GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync(blob, new Azure.Cosmos.PartitionKey(blob.code));
                        }
                        bloblog.Add(blob);
                    }
                }
                root.ToList().ForEach(async x => {
                    var messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", root = x, name = $"{name}" }.ToJsonString()); ;
                    messageBlob.ApplicationProperties.Add("name", "BlobRoot");
                    var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
                    await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
                });
                return Ok(new { bloblog, status = 200 });
                 
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"IES5，{_option.Location}，blob/bloblog-blob()\n{ex.Message}{ex.StackTrace}\n{request.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
            }
            return Ok(new { status = 200 });
        }

        /// <summary>
        /// 删除prefix  不管是内容 模块还是其他试题试卷 评测 问卷投票等都在使用。
        /// 
        /// {"cntr":"","prefix":"res/test"}
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("delete-prefix")]
        [AuthToken(Roles = "teacher,admin")]
        public async Task<IActionResult> DeletePrefix(JsonElement json)
        {
            var (id, _, _, school) = HttpContext.GetAuthTokenInfo();
            string blobContainerName = null;
            string prefix = null;
            if (json.TryGetProperty("cntr", out JsonElement cntr) && cntr.ValueKind.Equals(JsonValueKind.String))
            {
                var cntrs = cntr.GetString();
                if (cntrs.Equals(id))
                {
                    blobContainerName = id;
                }
                else if (cntrs.Equals(school))
                {
                    blobContainerName = school;
                }else if (cntrs.Equals("teammodelos"))
                {
                    blobContainerName = "teammodelos";
                }
                else
                {
                    return BadRequest("只能删除本人管理的文件夹");
                }
            }
            if (json.TryGetProperty("prefix", out JsonElement prefixjson) && prefixjson.ValueKind.Equals(JsonValueKind.String))
            {
                prefix = prefixjson.GetString();
            }
            if (prefix != null && blobContainerName != null)
            {
                var status = await _azureStorage.GetBlobServiceClient().DeleteBlobs(_dingDing, blobContainerName, new List<string> { prefix });
                string u = "";
                string[] uls = System.Web.HttpUtility.UrlDecode($"{prefixjson}", Encoding.UTF8).Split("/");
                if (uls != null)
                {
                    u = !string.IsNullOrEmpty(uls[0]) ? uls[0] : uls[1];
                }
                var messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", root = u, name = $"{blobContainerName}" }.ToJsonString()); ;
                messageBlob.ApplicationProperties.Add("name", "BlobRoot");
                var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
                await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
                return Ok(new { status });
            }
            else
            {
                return BadRequest();
            }
        }

        public record ContBlob { 
            public string path { get; set; }
            public string id { get; set; }
        }

        /// <summary>
        /// 删除多个Url,只会在内容模块使用该接口
        /// 
        /// 
        /// {"scope":"school","cntr":"hbcn","blobs":[{"path":"other/test/1.json","id":"c107069d-4553-46c2-8c81-b3e6b4599393"},{"path":"res/test","id":"09d59b87-68c0-45fa-8221-9931a4190a2f"}]}
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("bloblog-delete")]
        [AuthToken(Roles = "teacher,admin")]
        public async Task<IActionResult> DeleteBlobs(JsonElement json)
        {
            ///BlobBaseClient  copy
            try {
                var (id, _, _, school) = HttpContext.GetAuthTokenInfo();
                string blobContainerName = null;
                if (!json.TryGetProperty("scope", out JsonElement _scope)) return BadRequest();
                if (!json.TryGetProperty("blobs", out JsonElement _blobs)) return BadRequest();
                if (json.TryGetProperty("cntr", out JsonElement cntr))
                {
                    var cntrs = cntr.ToString();
                    if (cntrs.Equals(id))
                    {
                        blobContainerName = id;
                    }
                    else if (cntrs.Equals(school))
                    {
                        blobContainerName = school;
                    }
                    else
                    {
                        return BadRequest("只能删除本人管理的文件");
                    }
                }
                bool flag = true;
                List<ContBlob> blobs = _blobs.ToObject<List<ContBlob>>();
                try
                {
                    var client = _azureCosmos.GetCosmosClient();
                    List<string> ids = blobs.Select(x => x.id).ToList();
                    string containerId = "School";
                    if (_scope.GetString().Equals("school"))
                    {
                        containerId = "School";
                    }
                    else if (_scope.GetString().Equals("private"))
                    {
                        containerId = "Teacher";
                    }
                    await client.GetContainer(Constant.TEAMModelOS, containerId).DeleteItemsAsync<Bloblog>(ids, $"Bloblog-{blobContainerName}");
                }
                catch (CosmosException   ex )
                {
                    //仅处理 cosmos不存在 但容器又存在的
                }
                if (flag)
                {
                    var urls = blobs.Select(x => x.path).ToList();
                    List<string> deleteUrl = new List<string>();
                    urls.ForEach(x => {
                        string delUrl = x;
                        if (x.StartsWith("res/") && x.EndsWith(".HTEX", StringComparison.OrdinalIgnoreCase))
                        {
                            delUrl = x.Substring(0, x.Length - 4);
                        }
                        if (x.StartsWith("res/") && x.EndsWith("/index.json", StringComparison.OrdinalIgnoreCase))
                        {
                            delUrl = x.Substring(0, x.Length -11);
                        }
                        //自动删除视频和图片的缩略图
                        if (x.StartsWith("image")||x.StartsWith("video")) {

                            var thum  = $"thum{ x.Substring(5)}" ;
                            if (x.StartsWith("video"))
                            {
                                string fileexturl = thum.Substring(thum.LastIndexOf(".") > 0 ? thum.LastIndexOf(".") : 0);
                                thum = thum.Replace(fileexturl, ".png");
                            }
                            deleteUrl.Add(thum);
                        }
                        deleteUrl.Add(delUrl);
                    });
                    var status = await _azureStorage.GetBlobServiceClient().DeleteBlobs(_dingDing, blobContainerName, deleteUrl);
                    //释放的空间
                    HashSet<string> root = new HashSet<string>();
                    foreach (var x in deleteUrl)
                    {
                        string url = System.Web.HttpUtility.UrlDecode(x, Encoding.UTF8);
                       
                        
                        string[] uls = url.Split("/");
                        if (uls != null)
                        {
                            string u = !string.IsNullOrEmpty(uls[0]) ? uls[0] : uls[1];
                            root.Add(u);
                        }
                    }
                    root.ToList().ForEach(async x => {
                        var messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", root = x, name = $"{blobContainerName}" }.ToJsonString()); ;
                        messageBlob.ApplicationProperties.Add("name", "BlobRoot");
                        var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
                        await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
                    });
                    return Ok(new { status });
                }
                else
                {
                    return BadRequest("只能删除本人管理的文件");
                }
            } catch (Exception ex) {

                await _dingDing.SendBotMsg($"IES5，{_option.Location}，blob/delete-blobs\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
                return BadRequest();
            }
        }

        /// <summary>
        /// 列出blob的
        /// 
        /// {"cntr":"","urls":["res/test/1.json","res/test/2.json"]}
        /// {"scope":"school","cntr":"hbcn","blobs":[{"path":"other/test/1.json","id":"c107069d-4553-46c2-8c81-b3e6b4599393"},{"path":"res/test","id":"09d59b87-68c0-45fa-8221-9931a4190a2f"}]}
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("blob-list")]
        [AuthToken(Roles = "teacher,admin,student")]
        public async Task<IActionResult> BlobList(JsonElement json) {
            var (userid, _, _, school) = HttpContext.GetAuthTokenInfo();
            List<string> paths = new List<string>();
            //文件的容器
            if (!json.TryGetProperty("cntr", out JsonElement _cntr)) return BadRequest();
            //业务存取类型 exam,vote,survey,item,paper,syllabus,records,avatar,content(doc,image,res,video,audio,other),thum,train,temp,jyzx
            if (!json.TryGetProperty("type", out JsonElement _type)) return BadRequest();
            //文件前缀prefix
            switch (true)
            {
                case bool when $"{_type}".Equals("exam", StringComparison.OrdinalIgnoreCase)
                    || $"{_type}".Equals("vote", StringComparison.OrdinalIgnoreCase)
                    || $"{_type}".Equals("survey", StringComparison.OrdinalIgnoreCase)
                    || $"{_type}".Equals("item", StringComparison.OrdinalIgnoreCase)
                    || $"{_type}".Equals("paper", StringComparison.OrdinalIgnoreCase):
                    string type = $"{_type}".Substring(0, 1).ToUpper() + $"{_type}".Substring(1);
                    //业务存取id
                    if (!json.TryGetProperty("id", out JsonElement _aid)) return BadRequest();
                    //业务存取分区键
                    if (!json.TryGetProperty("code", out JsonElement _acode)) return BadRequest();
                    //业务存取分区键
                    if (!json.TryGetProperty("scope", out JsonElement _ascope)) return BadRequest();
                    break;
                case bool when $"{_type}".Equals("doc", StringComparison.OrdinalIgnoreCase)
                    || $"{_type}".Equals("image", StringComparison.OrdinalIgnoreCase)
                    || $"{_type}".Equals("res", StringComparison.OrdinalIgnoreCase)
                    || $"{_type}".Equals("video", StringComparison.OrdinalIgnoreCase)
                    || $"{_type}".Equals("audio", StringComparison.OrdinalIgnoreCase)
                    || $"{_type}".Equals("other", StringComparison.OrdinalIgnoreCase):
                    //业务存取id
                    if (!json.TryGetProperty("id", out JsonElement _bid)) return BadRequest();
                    //业务存取分区键
                    if (!json.TryGetProperty("code", out JsonElement _bcode)) return BadRequest();
                    //业务存取分区键
                    if (!json.TryGetProperty("scope", out JsonElement _bscope)) return BadRequest();
                    break;
                case bool when $"{_type}".Equals("records", StringComparison.OrdinalIgnoreCase)
                    || $"{_type}".Equals("syllabus", StringComparison.OrdinalIgnoreCase)
                    || $"{_type}".Equals("thum", StringComparison.OrdinalIgnoreCase)
                    || $"{_type}".Equals("temp", StringComparison.OrdinalIgnoreCase)
                    || $"{_type}".Equals("jyzx", StringComparison.OrdinalIgnoreCase)
                    || $"{_type}".Equals("avatar", StringComparison.OrdinalIgnoreCase)
                    || $"{_type}".Equals("train", StringComparison.OrdinalIgnoreCase):
                    break;
                default:
                    break;
            }
           return Ok(new { paths ,status=1});
        }
    }
}
