package org.dromara.web.utils;

import cn.hutool.core.codec.Base64;
import com.tencent.cloud.CosStsClient;
import com.tencent.cloud.Policy;
import com.tencent.cloud.Response;
import com.tencent.cloud.Statement;
import com.tencent.cloud.cos.util.Jackson;
import com.tencentcloudapi.common.AbstractModel;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.ims.v20201229.ImsClient;
import com.tencentcloudapi.ims.v20201229.models.ImageModerationRequest;
import com.tencentcloudapi.ims.v20201229.models.ImageModerationResponse;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import com.tencentcloudapi.tms.v20201229.TmsClient;
import com.tencentcloudapi.tms.v20201229.models.TextModerationRequest;
import com.tencentcloudapi.tms.v20201229.models.TextModerationResponse;

import java.util.TreeMap;


/**
 * 腾讯云工具类
 * @author Maosw
 */
public class TxApiSdkUtils
{

    private static final String SMS_SECRET_ID = "AKIDMcmoeNr64nIpicWBYeU6TaR8h280uyAF";

    private static final String SMS_SECRET_KEY = "yg8JEzVmriLjtqZ3KURUIrDRQ9euxmbI";

    /**
     * 获取上传临时密钥
     */
    public void getCredential() {
        TreeMap<String, Object> config = new TreeMap<String, Object>();
        try {
            //这里的 SecretId 和 SecretKey 代表了用于申请临时密钥的永久身份（主账号、子账号等），子账号需要具有操作存储桶的权限。
            String secretId = System.getenv(SMS_SECRET_ID);
            String secretKey = System.getenv(SMS_SECRET_KEY);
            // 替换为您的云 api 密钥 SecretId
            config.put("secretId", secretId);
            // 替换为您的云 api 密钥 SecretKey
            config.put("secretKey", secretKey);
            // 初始化 policy
            Policy policy = new Policy();
            // 临时密钥有效时长，单位是秒，默认 1800 秒，目前主账号最长 2 小时（即 7200 秒），子账号最长 36 小时（即 129600）秒
            config.put("durationSeconds", 1800);
            // 换成您的 bucket
            config.put("bucket", "examplebucket-1250000000");
            // 换成 bucket 所在地区
            config.put("region", "ap-shanghai");

            // 开始构建一条 statement
            Statement statement = new Statement();
            // 声明设置的结果是允许操作
            statement.setEffect("allow");
            statement.addActions(new String[]{
                    "cos:PutObject",
                    // 表单上传、小程序上传
                    "cos:PostObject",
                    // 分块上传
                    "cos:InitiateMultipartUpload",
                    "cos:ListMultipartUploads",
                    "cos:ListParts",
                    "cos:UploadPart",
                    "cos:CompleteMultipartUpload",
                    // 处理相关接口一般为数据万象产品 权限中以ci开头
                    // 创建媒体处理任务
                    "ci:CreateMediaJobs",
                    // 文件压缩
                    "ci:CreateFileProcessJobs"
            });

            statement.addResources(new String[]{
                    "qcs::cos:ap-chongqing:uid/1250000000:examplebucket-1250000000/*",
                    "qcs::ci:ap-chongqing:uid/1250000000:bucket/examplebucket-1250000000/*"});

            // 把一条 statement 添加到 policy 可以添加多条
            policy.addStatement(statement);
            // 将 Policy 示例转化成 String，可以使用任何 json 转化方式，这里是本 SDK 自带的推荐方式
            config.put("policy", Jackson.toJsonPrettyString(policy));
            Response response = CosStsClient.getCredential(config);
        } catch (Exception e) {
            throw new IllegalArgumentException("no valid secret !");
        }
    }

    /**
     * 腾讯云文件安全检测
     * @param content
     * @return
     */
    public static String checkContext(String content){
        try{
            Credential cred = new Credential(SMS_SECRET_ID, SMS_SECRET_KEY);
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("tms.ap-shanghai.tencentcloudapi.com");
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            TmsClient client = new TmsClient(cred, "ap-shanghai", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            TextModerationRequest req = new TextModerationRequest();

            String str = Base64.encode(content);
            req.setContent(str);
            // 返回的resp是一个TextModerationResponse的实例，与请求对象对应
            TextModerationResponse resp = client.TextModeration(req);
            // 输出json格式的字符串回包
            return AbstractModel.toJsonString(resp);
        } catch (TencentCloudSDKException e) {
            throw new IllegalArgumentException("文件检测接口异常");
        }
    }


    /**
     * 腾讯云图片安全检测
     * @param imgUrl
     * @return
     */
    public static String checkImages(String imgUrl){
        try{
            Credential cred = new Credential(SMS_SECRET_ID, SMS_SECRET_KEY);
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("ims.ap-shanghai.tencentcloudapi.com");
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            ImsClient client = new ImsClient(cred, "ap-shanghai", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象jkighjkhgkhgkhgjhghkjj
            ImageModerationRequest req = new ImageModerationRequest();
            req.setFileUrl(imgUrl);
            // 返回的resp是一个ImageModerationResponse的实例，与请求对象对应
            ImageModerationResponse resp = client.ImageModeration(req);
            // 输出json格式的字符串回包
            return AbstractModel.toJsonString(resp);
        } catch (TencentCloudSDKException e) {
            throw new IllegalArgumentException("文件检测接口异常");
        }
    }


    /**
     * 腾讯云发送短信
     * @param phoneNumber
     * @param code
     * @return
     */
    public static String sendSmsMsg(String phoneNumber, String code){
        try{
            Credential cred = new Credential(SMS_SECRET_ID, SMS_SECRET_KEY);
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("sms.tencentcloudapi.com");
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            SmsClient client = new SmsClient(cred, "ap-nanjing", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            SendSmsRequest req = new SendSmsRequest();

            String[] phoneNumberSet1 = {phoneNumber};
            req.setPhoneNumberSet(phoneNumberSet1);
            req.setSmsSdkAppId("1400926380");
            req.setTemplateId("2222045");
            req.setSignName("合肥小图科技");

            String[] templateParamSet1 = {code};
            req.setTemplateParamSet(templateParamSet1);

            // 返回的resp是一个SendSmsResponse的实例，与请求对象对应
            SendSmsResponse resp = client.SendSms(req);
            // 输出json格式的字符串回包
            return AbstractModel.toJsonString(resp);
        } catch (TencentCloudSDKException e) {
            throw new IllegalArgumentException("短信接口异常");
        }
    }

}
