package com.fs.qw.utils;


import com.alibaba.fastjson.JSON;
import com.fs.common.exception.file.OssException;
import com.fs.qw.config.QwConfig;



import com.fs.qw.domain.*;
import okhttp3.*;
import org.apache.commons.codec.digest.DigestUtils;

import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;



@SuppressWarnings("all")
public class QwUploadUtil {
//    @Autowired
//    QwUrlConfig qwUrlConfig;

    public static QwCDNFileInfo uploads(MultipartFile file, String deviceId) throws Exception{
        if (file.isEmpty())
        {
            throw new OssException("上传文件不能为空");
        }
        QwUpload qwUpload = new QwUpload();
        qwUpload.setFile(file);
        String contentType = file.getContentType(); // 获取文件的MIME类型
        String extension = getFileExtension(file.getOriginalFilename()); // 获取文件的扩展名
        if (isImage(contentType, extension)) {
            // 文件是图片
            qwUpload.setFileType(2);
        } else if (isVideo(contentType, extension)) {
            // 文件是视频
            qwUpload.setFileType(4);
        } else if (isVoice(contentType, extension)){
            // 文件是音频类型
            qwUpload.setFileType(6);
        }else {
            //文件是file类型
            qwUpload.setFileType(5);
        }
        qwUpload.setFileSize(file.getSize());
        //上传cdn返回cdn参数
        String data = upload(QwConfig.CDN_UPLOAD,qwUpload,deviceId);
        QwCDNFileInfo qwCDNFileInfo = JSON.parseObject(data, QwCDNFileInfo.class);
//        String fileName = file.getOriginalFilename();
//        String suffix = fileName.substring(fileName.lastIndexOf("."));
//        CloudStorageService storage = OSSFactory.build();
//        String url = storage.uploadSuffix(file.getBytes(), suffix);
        qwCDNFileInfo.setFileType(qwUpload.getFileType());
//        qwMaterial.setUrl(url);
//        qwMaterial.setFileName(fileName);
        return qwCDNFileInfo;
    }

    public static String sendPostToUpload(String url, QwUpload qwUpload, String deviceId) throws Exception {
        // 创建 OkHttpClient 实例
        OkHttpClient client = new OkHttpClient();
        String token = DigestUtils.md5Hex(QwConfig.APP_KEY+QwConfig.APP_SECRET+QwConfig.TRACE_ID+deviceId);

        // 创建 MultipartBody.Builder 实例
        MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("fileType", qwUpload.getFileType().toString())
                .addFormDataPart("fileSize", qwUpload.getFileSize().toString());

        // 添加文件
        RequestBody fileBody = RequestBody.create(MediaType.parse(qwUpload.getFile().getContentType()), qwUpload.getFile().getBytes());
        multipartBodyBuilder.addFormDataPart("file", qwUpload.getFile().getOriginalFilename(), fileBody);

        // 构建 MultipartBody
        MultipartBody multipartBody = multipartBodyBuilder.build();

        // 创建 Request 实例
        Request request = new Request.Builder()
                .url(url)
                .post(multipartBody)
                .header("Content-Type","multipart/form-data")
                .header("X-Trace-Id", QwConfig.TRACE_ID)
                .header("X-Device-Id", deviceId)
                .header("X-App-Key", QwConfig.APP_KEY)
                .header("X-Token", token)
                .build();

        // 执行请求并获取响应
        Response response = client.newCall(request).execute();
        String responseText = "";
        if (response.body() != null) {
            responseText = response.body().string();
        }
        if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
        } else {
            // 处理响应
            return responseText;
        }

    }

    public static String upload(String url, QwUpload qwUpload, String deviceId) throws Exception{
        String json = sendPostToUpload(url, qwUpload, deviceId);
        QwRestful qwRestful = JSON.parseObject(json,QwRestful.class);
        if ("0".equals(qwRestful.getCode())){
            return JSON.toJSONString(qwRestful.getData());
        }
        return null;
    }

    // 根据文件名获取文件的扩展名
    private static String getFileExtension(String filename) {
        if (filename.contains(".")) {
            return filename.substring(filename.lastIndexOf(".") + 1);
        }
        return "";
    }

    // 判断文件是否为图片类型
    private static boolean isImage(String contentType, String extension) {
        return contentType != null && contentType.startsWith("image/") ||
                extension.equalsIgnoreCase("jpg") ||
                extension.equalsIgnoreCase("jpeg") ||
                extension.equalsIgnoreCase("png") ||
                extension.equalsIgnoreCase("gif") ||
                extension.equalsIgnoreCase("bmp");
    }

    // 判断文件是否为视频类型
    private static boolean isVideo(String contentType, String extension) {
        return contentType != null && contentType.startsWith("video/") ||
                extension.equalsIgnoreCase("mp4") ||
                extension.equalsIgnoreCase("avi") ||
                extension.equalsIgnoreCase("mov") ||
                extension.equalsIgnoreCase("mkv");
    }

    // 判断文件是否为音频类型
    private static boolean isVoice(String contentType, String extension) {
        return contentType != null && contentType.startsWith("audio/") ||
                extension.equalsIgnoreCase("mpeg");
    }



}
