package com.tax.file.service.async;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.tax.file.constants.CommonConstants;
import com.tax.file.mapper.FinInvoiceDetailMapper;
import com.tax.file.mapper.FinInvoiceMapper;
import com.tax.file.mapper.TkFileMapper;
import com.tax.file.model.FinInvoice;
import com.tax.file.model.FinInvoiceDetail;
import com.tax.file.model.TkFile;
import com.tax.file.model.TkFileExample;
import com.tax.file.service.api.FinInvoiceService;
import com.tax.file.utils.invoice.FileExcelReadUtil;
import com.yxcheng.tax.fs.minio.service.MinioTemplate;
import com.yxcheng.token.utils.StringUtil;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * @author breeze
 * @date 2019-09-02
 * <p>
 * 文件URL重置
 */
@Component
public class FileUrlResetTask {
    private static final Logger logger = LoggerFactory.getLogger(FileUrlResetTask.class);
    private ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
    
    @Autowired
    TkFileMapper tkFileMapper;
    
    @Autowired
	private MinioTemplate minioTemplate;
    
    public void urlReset() {
    	//1.查询待重置数据
    	List<TkFile> tkFiles = tkFileMapper.fileUrlReset();
    	int size = (tkFiles != null?tkFiles.size():0);
    	
    	while(size > 0){
        	//2.重新获取URL
        	Iterator<TkFile> iter = tkFiles.iterator();
        	List<Future<String>> taskResults = new ArrayList<Future<String>>();
        	while(iter.hasNext()){
        		TkFile tkFile = iter.next();
        		taskResults.add(process(tkFile));
        	}
        	
        	while (true) {
                boolean isAllDone = true;
                for (Future<String> taskResult : taskResults) {
                    isAllDone &= (taskResult.isDone() || taskResult.isCancelled());
                }
                if (isAllDone) {
                    // 任务都执行完毕，跳出循环
                	//3.更新URL
                	int len= tkFileMapper.updateFileUrlBatch(tkFiles);
                	logger.info("FileUrlResetTask urlReset update data size:"+len);
                	break;
                }
            }
        	
        	tkFiles = tkFileMapper.fileUrlReset();
        	size = (tkFiles != null?tkFiles.size():0);
        	logger.info("FileUrlResetTask urlReset query data size:"+size);
        	if(tkFiles == null || size == 0){
         		logger.info("FileUrlResetTask urlReset count is empty");
         		return;
         	}
    	}
    	
    }
    
    public Future<String> process(final TkFile tkFile) {
        return fixedThreadPool.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                String flag = "0";
                resetUrlOne(tkFile);
                return flag;
            }
        });
    }
    
    public void resetUrlOne(TkFile tkFile){
    	try {
    		tkFile.setUploadTime(new Date());
    		tkFile.setDownCount(0);
    		if("0".equals(tkFile.getExcelImport())){
    			tkFile.setExcelImportCount(0);
    		}
    		
    		if(tkFile.getUrl() == null || "".equals(tkFile.getUrl())){
    			return;
    		}
    		//从URL中获取桶名称
    		String[] arr = tkFile.getUrl().split("/");
    		String bucketName = arr[3];
			String url = minioTemplate.getObjectURL(bucketName, tkFile.getFileKey(), CommonConstants.EXPIRES);
			tkFile.setUrl(url);
		} catch (Exception e) {
			logger.error("FileUrlResetTask urlReset resetUrlOne file:"+tkFile.getId()+",exception:"+e);
			e.printStackTrace();
		}
    }
   
    
}
