package com.ms.biz.tool;

import com.jinritemai.cloud.base.core.service.TosFactory;
import com.ms.biz.common.Ret;
import com.volcengine.tos.TOSV2;
import com.volcengine.tos.TOSV2ClientBuilder;
import com.volcengine.tos.TosException;
import com.volcengine.tos.model.object.*;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * 火山引擎的存储服务TOS
 */
@Slf4j
@Component
public class TosTemplate {

    @Value("${spring.tos.endpoint}")
    private String endpoint;

    @Value("${spring.tos.region}")
    private String region;

    @Value("${spring.tos.accessKey}")
    private String accessKey;

    @Value("${spring.tos.secretKey}")
    private String secretKey;

    @Value("${spring.tos.domain}")
    @Getter
    private String domain;

    @Getter
    private String bucket;

    private TOSV2 tosClient;

    public TOSV2 getClient() {
        if (!Objects.isNull(tosClient)) {
            return tosClient;
        }
        if (SystemTool.isDevEnv()) {
            tosClient = (new TOSV2ClientBuilder()).build(region, endpoint, accessKey, secretKey);
            bucket = "ddy-pub-dev";
        } else if (SystemTool.isTestEnv()) {
            tosClient = TosFactory.newTosClient();
            bucket = "miaofenxiao-file";
        } else if (SystemTool.isProdEnv()) {
            tosClient = TosFactory.newTosClient();
            bucket = "miaofenxiao-file-prod";
        }
        return tosClient;
    }

    /**
     * 上传文本到TOS
     * @param key
     * @param data
     * @return
     */
    public Ret upload(String key, String data) {
        TOSV2 tosClient = getClient();
        try {
            ByteArrayInputStream stream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8));
            PutObjectBasicInput basicInput = new PutObjectBasicInput().setBucket(getBucket()).setKey(key);
            PutObjectInput putObjectInput = new PutObjectInput().setPutObjectBasicInput(basicInput).setContent(stream);
            tosClient.putObject(putObjectInput);
            return CommonTool.successResult("url", domain + key);
        } catch (TosException e) {
            e.printStackTrace();
        }
        return CommonTool.failResult();
    }

    /**
     * 上传文件到TOS
     * @param key
     * @param data
     * @return
     */
    public Ret upload(String key, byte[] data) {
        TOSV2 tosClient = getClient();
        try {
            ByteArrayInputStream stream = new ByteArrayInputStream(data);
            PutObjectBasicInput basicInput = new PutObjectBasicInput().setBucket(getBucket()).setKey(key);
            PutObjectInput putObjectInput = new PutObjectInput().setPutObjectBasicInput(basicInput).setContent(stream);
            tosClient.putObject(putObjectInput);
            return CommonTool.successResult("url", domain + key);
        } catch (TosException e) {
            e.printStackTrace();
        }
        return CommonTool.failResult();
    }

    /**
     * 下载文件到内存
     * @param key
     * @return
     */
    public Ret download2Mem(String key) {
        TOSV2 tos = getClient();
        GetObjectV2Input input = new GetObjectV2Input().setBucket(getBucket()).setKey(key);
        try (GetObjectV2Output output = tos.getObject(input); BufferedReader reader = new BufferedReader(new InputStreamReader(output.getContent()))) {
            StringBuilder sb = new StringBuilder();
            String line = reader.readLine();
            while (line != null) {
                sb.append(line);
                line = reader.readLine();
            }
            return CommonTool.successResult("data", sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return CommonTool.failResult("存储数据获取失败:" + key);
    }

    /**
     * 下载文件到本地
     * @param key
     * @param filePath
     * @return
     */
    public Ret download2File(String key,String filePath){
        TOSV2 tos = getClient();
        try{
            // sdk有的方法点不出来，可能是版本问题
//            GetObjectToFileInput fileInput = new GetObjectToFileInput().setFilePath(filePath).setBucket(getBucket()).setKey(key);
//            GetObjectToFileOutput fileOutput = tos.getObjectToFile(fileInput);
//            if (fileOutput.getCustomMetadata()  != null) {
//                System.out.println("object has custom meta data.");
//                for (Map.Entry<String, String>  entry : fileOutput.getCustomMetadata().entrySet()) {
//                    System.out.println("custom meta key: " + entry.getKey()  + ", value: " + entry.getValue());
//                }
//            }
            return CommonTool.successResult();
        }  catch (Exception e) {
            e.printStackTrace();
            return CommonTool.failResult();
        }
    }

    /**
     * 删除文件
     * @param ossPath
     * @return
     */
    public Ret delete(String ossPath) {
        TOSV2 tos = getClient();
        try{
            DeleteObjectInput input = new DeleteObjectInput().setBucket(getBucket()).setKey(ossPath);
            DeleteObjectOutput output = tos.deleteObject(input);
            return CommonTool.successResult();
        }  catch (Exception e) {
            e.printStackTrace();
            return CommonTool.failResult();
        }
    }
}
