package com.fs.qw.utils;

import com.alibaba.fastjson.JSON;
import com.fs.common.utils.BASE64ToMultipartFile;
import com.fs.common.utils.sign.Base64Utils;
import com.fs.qw.config.QwConfig;
import com.fs.system.oss.CloudStorageService;
import com.fs.system.oss.OSSFactory;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Map;
import java.util.UUID;

@SuppressWarnings("all")
public class QwDownloadUtil {

    private static final String BASE64_IMAGE = "data:image/png;base64,%s";

    public static byte[] cdnDownload(Map<String,Object> map,String deviceId){
        return QwDownloadUtil.sendQwHttp(QwConfig.CDN_DOWNLOAD,map,deviceId);
    }
    public static String cdnDownloadBase64(Map<String,Object> map,String deviceId){
        return QwDownloadUtil.sendQwHttpBase64(QwConfig.CDN_DOWNLOAD,map,deviceId);
    }


    public static byte[] sendQwHttp(String url , Map<String,Object> map , String deviceId){
        String json = JSON.toJSONString(map);
        String token = DigestUtils.md5Hex(QwConfig.APP_KEY+QwConfig.APP_SECRET+QwConfig.TRACE_ID+deviceId);
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
        httpPost.setHeader("Connection", "Keep-Alive");
        httpPost.setHeader("X-Trace-Id",QwConfig.TRACE_ID);
        httpPost.setHeader("X-Device-Id", deviceId);
        httpPost.setHeader("X-App-Key", QwConfig.APP_KEY);
        httpPost.setHeader("X-Token", token);
        StringEntity requestEntity = new StringEntity(json, "UTF-8");
        httpPost.setEntity(requestEntity);
        return  sendHttp(httpPost);
    }


    public static String sendQwHttpBase64(String url , Map<String,Object> map , String deviceId){
        String json = JSON.toJSONString(map);
        String token = DigestUtils.md5Hex(QwConfig.APP_KEY+QwConfig.APP_SECRET+QwConfig.TRACE_ID+deviceId);
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
        httpPost.setHeader("Connection", "Keep-Alive");
        httpPost.setHeader("X-Trace-Id",QwConfig.TRACE_ID);
        httpPost.setHeader("X-Device-Id", deviceId);
        httpPost.setHeader("X-App-Key", QwConfig.APP_KEY);
        httpPost.setHeader("X-Token", token);
        StringEntity requestEntity = new StringEntity(json, "UTF-8");
        httpPost.setEntity(requestEntity);
        return  sendHttpBase64(httpPost);

    }

    public static byte[] sendHttp( HttpPost httpPost){
        // 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 发送请求，获取响应
        try {
            CloseableHttpResponse response = httpClient.execute(httpPost);
            // 获取响应实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream inputStream = entity.getContent();
                // 将二进制文件流转换为 Base64 字符串
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                outputStream.close();
                byte[] fileBytes = outputStream.toByteArray();
//                String fileName = UUID.randomUUID().toString().replaceAll("-", "");
//                CloudStorageService storage = OSSFactory.build();
//                String url = storage.uploadSuffix(fileBytes, fileName);
                return fileBytes;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    public static String sendHttpBase64( HttpPost httpPost){
        // 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 发送请求，获取响应
        try {
            CloseableHttpResponse response = httpClient.execute(httpPost);
            // 获取响应实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream inputStream = entity.getContent();
                // 将二进制文件流转换为 Base64 字符串
                String base64String = Base64Utils.inputStream2Base64(inputStream);
                return String.format(BASE64_IMAGE, base64String);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    public static MultipartFile base64ToMultipart(String base64) {
        try {
            String[] baseStrs = base64.split(",");

            BASE64Decoder decoder = new BASE64Decoder();
            byte[] b = new byte[0];
            b = decoder.decodeBuffer(baseStrs[1]);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            return new BASE64ToMultipartFile(b, baseStrs[0]);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String generateDownloadLink(byte[] fileData, String fileName) throws IOException {
        // 生成一个唯一的文件名
        String uniqueFileName = UUID.randomUUID().toString();

        // 将字节数组写入临时文件
        Path tempFilePath = Files.createTempFile(uniqueFileName, fileName);
        Files.write(tempFilePath, fileData, StandardOpenOption.CREATE);

        // 返回临时文件的下载链接
        return tempFilePath.toUri().toString();
    }

}
