package com.ruoyi.framework.obs;

import cn.hutool.core.util.IdUtil;
import com.obs.services.ObsClient;
import com.obs.services.ObsConfiguration;
import com.obs.services.exception.ObsException;
import com.obs.services.model.ObsObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class ObsService {

    @Value("${huawei.obs.ak}")
    private String ak;

    @Value("${huawei.obs.sk}")
    private String sk;

    @Value("${huawei.obs.upload.endPoint}")
    private String endPoint;

    @Value("${huawei.obs.bucketName}")
    private String bucketName;

    @Value("${huawei.obs.access.endPoint}")
    private String accessEndPoint;

    private final String objectKey = "file/";

    //objectKey就是文件名，如果桶中有文件夹的话，如往test文件上传test.txt文件，那么objectKey就是test/test.txt
    public Map<String, Object> uploadFile(MultipartFile file) throws Exception {
        ObsClient obsClient = new ObsClient(ak, sk, endPoint);
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        String fileName = IdUtil.fastSimpleUUID() + "." + suffix;
        InputStream inputStream = file.getInputStream();
        obsClient.putObject(bucketName, objectKey + fileName, inputStream);
        inputStream.close();
        obsClient.close();
        Map map = new HashMap();
        map.put("url", accessEndPoint + "/" + objectKey + fileName);
        map.put("objectKey", objectKey + fileName);
        map.put("fileName", file.getOriginalFilename());
        return map;
    }

    /**
     * 下载文件, 中文名
     * @param file
     * @return
     * @throws Exception
     */
    public Map<String, Object> uploadFileX(MultipartFile file) throws Exception {
        ObsClient obsClient = new ObsClient(ak, sk, endPoint);
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        String fileName = IdUtil.fastSimpleUUID() + "." + suffix;
        InputStream inputStream = file.getInputStream();
        obsClient.putObject(bucketName, objectKey + fileName + "&&&" + file.getOriginalFilename(), inputStream);
        inputStream.close();
        obsClient.close();
        Map map = new HashMap();
        map.put("url", accessEndPoint + "/" + objectKey + fileName + "&&&" + file.getOriginalFilename());
        map.put("objectKey", objectKey + fileName + "&&&" + file.getOriginalFilename());
        map.put("fileName", file.getOriginalFilename());
        return map;
    }

    @Async
    public void deleteFiles(List<String> list) {
        list.forEach(x -> {
            try {
                deleteFile(objectKey + x.substring(x.lastIndexOf("/") + 1));
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    public void deleteFile(String objectKey) throws Exception {
        ObsClient obsClient = new ObsClient(ak, sk, endPoint);
        obsClient.deleteObject(bucketName, objectKey);
        obsClient.close();
    }

    public void download(String localFilePath, String fileName) throws ObsException, IOException {
        ObsConfiguration config = new ObsConfiguration();
        config.setSocketTimeout(30000);
        config.setConnectionTimeout(10000);
        config.setEndPoint(endPoint);
        ObsClient obsClient = null;
        try {
            obsClient = new ObsClient(ak, sk, config);
            System.out.println("Create a new bucket for demo\n");
//            obsClient.createBucket(bucketName);
            System.out.println("Uploading a new object to OBS from a file\n");
//            obsClient.putObject(bucketName, objectKey, createSampleFile());
            System.out.println("Downloading an object\n");
            simpleDownload(obsClient);
            File localFile = new File(localFilePath);
            if (!localFile.getParentFile().exists()) {
                localFile.getParentFile().mkdirs();
            }
            System.out.println("Downloading an object to file:" + localFilePath + "\n");
            downloadToLocalFile(obsClient, localFilePath, fileName);
            System.out.println("Deleting object  " + objectKey + "\n");
//            obsClient.deleteObject(bucketName, objectKey, null);

        } catch (ObsException e) {
            System.out.println("Response Code: " + e.getResponseCode());
            System.out.println("Error Message: " + e.getErrorMessage());
            System.out.println("Error Code:       " + e.getErrorCode());
            System.out.println("Request ID:      " + e.getErrorRequestId());
            System.out.println("Host ID:           " + e.getErrorHostId());
        } finally {
            if (obsClient != null) {
                try {
                    /*
                     * Close obs client
                     */
                    obsClient.close();
                } catch (IOException e) {
                }
            }
        }
    }

    private void simpleDownload(ObsClient obsClient) throws ObsException, IOException {
        ObsObject obsObject = obsClient.getObject(bucketName, objectKey, null);
        displayTextInputStream(obsObject.getObjectContent());
    }

    private void displayTextInputStream(InputStream input) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(input));
        while (true) {
            String line = reader.readLine();
            if (line == null)
                break;

            System.out.println("\t" + line);
        }
        System.out.println();

        reader.close();
    }

    private void downloadToLocalFile(ObsClient obsClient, String localFilePath, String fileName) throws ObsException, IOException {
        String key = objectKey + fileName;
        ObsObject obsObject = obsClient.getObject(bucketName, key, null);
        if (!new File(localFilePath + "/" + fileName).exists()) {
            ReadableByteChannel rchannel = Channels.newChannel(obsObject.getObjectContent());
            ByteBuffer buffer = ByteBuffer.allocate(4096);
            WritableByteChannel wchannel = Channels.newChannel(new FileOutputStream(new File(localFilePath + "/" + fileName)));
            System.out.println(localFilePath + "/" + fileName);
            while (rchannel.read(buffer) != -1) {
                buffer.flip();
                wchannel.write(buffer);
                buffer.clear();
            }
            rchannel.close();
            wchannel.close();
        }
    }

    private File createSampleFile() throws IOException {
        File file = File.createTempFile("obs-java-sdk-", ".txt");
        file.deleteOnExit();
        Writer writer = new OutputStreamWriter(new FileOutputStream(file));
        writer.write("abcdefghijklmnopqrstuvwxyz\n");
        writer.write("0123456789011234567890\n");
        writer.close();

        return file;
    }

}
