package com.sunda.spmsweb.ureport;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import com.bstek.ureport.provider.report.ReportFile;
import com.bstek.ureport.provider.report.ReportProvider;

import lombok.NoArgsConstructor;


@NoArgsConstructor
public class CustomFileReportProvider implements ReportProvider {
	
	private final Logger logger = LoggerFactory.getLogger(CustomFileReportProvider.class);

    private String prefix="rfile:";
    
    @Value("${ureport.fileStoreDir1}")
    private String fileStoreDir;
    
    private final String SEPARATOR = "/";
    
    private boolean disabled;
	
	@Override
	public InputStream loadReport(String file) {
		if (file.startsWith(prefix)) {
            file = file.substring(prefix.length(), file.length());
        }
        String fullPath = fileStoreDir + SEPARATOR + file;
        try {
            return new FileInputStream(fullPath);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
	}

	@Override
	public void deleteReport(String file) {
		if (file.startsWith(prefix)) {
            file = file.substring(prefix.length(), file.length());
        }
        String fullPath = fileStoreDir + SEPARATOR + file;
        File f = new File(fullPath);
        if (f.exists()) {
            boolean flag= f.delete();
            if(!flag){
                logger.error("delete file failed!");
            }
        }
	}

	@Override
	public List<ReportFile> getReportFiles() {
        File file = new File(fileStoreDir);
        // 创建文件夹
        if (!file.exists()) {
            file.mkdirs();
        }
        List<ReportFile> list = new ArrayList<ReportFile>();
        for (File f : file.listFiles()) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(f.lastModified());
            list.add(new ReportFile(f.getName(), calendar.getTime()));
        }
        Collections.sort(list, new Comparator<ReportFile>() {
            @Override
            public int compare(ReportFile f1, ReportFile f2) {
                return f2.getUpdateDate().compareTo(f1.getUpdateDate());
            }
        });
        return list;
	}

	@Override
	public void saveReport(String file, String content) {
		if (file.startsWith(prefix)) {
            file = file.substring(prefix.length(), file.length());
        }
        String filePath = fileStoreDir + SEPARATOR;
        logger.error("开始保存报表【" + file + "】保存路径：" + filePath);
        // 创建文件夹
        File saveDirFile = new File(filePath);
        if (!saveDirFile.exists()) {
            saveDirFile.mkdirs();
        }
        String fullPath = filePath + SEPARATOR + file;
        FileOutputStream outStream = null;
        try {
            outStream = new FileOutputStream(new File(fullPath));
            IOUtils.write(content, outStream, "utf-8");
            logger.error("保存报表【" + file + "】保存成功! 保存路径：" + filePath);
            outStream.close();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        } finally{
            if(outStream!=null){
                try {
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
	}

	@Override
	public String getName() {
		return "default";
	}

	@Override
    public boolean disabled() {
        return disabled;
    }

    public void setDisabled(boolean disabled) {
        this.disabled = disabled;
    }
    
	@Override
	public String getPrefix() {
		return prefix;
	}

}
