package com.moka.gdtauto.service;

import com.aliyun.oss.common.utils.BinaryUtil;
import com.moka.gdtauto.GdtAutoApplication;
import com.moka.gdtauto.entity.OssFile;
import com.moka.gdtauto.util.TencentFileMd5Util;

import org.springframework.beans.factory.annotation.Autowired;

import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * mvn test -Dtest=com.moka.gdtauto.service.OssFileMd5#testOssFileMd5 -Dspring.profiles.active=test
 */
@SpringBootTest(classes = GdtAutoApplication.class)
@ActiveProfiles("test")
public class OssFileMd5 {
    @Autowired
    private OssFileService ossFileService;

    @Test
    public void testOssFileMd5() {
        List<OssFile> ossFileList = ossFileService.lambdaQuery()
        .ge(OssFile::getId, 19).list();
        for (OssFile ossFile : ossFileList) {
            try {
                URL url = new URL(ossFile.getFileUrl());
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout(10000);
                connection.setReadTimeout(30000);
                connection.setRequestMethod("GET");
                connection.connect();

                int responseCode = connection.getResponseCode();
                if (responseCode != HttpURLConnection.HTTP_OK) {
                    throw new Exception("下载文件失败，HTTP状态码: " + responseCode);
                }

                try (java.io.InputStream inputStream = connection.getInputStream()) {
                    String md5 = TencentFileMd5Util.calculateMd5(inputStream);
                    ossFileService.lambdaUpdate()
                        .eq(OssFile::getId, ossFile.getId())
                        .set(OssFile::getFileMd5, md5).update();
                } finally {
                    connection.disconnect();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } 
        }
    }
}
