package com.malk.mc.service.impl;

import com.alibaba.fastjson.JSON;
import com.malk.mc.service.McRequestService;
import com.malk.server.common.VenR;
import com.malk.server.dingtalk.DDR_New;
import com.malk.service.dingtalk.DDClient;
import com.malk.utils.UtilHttp;

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

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Service
public class McRequestServiceImpl implements McRequestService {
    @Autowired
    private DDClient ddClient;

    @Override
    public Map get(String url, Map headers, Map params) {
        Map map = (Map) JSON.parse(UtilHttp.doGet(url, headers, params));
        return map;
    }

    @Override
    public Map post(String url, Map headers, Map params, Map body) {
        Map map = (Map) JSON.parse(UtilHttp.doPost(url, headers, params, body));
        return map;
    }

    @Override
    public String downloadFile(String ydUrl, Map headers, Map params, String fileName,String downloadPath) {
        try {
            String fileUrl = ((DDR_New) UtilHttp.doGet(ydUrl, headers, params, DDR_New.class)).getResult().toString();

            URL url = new URL(fileUrl);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            int responseCode = httpConn.getResponseCode();

            // 检查HTTP响应代码是否为200
            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = httpConn.getInputStream();
                FileOutputStream outputStream = new FileOutputStream(downloadPath + fileName);

                byte[] buffer = new byte[4096];
                int bytesRead = -1;

                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }

                outputStream.close();
                inputStream.close();
            } else {
                System.out.println("无法下载文件。HTTP响应代码: " + responseCode);
            }
            httpConn.disconnect();


            int lastIndex = downloadPath.lastIndexOf("/");
            int secondLastIndex = downloadPath.lastIndexOf("/",lastIndex-1);
            String path = downloadPath.substring(secondLastIndex);//  /lingmingguangzi/

            String downloadUrl = "https://mc.cloudpure.cn/mjs" + path + fileName;
            return downloadUrl;
        }catch (Exception e){
            return "";
        }
    }
}
