package com.xy.utils;

import cn.hutool.system.SystemUtil;
import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.PutObjectResult;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 拓元算法有效期商品链接下载并转换到喵星人自己的oss上。由于拓元的barcode唯一使用barcode命名图片
 *
 * @author 谭斌
 * @date 2023/11/13
 */
public class TyImgUrlConvert {

    public static void main(String[] args) throws Exception {
        upload();
    }

    public static void upload() throws InterruptedException, IOException {
        // 初始化OSS
        OSS ossClient = new OSSClient("oss-cn-beijing.aliyuncs.com",
                new DefaultCredentialProvider("LTAI5tKyfiX3LT2PENxrax6a", "QDpoLnUek0e0DE613mECgIirDExW89"),
                new ClientConfiguration());
        // 读取Excel
        XSSFWorkbook workbook;
        if (!SystemUtil.getOsInfo().isLinux()) {
            workbook = new XSSFWorkbook("D:\\tyGoods.xlsx");
        } else {
            InputStream inputStream = IoUtils.inputStream("tyGoods.xlsx").get();
            workbook = new XSSFWorkbook(inputStream);

        }

        XSSFSheet sheet = workbook.getSheetAt(0);

        // 创建线程池
        ExecutorService executor = Executors.newFixedThreadPool(20);

        // 遍历每一行数据
        for (Row row : sheet) {
            if (row.getRowNum() == 0) { // 跳过表头
                continue;
            }

            Cell barcodeCell = row.getCell(0);
            Cell urlCell = row.getCell(1);

            if (barcodeCell == null || urlCell == null) {
                continue;
            }

            String barcode = barcodeCell.getStringCellValue();
            String url = urlCell.getStringCellValue();
            String bucketName = "mxrnetfiles";
            // 下载并上传图片到阿里云对象存储
            Future<String> future = executor.submit(() -> {
                try {
                    // 下载图片
                    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
                    connection.setRequestMethod("GET");
                    connection.connect();
                    BufferedImage image = ImageIO.read(connection.getInputStream());

                    // 上传图片到阿里云对象存储
                    File tempFile = File.createTempFile("image", ".png");
                    FileOutputStream fos = new FileOutputStream(tempFile);
                    ImageIO.write(image, "png", fos);
                    fos.close();
                    String fileUrl = "tyGoods/" + barcode + ".png";
                    PutObjectResult result = ossClient.putObject(bucketName, fileUrl, tempFile);
                    // 设置权限(公开读)
                    ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
                    if (result != null) {
//                        https://cdn.ossfile.mxrvending.com/tyGoods/6948960111210.png
                        System.out.println("------OSS文件上传成功------ " + fileUrl);
                    }
                    tempFile.delete();

                    return "OK";
                } catch (IOException e) {
                    e.printStackTrace();
                    return "ERROR";
                }
            });

            // 等待所有任务完成
            while (!future.isDone()) {
                Thread.sleep(100);
            }
        }
        // 关闭线程池
        executor.shutdown();
    }
}
