package com.yunzhi.marketing.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class VideoThreadDownLoad {
    public static final Logger LOG = LoggerFactory.getLogger(VideoThreadDownLoad.class);
    /**
     * 线程下载成功标志
     */
    private static int flag = 0;

    /**
     * 本地文件
     */
    private MultipartFile uploadFile;

    /**
     * 本地路径
     */
    private String localPath;

    /**
     * 线程计数同步辅助
     */
    private CountDownLatch latch;

    private final int THREAD_POOL_CORE_SIZE= 10;
    private final int THREAD_POOL_MAX_CORE_SIZE=30;
    private final int THREAD_POOL_KEEP_ALIVE_TIME=60;

    // 定长线程池
    private ThreadPoolExecutor threadPool = new ThreadPoolExecutor(THREAD_POOL_CORE_SIZE,THREAD_POOL_MAX_CORE_SIZE,THREAD_POOL_KEEP_ALIVE_TIME, TimeUnit.SECONDS,new LinkedBlockingDeque<>());

    public VideoThreadDownLoad(MultipartFile uploadFile, String localPath) {
        this.uploadFile = uploadFile;
        this.localPath = localPath;
    }

    public synchronized static void downLoad(MultipartFile uploadFile, String localPath) {
        LOG.info("文件开始下载，下载位置为{}",localPath);
        ReentrantLock lock = new ReentrantLock();
        lock.lock();
        VideoThreadDownLoad videoThreadDownLoad = new VideoThreadDownLoad(uploadFile,localPath);
        long startTime = System.currentTimeMillis();
        boolean flag = false;
        try {
            flag = videoThreadDownLoad.executeDownLoad();
            long endTime = System.currentTimeMillis();
            if (flag) {
                LOG.info("文件下载成功,共耗时" + (endTime - startTime) / 1000 + "s");
            }
        } catch (Exception ex) {
            LOG.error(ex.getMessage());
        } finally {
            VideoThreadDownLoad.flag = 0; // 重置 下载状态
            if (!flag) {
                LOG.info("文件下载失败,本地文件已经删除。");
                File file = new File(localPath);
                file.delete();
            }
            lock.unlock();
        }
    }

    /**
     * 下载操作
     * @return
     */
    public boolean executeDownLoad() {
        try {
            //服务器返回的数据的长度，实际上就是文件的长度,单位是字节
            long length = uploadFile.getSize();

            LOG.info("文件总长度:" + length + "字节(B)");
            RandomAccessFile raf = new RandomAccessFile(localPath, "rwd");
            //指定创建的文件的长度
            raf.setLength(length);
            raf.close();
            //分割文件
            int partCount = getPartCount(length);
            int partSize = (int)(length / partCount);
            latch = new CountDownLatch(partCount);
            for (int threadId = 1; threadId <= partCount; threadId++) {
                // 每一个线程下载的开始位置
                long startIndex = (threadId - 1) * partSize;
                // 每一个线程下载的开始位置
                long endIndex = startIndex + partSize - 1;
                if (threadId == partCount) {
                    //最后一个线程下载的长度稍微长一点
                    endIndex = length;
                }
                LOG.info("线程" + threadId + "下载:" + startIndex + "字节~" + endIndex + "字节");
                threadPool.execute(new DownLoadThread(threadId, startIndex, endIndex, latch));
            }
            latch.await();
            if(flag == 0){
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOG.error("文件下载失败,失败原因：{}", e.getMessage());
        }
        return false;
    }

    /**
     * 计算分割多少文件比较合适
     * @param length
     * @return
     */
    private int getPartCount(long length) {
        // 十兆划分文件
        int size = (int) (length / 10485760);
        return size + 1;
    }

    /**
     * 内部类用于实现下载
     */
    public class DownLoadThread implements Runnable {

        /**
         * 线程ID
         */
        private int threadId;
        /**
         * 下载起始位置
         */
        private long startIndex;
        /**
         * 下载结束位置
         */
        private long endIndex;

        private CountDownLatch latch;

        public DownLoadThread(int threadId, long startIndex, long endIndex, CountDownLatch latch) {
            this.threadId = threadId;
            this.startIndex = startIndex;
            this.endIndex = endIndex;
            this.latch = latch;
        }

        @Override
        public void run() {
            try {
                LOG.info("线程" + threadId + "开始下载中:" + startIndex + "字节~" + endIndex + "字节");
                InputStream is = uploadFile.getInputStream();//返回资源
                RandomAccessFile raf = new RandomAccessFile(localPath, "rwd");
                raf.seek(startIndex);//定位文件
                int len = 0;
                byte[] buffer = new byte[1024];
                while ((len = is.read(buffer)) != -1) {
                    raf.write(buffer, 0, len);
                }
                is.close();
                raf.close();
            } catch (Exception e) {
                //线程下载出错
                VideoThreadDownLoad.flag = 1;
                LOG.error(e.getMessage());
            } finally {
                //计数值减一
                latch.countDown();
            }

        }
    }
}
