package com.ruoyi.system.config;

import cn.hutool.core.util.IdUtil;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.teaopenapi.models.Config;
import com.aliyuncs.exceptions.ClientException;
import com.ruoyi.common.constant.AliKeyConfig;
import com.ruoyi.common.core.domain.entity.ShopUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import static com.alibaba.fastjson2.JSONObject.toJSONString;

public class AliConfig {



    private static final Logger log = LoggerFactory.getLogger(AliConfig.class);
    public static Client createClient() {
        Config config = new Config()
                // 配置 AccessKey ID，请确保代码运行环境配置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId(AliKeyConfig.ACCESS_KEY_ID)
                // 配置 AccessKey Secret，请确保代码运行环境配置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret(AliKeyConfig.ACCESS_KEY_SECRET);
        // System.getenv()方法表示获取系统环境变量，不要直接在getenv()中填入AccessKey信息。

        // 配置 Endpoint。中国站请使用dysmsapi.aliyuncs.com
        config.endpoint = "dysmsapi.aliyuncs.com";

        try {
            return new Client(config);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        ShopUser shopUser = new ShopUser();
        shopUser.setPhone("13943965645");
        shopUser.setCode("123456");
        sendMsg(shopUser);
    }

    public static String sendMsg(ShopUser shopUser) {
        // 初始化请求客户端
        Client client = AliConfig.createClient();

        // 1. 生成6位验证码
        String code = String.valueOf((int)((Math.random()*9+1)*100000));

        //String templateParam = "{\"name\":\"" + shopUser.getUsername() + "\",\"number\":\""+ shopUser.getPhone() +"\"}";

        String templateParam = "{'code':"+ code + "}";

        // 构造API请求对象，请替换请求参数值
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(shopUser.getPhone())
                .setSignName("北京盛兴平商贸")
                .setTemplateCode("SMS_323405385")
                .setTemplateParam(templateParam); // TemplateParam为序列化后的JSON字符串。

        // 获取响应对象
        SendSmsResponse sendSmsResponse;
        try {
            sendSmsResponse = client.sendSms(sendSmsRequest);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        log.info("aliyun 发送验证码返回信息：{}", toJSONString(sendSmsResponse));

        if (sendSmsResponse.getStatusCode() == 200){
            return code;
        }
        return null;
    }


    public static String ossUp(String objectName,String fileName, InputStream inputStream){
        // 配置参数
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        String accessKeyId = AliKeyConfig.ACCESS_KEY_ID;
        String accessKeySecret = AliKeyConfig.ACCESS_KEY_SECRET;
        String bucketName = "wenzhuangmusic";

        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String path = objectName + IdUtil.fastUUID() + suffix;
        try {
            // 上传字符串内容作为文件
            ossClient.putObject(bucketName, path, inputStream);
            System.out.println("文件上传成功：" + objectName);
            return "/file/download/"+path;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭OSSClient
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }


    public static byte[] ossDown(String objectName) {
        // 配置参数
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        String accessKeyId = AliKeyConfig.ACCESS_KEY_ID;
        String accessKeySecret = AliKeyConfig.ACCESS_KEY_SECRET;
        String bucketName = "wenzhuangmusic";

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            // ossObject包含文件所在的存储空间名称、文件名称、文件元数据以及一个输入流。
            OSSObject ossObject = ossClient.getObject(bucketName, objectName);
            InputStream inputStream = ossObject.getObjectContent();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            // 读取文件内容到字节数组。
            byte[] readBuffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(readBuffer)) != -1) {
                byteArrayOutputStream.write(readBuffer, 0, bytesRead);
            }
            // 获取最终的字节数组。
            byte[] fileBytes = byteArrayOutputStream.toByteArray();
            // 数据读取完成后，获取的流必须关闭，否则会造成连接泄漏，导致请求无连接可用，程序无法正常工作。
            inputStream.close();
            byteArrayOutputStream.close();
            // ossObject对象使用完毕后必须关闭，否则会造成连接泄漏，导致请求无连接可用，程序无法正常工作。
            ossObject.close();
            return fileBytes;
        } catch (OSSException oe) {
            oe.printStackTrace();
        } catch (Throwable ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }

}
