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 TEAMModelOS.SDK.Context.Constant.Common;
using HTEXLib.COMM.Helpers;
using TEAMModelOS.Models;
using Microsoft.Extensions.Options;
using TEAMModelOS.SDK.Models;
using Azure.Cosmos;

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>
        /// 删除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
                {
                    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().DelectBlobs(blobContainerName, 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();
            }
            
        }

         
        /// <summary>
        /// 删除多个Url
        /// 
        /// {"cntr":"","urls":["res/test/1.json","res/test/2.json"]}
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("delete-blobs")]
        [AuthToken(Roles = "teacher,admin")]
        public async Task<IActionResult> DeleteBlobs(JsonElement json)
        {
           var (id, _, _, school) = HttpContext.GetAuthTokenInfo();
            string blobContainerName = null;
            List<Uri> uris = null;
            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;
            if (json.TryGetProperty("urls", out JsonElement urlsjson)) {
                uris= urlsjson.ToObject<List<Uri>>();
                uris.ForEach(x => {
                    (string, string) a = BlobUrlString(x.ToString());
                    string ContainerName = a.Item1;
                    string BlobName = a.Item2;
                    if (ContainerName!=blobContainerName) {
                        flag = false;
                    }
                });
            }
            if (flag)
            {
                if (blobContainerName != null && uris != null && uris.Count > 0)
                {
                    var urls = urlsjson.ToObject<List<string>>();
                    var status = await _azureStorage.GetBlobServiceClient().DelectBlobs(blobContainerName, uris);
                    //释放的空间
                    HashSet<string> root = new HashSet<string>();
                    foreach (var x in urls)
                    {
                        string[] uls = System.Web.HttpUtility.UrlDecode(x, Encoding.UTF8).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();
                }
            }
            else {
                return BadRequest("只能删除本人管理的文件");
            }
        }


        /// <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>
        /// 获取容器的 分类及总量
        /// </summary>
        /// <param name="azureBlobSASDto"></param>
        /// <returns></returns>
        [HttpPost("get-blobsize")]
        public async Task<ActionResult> GetBlobsSize(JsonElement request)
        {
            try
            {
                request.TryGetProperty("containerName", out JsonElement containerName);
                request.TryGetProperty("cache", out JsonElement cache);
                var name =containerName.GetString();
                if (cache.GetBoolean())
                {
                    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 });
                    }
                    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 });
                    }
                    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 });
                    }
                }
                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 });
                }
                
            }
            catch (Exception  ex){
                await _dingDing.SendBotMsg($"IES5，{_option.Location}，blon/get-blobsize()\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
            }
            return BadRequest();
        }

        //TODO 不要了
        /// <summary>
        /// 测试单个文本内容的上传
        /// {"containerName":"hbcn","urls":["video/xxx.mp4","res/xxx.png"],"prefix":["res/xxx","res/aaa"]}
        /// </summary>
        /// <param name="azureBlobSASDto"></param>
        /// <returns></returns>
        [HttpPost("check-blobsize")]
        public async Task<ActionResult> checkBlobsSize(JsonElement request)
        {
            request.TryGetProperty("containerName", out JsonElement containerName);
            request.TryGetProperty("urls", out JsonElement optUrls);
            request.TryGetProperty("prefix", out JsonElement prefixjs);
            var name = containerName.GetString();
            var urls = optUrls.ValueKind.Equals(JsonValueKind.Array) ? optUrls.ToObject<List<string>>() : null ;
            var client = _azureStorage.GetBlobContainerClient(name);
            var urlsSize = await client.GetBlobsSize(urls);
            List<OptUrl> prefixSize = new List<OptUrl>();
            var prefixs = prefixjs.ValueKind.Equals(JsonValueKind.Array) ? prefixjs.ToObject<List<string>>() : new List<string>();
            foreach(var prefix in prefixs) {
               var  size = await client.GetBlobsSize(System.Web.HttpUtility.UrlDecode(prefix, Encoding.UTF8));
                prefixSize.Add(new OptUrl { url = prefix, size = size.Value });
            }
            return Ok(new {  urlsSize   , prefixSize });
        }

        /*
         * 
         {
            "containerName": "hbcn",
            "cache": true,
            "optUrls": [
                {
                    "url": "video%2F37Z888piCvm9.mp4",
                    "size": 1000
                }
            ]
         }
        */
        //TODO 不要了
        /// <summary>
        /// 测试单个文本内容的上传
        /// {"containerName":"hbcn","uploadSize":5000,"optUrls":[{"url":"video/37Z888piCvm9.mp4","size":0},{}]}
        /// </summary>
        /// <param name="azureBlobSASDto"></param>
        /// <returns></returns>
        [HttpPost("update-blobsize")]
        public async Task<ActionResult> updateBlobsSize(JsonElement request)
        {
            request.TryGetProperty("containerName", out JsonElement containerName);
            request.TryGetProperty("optUrls", out JsonElement optUrls);
            var name = containerName.GetString();
            var urls = optUrls.ToObject<List<OptUrl>>();
            var client = _azureStorage.GetBlobContainerClient(name);
            var disSize = urls.Select(x => x.size).Sum();
            RedisValue value = default;
            long blobSize = 0;
            value = _azureRedis.GetRedisClient(8).HashGet($"Blob:Record", name);
            if (value != default && !value.IsNullOrEmpty)
            {
                JsonElement record = value.ToString().ToObject<JsonElement>();
                if (record.TryGetInt64(out blobSize))
                {
                }
            }
            long? useSize = blobSize + disSize;
            await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", name, useSize);
            Dictionary<string, double?> catalog = new Dictionary<string, double?>();
            HashSet<string> root = new HashSet<string>();
            foreach (var x in urls) {
                string[] uls = System.Web.HttpUtility.UrlDecode(x.url, Encoding.UTF8).Split("/");
                if (uls != null)
                {
                    string u = !string.IsNullOrEmpty(uls[0]) ? uls[0] : uls[1];
                    root.Add(u);

                    await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{name}", u, x.size);
                    catalog[u] = await _azureRedis.GetRedisClient(8).SortedSetScoreAsync($"Blob:Catalog:{name}", u);
                    if (catalog[u] < 0)
                    {
                        await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{name}", u);
                        catalog[u] = 0;
                    }
                }
            }
            var messageBlob = new ServiceBusMessage(new {id=Guid.NewGuid().ToString(), progress = "update", root= root.ToArray(), name=name}.ToJsonString());;
            messageBlob.ApplicationProperties.Add("name", "Blob");
            var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
            await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
            return Ok(new { size=useSize, catalog });
        }

        /// <summary>
        /// {"name":"hbcn","urls":["root/xxxx/xxx.json","root/xxxx/xxx.json"]}
        /// </summary>
        /// <param name="azureBlobSASDto"></param>
        /// <returns></returns>
        [HttpPost("refresh-blobsize")]
        public async Task<ActionResult> RefreshBlob(JsonElement request) {
            try {
                request.TryGetProperty("name", out JsonElement name);
                request.TryGetProperty("urls", out JsonElement jurls);
                var urls = jurls.ToObject<List<string>>();
                HashSet<string> root = new HashSet<string>();
                foreach (var x in urls)
                {
                    string[] uls = System.Web.HttpUtility.UrlDecode(x, Encoding.UTF8).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 = $"{name}" }.ToJsonString()); ;
                    messageBlob.ApplicationProperties.Add("name", "BlobRoot");
                    var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
                    await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
                });
                return Ok(new { status = 200 });
            } catch (Exception ex) {
                await _dingDing.SendBotMsg($"IES5，{_option.Location}，blon/refresh-blob()\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
            }
            return Ok(new { status = 500 });
        }
        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("period", out JsonElement period);
                var client = _azureCosmos.GetCosmosClient();
                var queryslt = $"SELECT  value(c) FROM c WHERE c.type='{type}' and  c.period='{period}'";
                if (scope.GetString().Equals("school"))
                {
                    await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<Bloblog>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Bloblog-{name}") }))
                    {
                        bloblogs.Add(item);
                    }
                }
                else if (scope.GetString().Equals("teacher"))
                {
                    await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<Bloblog>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Bloblog-{name}") }))
                    {
                        bloblogs.Add(item);
                    }
                }
                return Ok(new { bloblogs = bloblogs });
            }
            catch (Exception ex) {
                return Ok(new { bloblogs = bloblogs });
            }
        }

        /*
         新增 编辑接口
        {
            "period": "",
            "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> BloblogUpsert(JsonElement request) {

            try
            {
                request.TryGetProperty("period", out JsonElement period);
                request.TryGetProperty("scope", out JsonElement scope);
                request.TryGetProperty("name", out JsonElement name);
                request.TryGetProperty("url", out JsonElement jurl);
                request.TryGetProperty("opt", out JsonElement opt);
                request.TryGetProperty("id", out JsonElement id);
                var url = System.Web.HttpUtility.UrlDecode(jurl.GetString(), Encoding.UTF8);
                string[] uls = url.Split("/");
                var u = "";
                if (uls != null)
                {
                     u = !string.IsNullOrEmpty(uls[0]) ? uls[0] : uls[1];
                    
                }
                var size = await _azureStorage.GetBlobContainerClient($"{name}").GetBlobsSize(url);
                long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                //获取文件的大小
                var client = _azureCosmos.GetCosmosClient();
                if (opt.GetString().Equals("add"))
                {
                    //地址相同的，直接更新
                    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("TEAMModelOS", "School").GetItemQueryIterator<Bloblog>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Bloblog-{name}") }))
                            {
                                item.size = size != null && size.HasValue ? size.Value : 0;
                                await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<Bloblog>(item, item.id, new Azure.Cosmos.PartitionKey(item.code));
                                exsit = true;
                            }
                        }
                        else if (scope.GetString().Equals("teacher")) {
                            await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<Bloblog>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Bloblog-{name}") }))
                            {
                                item.size = size != null && size.HasValue ? size.Value : 0;
                                await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<Bloblog>(item, item.id, new Azure.Cosmos.PartitionKey(item.code));
                                exsit = true;
                            }
                        }
                    } catch (Exception ex) {
                    }
                    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,
                            period = $"{period}",
                            type = u
                        };
                        if (scope.GetString().Equals("school"))
                        {
                            await client.GetContainer("TEAMModelOS", "School").CreateItemAsync(blob, new Azure.Cosmos.PartitionKey(blob.code));
                        }
                        else if (scope.GetString().Equals("teacher"))
                        {
                            await client.GetContainer("TEAMModelOS", "Teacher").CreateItemAsync(blob, new Azure.Cosmos.PartitionKey(blob.code));
                        }
                    }
                }
                else if (opt.GetString().Equals("del"))
                {
                    if (scope.GetString().Equals("school"))
                    {
                        await client.GetContainer("TEAMModelOS", "School").DeleteItemStreamAsync($"{id}", new Azure.Cosmos.PartitionKey($"Bloblog-{name}"));
                    }
                    else if (scope.GetString().Equals("teacher"))
                    {
                        await client.GetContainer("TEAMModelOS", "Teacher").DeleteItemStreamAsync($"{id}", new Azure.Cosmos.PartitionKey($"Bloblog-{name}"));
                    }
                }
                else { return BadRequest(); }
                return Ok(new { status = 200 });
            }
            catch (Exception ex)
            {
                await _dingDing.SendBotMsg($"IES5，{_option.Location}，blon/refresh-blob()\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
            }
            return Ok(new { status = 200 });
        }


    }
}
