package com.yihu.jw.file_upload;

import com.yihu.jw.restmodel.iot.common.UploadVO;
import com.yihu.jw.util.date.DateUtil;
import org.csource.common.MyException;
import org.springframework.util.Assert;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Random;
import java.util.Set;

/**
 * 多线程处理文件上传，有返回值的多线程
 */
public class FileUploadRunnable implements Runnable {

    /**
     * 上传文件模板类
     */
    private UploadVO uploadVO;

    /**
     * 微信文件流id，从微信把文件下载下来
     */
    private Set<String> wxMediaIdSet;

    private FileUploadService fileUploadService;

    private String  fastdfsUrl;

    private FileUploadCallback callback;

    /**
     * 微信文件流id，从微信把文件下载下来
     */
    private String accessToken;

    public FileUploadRunnable(Set<String> wxMediaIdSet, String accessToken, FileUploadService fileUploadService, String fastdfsUrl, FileUploadCallback callback){
        this.wxMediaIdSet = wxMediaIdSet;
        this.accessToken = accessToken;
        this.fileUploadService = fileUploadService;
        this.fastdfsUrl = fastdfsUrl;
        this.callback = callback;
    }


    @Override
    public void run() {
        Assert.notNull(wxMediaIdSet,"微信文件流id不可为空！");
        StringBuilder photoUrl = new StringBuilder();
        wxMediaIdSet.forEach( one -> {
            InputStream inputStream = getInputStream(one);
            // 重命名文件
            String newFileName = DateUtil.dateToStr(new Date(), DateUtil.YYYYMMDDHHMMSS) + "_" + new Random().nextInt(1000) + ".png";
            try {
                UploadVO uploadVO = fileUploadService.uploadImg(inputStream,newFileName,0,fastdfsUrl);
                photoUrl.append(uploadVO.getFullUrl()).append(",");
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (MyException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        callback.callback(photoUrl.toString());
    }

    /**
     * 下载多媒体文件（请注意，视频文件不支持下载，调用该接口需http协议）
     *
     * @return
     */
    public InputStream getInputStream(String mediaId) {
        InputStream is = null;
        String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + accessToken + "&media_id=" + mediaId;
        try {
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
            http.setRequestMethod("GET"); // 必须是get方式请求
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
            http.connect();
            // 获取文件转化为byte流
            is = http.getInputStream();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return is;
    }

}
