package cn.quantgroup.customer.service.impl;

import cn.quantgroup.customer.rest.vo.JsonResult;
import cn.quantgroup.customer.service.IFileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

/**
 * 文件流转发
 *
 * @author tao
 * @version 2020-09-30 17:28
 */
@Service
@Slf4j
public class FileServiceImpl implements IFileService {


    //随便写一个
    private static final String boundary = java.util.UUID.randomUUID().toString();

    @Override
    public BufferedInputStream getBufferedInputStream(Long loanId) throws Exception {

        HttpURLConnection con = (HttpURLConnection) new URL("").openConnection();
        // 设置是否向httpUrlConnection输出，因为这个是post请求，参数要放在
        // http正文内，因此需要设为true, 默认情况下是false;
        con.setDoOutput(true);
        // 设置是否从httpUrlConnection读入，默认情况下是true;
        con.setDoInput(true);
        // 设定请求的方法为"POST"，默认是GET
        con.setRequestMethod("POST");
        // Post 请求不能使用缓存
        con.setUseCaches(false);
        //设置接收返回值的格式
        con.setRequestProperty("Accept", "text/plain, */*");
        //设置接收编码
        con.setRequestProperty("Accept-Language", "zh-cn");
        con.setRequestProperty("Host", "127.0.0.1");
        //设置请求参数格式以及boundary分割线
        con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        con.setRequestProperty("User-Agent", " WinHttpClient");
        //开启长连接可以持续传输
        con.setRequestProperty("Connection", "Keep-Alive");
        //连接超时时间20秒
        con.setConnectTimeout(20000);
        //读取超时时间20秒
        con.setReadTimeout(20000);


        int responseCode = con.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            String fileName = "";
            try {
                fileName = con.getHeaderField(1).substring(21, con.getHeaderField(1).length() - 1);
                fileName = "EBDT" + fileName.split("_")[1];
                System.out.println(fileName);
            } catch (Exception e) {
                return null;
            }
            return new BufferedInputStream(con.getInputStream());
        }
        return null;
    }

    @Override
    public JsonResult outputFile(HttpServletResponse response, String fileName, byte[] file){
        if (ArrayUtils.isEmpty(file)) {
            log.info("get file download url failed.");
            return JsonResult.buildErrorStateResult("file is null");
        }
        // 设置相关头信息
        response.setContentType("multipart/form-data");
        try {
            fileName = URLEncoder.encode(fileName, "UTF8");
        } catch (UnsupportedEncodingException e) {
            log.error("fileName encode failed. errorMessage[{}]", e.getMessage());
            return JsonResult.buildErrorStateResult("fileName encode failed");
        }
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.addHeader("Pragma", "no-cache");
        response.addHeader("Cache-Control", "no-cache");
        response.addDateHeader("Expries", 0);
        // 返回文件
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            out.write(file);
            out.flush();
        } catch (IOException e) {
            log.error("download file failed. errorMessage[{}]", e.getMessage());
            return JsonResult.buildErrorStateResult("download file failed");
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    log.error("OutputStream close failed. errorMessage[{}]", e.getMessage());
                }
            }
        }
        return JsonResult.buildSuccessResult("ok",null);
    }
}
