using BPA.KitChen.GroupMeal.Application.Service.SysService.Dtos;
using BPA.KitChen.GroupMeal.Core.Common.Const;
using BPA.KitChen.GroupMeal.SqlSugar;
using COSXML;
using COSXML.Auth;
using COSXML.Model.Tag;
using Furion;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System.Text.RegularExpressions;

namespace BPA.KitChen.GroupMeal.Application.Service.SysService
{
    [ApiDescriptionSettings("系统管理", Tag = "系统", SplitCamelCase = false)]
    public class SysService : SupperRepository, IDynamicApiController, ITransient, ISysService
    {
        private readonly SqlSugarScope db;

         private COSXML.CosXml cosXml;
        public SysService()
        {
            db = SqlSugarDb.Db;
            CosXmlConfig config = new CosXmlConfig.Builder()
                .SetRegion(App.Configuration["cos_config:Region"]) // 设置默认的区域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
                .Build();

            string secretId = App.Configuration["cos_config:SecretId"];   // 云 API 密钥 SecretId, 获取 API 密钥请参照 https://console.cloud.tencent.com/cam/capi
            string secretKey = App.Configuration["cos_config:SecretKey"]; // 云 API 密钥 SecretKey, 获取 API 密钥请参照 https://console.cloud.tencent.com/cam/capi
            long durationSecond = 6000;          //每次请求签名有效时长，单位为秒
            QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCredentialProvider(secretId,
                secretKey, durationSecond);

            this.cosXml = new CosXmlServer(config, qCloudCredentialProvider);
        }

        [HttpPost("/api/SysService/GetPresignUploadUrl")]
        public FileOutInfoDto GetPresignUploadUrl(FileInputInfoDto inputDto)
        {
            // var cosConfig = CosConfig.cosInfoOptions;
            string GroupId = App.User.FindFirst(ClaimConst.GroupId)?.Value;
            string baseUrl = "/Franchisee/";
            if (!string.IsNullOrWhiteSpace(GroupId))
            {
                //var Companycheck = db.Queryable<BPA_Company>().Where(x => x.Id == GroupId).First();
                baseUrl = baseUrl + GroupId + "/";
            }
            DateTime dt = DateTime.Now;
            baseUrl = baseUrl + inputDto.Directory + "/" + dt.ToFileTime().ToString() + "." + inputDto.FileExtension;
            try
            {
                PreSignatureStruct preSignatureStruct = new PreSignatureStruct();
                preSignatureStruct.appid = App.Configuration["cos_config:AppId"];//腾讯云账号 APPID
                preSignatureStruct.region = App.Configuration["cos_config:Region"]; //存储桶地域
                preSignatureStruct.bucket = App.Configuration["cos_config:Bucket"]; //存储桶
                preSignatureStruct.key = baseUrl; //对象键+".png"
                preSignatureStruct.httpMethod = "PUT"; //HTTP 请求方法
                preSignatureStruct.isHttps = true; //生成 HTTPS 请求 URL
                preSignatureStruct.signDurationSecond = 6000; //请求签名时间为 600s
                preSignatureStruct.headers = null;//签名中需要校验的 header
                preSignatureStruct.queryParameters = null; //签名中需要校验的 URL 中请求参数
                //上传预签名 URL (使用永久密钥方式计算的签名 URL)
                string requestSignURL = cosXml.GenerateSignURL(preSignatureStruct);
                string[] urls = requestSignURL.Split('?');
                Regex reg = new Regex("(http|https)://.+?(?=/)");
                Match match = reg.Match(requestSignURL);
                FileOutInfoDto fileOut = new FileOutInfoDto();
                fileOut.Domain = match.Value;
                fileOut.FileUrl = urls[0].Replace(fileOut.Domain, "/cos");
                fileOut.Param = urls[1];
                fileOut.AllUrl = requestSignURL;
                fileOut.SeeUrl = urls[0];
                return fileOut;
            }
            catch (COSXML.CosException.CosClientException clientEx)
            {
                //请求失败
                //  Console.WriteLine("CosClientException: " + clientEx);
            }
            catch (COSXML.CosException.CosServerException serverEx)
            {
                //请求失败
                //Console.WriteLine("CosServerException: " + serverEx.GetInfo());
            }
            return null;
        }
    }
}
