using BPA.SAAS.Manage.Application.System.Dtos;
using BPA.SAAS.Manage.Application.System.Interface;
using BPA.SAAS.Manage.Comm.Const;
using BPA.SAAS.Manage.Core.Org;
using COSXML;
using COSXML.Auth;
using COSXML.Model.Tag;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace BPA.SAAS.Manage.Application.System.Services
{
    public class SystemConfigService: ISystemConfigService, ITransient
    {
        private readonly ISqlSugarClient _db;
        private CosXml cosXml;
        public SystemConfigService( ISqlSugarClient db)
        {
            _db=db;
            var cosConfig = CosConfig.cosInfoOptions;
            CosXmlConfig config = new CosXmlConfig.Builder()
           .SetRegion(cosConfig.Region) // 设置默认的区域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
           .Build();

            string secretId = cosConfig.SecretId;   // 云 API 密钥 SecretId, 获取 API 密钥请参照 https://console.cloud.tencent.com/cam/capi
            string secretKey = cosConfig.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);
        }

        public async Task<string> GetCosImgesURL(IFormFile file)
        {
            byte[] pReadByte = new byte[0];

            var pFileStream = file.OpenReadStream();

            BinaryReader r = new BinaryReader(pFileStream);
            r.BaseStream.Seek(0, SeekOrigin.Begin);    //将文件指针设置到文件开
            pReadByte = r.ReadBytes((int)r.BaseStream.Length);

            TransferUploadObjectModel m = new TransferUploadObjectModel(_db);
            /// 高级接口上传对象
            var result = await m.TransferUploadFile(new FileInputInfoDto()
            {
                Directory = "goods",
                FileExtension = Path.GetExtension(file.FileName).Replace(".", ""),
                Method = "PUT",
            }, pReadByte);
            return result;
        }

        public FileOutInfoDto GetCosRequestSignURL(FileInputInfoDto inputDto)
        {

            return GetPresignUploadUrl(inputDto);
        }
        private 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 + Companycheck.Code + "/";
            }
            DateTime dt = DateTime.Now;
            baseUrl = baseUrl + inputDto.Directory + "/" + dt.ToFileTime().ToString() + "." + inputDto.FileExtension;
            try
            { 
                PreSignatureStruct preSignatureStruct = new PreSignatureStruct();
                preSignatureStruct.appid = cosConfig.AppId;//腾讯云账号 APPID
                preSignatureStruct.region = cosConfig.Region; //存储桶地域
                preSignatureStruct.bucket = cosConfig.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;
        }
    }
}
