package cn.com.qmth.examcloud.core.questions.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import cn.com.qmth.examcloud.api.commons.security.bean.User;
import cn.com.qmth.examcloud.commons.exception.StatusException;
import cn.com.qmth.examcloud.core.questions.base.CommonUtils;
import cn.com.qmth.examcloud.core.questions.base.FileDisposeUtil;
import cn.com.qmth.examcloud.core.questions.base.IoUtils;
import cn.com.qmth.examcloud.core.questions.base.enums.ExamFileType;
import cn.com.qmth.examcloud.core.questions.base.enums.ExportType;
import cn.com.qmth.examcloud.core.questions.base.enums.ExportWay;
import cn.com.qmth.examcloud.core.questions.base.enums.PaperSeqMode;
import cn.com.qmth.examcloud.core.questions.base.excel.ExcelWriter;
import cn.com.qmth.examcloud.core.questions.dao.entity.ExamFile;
import cn.com.qmth.examcloud.core.questions.dao.entity.ExamPaper;
import cn.com.qmth.examcloud.core.questions.dao.entity.ExportStructure;
import cn.com.qmth.examcloud.core.questions.dao.entity.ExtractConfig;
import cn.com.qmth.examcloud.core.questions.dao.entity.Paper;
import cn.com.qmth.examcloud.core.questions.dao.entity.PaperDetailUnit;
import cn.com.qmth.examcloud.core.questions.dao.entity.QuesOption;
import cn.com.qmth.examcloud.core.questions.dao.entity.Question;
import cn.com.qmth.examcloud.core.questions.dao.entity.QuestionAudio;
import cn.com.qmth.examcloud.core.questions.dao.entity.QuestionTypeNum;
import cn.com.qmth.examcloud.core.questions.service.ExamFileService;
import cn.com.qmth.examcloud.core.questions.service.ExportStructureService;
import cn.com.qmth.examcloud.core.questions.service.ExtractConfigFileService;
import cn.com.qmth.examcloud.core.questions.service.ExtractConfigService;
import cn.com.qmth.examcloud.core.questions.service.QuestionAudioService;
import cn.com.qmth.examcloud.core.questions.service.bean.dto.DownloadPaperDto;
import cn.com.qmth.examcloud.core.questions.service.bean.dto.ExportPaperInfoModel;
import cn.com.qmth.examcloud.core.questions.service.bean.dto.ObjectiveQuestionStructure;
import cn.com.qmth.examcloud.core.questions.service.bean.dto.PaperDetailExp;
import cn.com.qmth.examcloud.core.questions.service.bean.dto.PaperDetailUnitExp;
import cn.com.qmth.examcloud.core.questions.service.bean.dto.PaperExp;
import cn.com.qmth.examcloud.core.questions.service.bean.dto.SubjectiveQuestionStructure;
import cn.com.qmth.examcloud.core.questions.service.config.SysProperty;
import cn.com.qmth.examcloud.core.questions.service.converter.PrintExamPaperService;
import cn.com.qmth.examcloud.core.questions.service.export.ExportPaperAbstractService;
import cn.com.qmth.examcloud.core.questions.service.export.InitPaperExpService;
import cn.com.qmth.examcloud.core.questions.service.util.ExportPaperUtil;
import cn.com.qmth.examcloud.core.questions.service.util.PaperUtil;
import cn.com.qmth.examcloud.examwork.api.ExamCloudService;
import cn.com.qmth.examcloud.examwork.api.bean.ExamCourseRelationBean;
import cn.com.qmth.examcloud.examwork.api.request.GetExamCourseListReq;
import cn.com.qmth.examcloud.examwork.api.response.GetExamCourseListResp;
import cn.com.qmth.examcloud.support.filestorage.FileStorageUtil;

/**
 * @author chenken
 * @date 2017年7月31日 下午6:03:46
 * @company QMTH
 * @description ExtractConfigFileServiceImpl.java
 */
@Service("extractConfigFileService")
public class ExtractConfigFileServiceImpl implements ExtractConfigFileService {

	private static final Logger LOG = LoggerFactory.getLogger(ExtractConfigFileServiceImpl.class);

	public static final String TEMP_FILE_EXP = "docxExport/";

	public static final String TEMP_FILE_NAME = "_考试说明";

	@Autowired
	private ExportStructureService exportStructureService;

	@Autowired
	private ExtractConfigService extractConfigService;

	@Autowired
	private ExamFileService examFileService;

	@Autowired
	private QuestionAudioService questionAudioService;

	@Autowired
	private InitPaperExpService initPaperExpService;

	@Autowired
	private PrintExamPaperService printExamPaperService;

	@Autowired
	private ExamCloudService examCloudService;

	@Autowired
	private SysProperty sysProperty;

	@Autowired
	MongoTemplate mongoTemplate;

	@Override
	public void saveExtractConfigAndBuildPaperFile(ExtractConfig extractConfig, Integer isbuildFile, User user,
			PaperSeqMode seqMode) {
		// 新增，id为空
		if (StringUtils.isBlank(extractConfig.getId())) {
			// 先查询
			ExtractConfig tempConfig = extractConfigService.findConfig(extractConfig);
			if (tempConfig != null) {
				extractConfig.setId(tempConfig.getId());
			}
		}
		// 查询试卷导出设置
		ExportStructure exportStructure = null;
		if (isbuildFile == 1) {
			exportStructure = exportStructureService.findStructureByExamId(extractConfig.getExamId() + "");
		}

		// 生成试卷
		List<ExamPaper> examPaperList = extractConfigService.saveExtractConfig(extractConfig, user);
		if (isbuildFile == 1) {
			// 删除原有试卷文件
			ExamFile examFile = new ExamFile();
			examFile.setExamId(extractConfig.getExamId() + "");
			examFile.setCourseId(extractConfig.getCourseCode());
			examFile.setOrgId(extractConfig.getOrgId());
			examFileService.deleteExamFile(examFile);
			// 上传抽取试卷对象集合
			for (ExamPaper examPaper : examPaperList) {
				String paperId = examPaper.getPaper().getId();
				uploadPaperFile(extractConfig, paperId, exportStructure, user, examPaper, seqMode);
			}
		}
	}
	
	/**
	 * 生成并上传试卷文件
	 *
	 * @param extractConfig
	 * @param paperId
	 * @param exportStructure
	 * @param user
	 * @throws Exception
	 */
	private void uploadPaperFile(ExtractConfig extractConfig, String paperId, ExportStructure exportStructure,
			User user, ExamPaper examPaper, PaperSeqMode seqMode) {
		ExportPaperAbstractService exportPaperAbstractService = PaperUtil
				.getByRootOrgId(String.valueOf(user.getRootOrgId()));
		exportPaperAbstractService.uploadFile(extractConfig, paperId, exportStructure, user, examPaper, seqMode);
	}

	@Override
	public void exportExamPaperInfoCheck(ExportPaperInfoModel exportModel, HttpServletResponse response)
			throws Exception {
		ExportStructure exportStructure = exportStructureService.findStructureByExamId(exportModel.getExamId() + "");
		// 如果是批量导出
		if (exportModel.getExportWay() == ExportWay.BATCH) {
			if (exportStructure == null) {
				exportStructure = new ExportStructure();
				exportStructure.setExportType(ExportType.NORMAL);
			}
			// 查询该考试下是否所有课程都制定了调卷规则和考试文件
			checkAllCourseByExamId(exportModel.getExamId(), exportStructure.getExportType());
		}
	}

	@Override
	public void exportExamPaperInfo(ExportPaperInfoModel exportModel, HttpServletResponse response, String loginName,
			String orgId, String psw) throws Exception {
		String tempDir = loginName + System.currentTimeMillis();
		String downloadDir = sysProperty.getDownloadDirectory() + "/" + tempDir;
		String downZipDir = sysProperty.getZipDirectory() + "/" + tempDir;
		// 创建试卷和压缩文件 文件夹
		FileDisposeUtil.createDirectory(downloadDir);
		// 创建压缩文件的文件夹
		FileDisposeUtil.createDirectory(downZipDir);
		try {
			ExportStructure exportStructure = exportStructureService
					.findStructureByExamId(exportModel.getExamId() + "");
			if (exportStructure == null) {
				exportStructure = new ExportStructure();
				exportStructure.setExportType(ExportType.NORMAL);
			}
			// 导出分布式印刷的数据包
			if (exportModel.getExportContentList().contains(ExamFileType.PRINT_EXAM_PACKAGE.name())) {
				ExtractConfig condition = new ExtractConfig();
				condition.setExamId(Long.valueOf(exportModel.getExamId()));
				condition.setCourseCode(exportModel.getCourseId());
				// 获取调卷规则
				ExtractConfig extractConfig = extractConfigService.findConfig(condition);
				if (extractConfig != null) {
					List<Paper> papers = new ArrayList<>();
					List<ExamPaper> examPapers = extractConfig.getExamPaperList();
					if (examPapers != null && examPapers.size() > 0) {
						for (ExamPaper examPaper : examPapers) {
							papers.add(examPaper.getPaper());
						}
					}
					printExamPaperService.downloadPaper(papers, downloadDir, psw);
				} else {
					LOG.info("exportPrintExamPaper fail, extractConfig is not exist!");
				}
			}
			// 如果是普通类型的批量导出 导出试卷结构
			if (exportModel.getExportWay() == ExportWay.BATCH) {
				Map<String, String> paperIds = checkAllCourseByExamId(exportModel.getExamId(),
						exportStructure.getExportType());
				if (exportStructure.getExportType() == ExportType.NORMAL) {
					if (paperIds.size() > 0 && exportModel.getExportContentList()
							.contains(ExamFileType.PAPER_STRUCTURE_OBJECTIVE.name())) {
						makePaperStructure(downloadDir, exportStructure.getExamName(), paperIds, exportStructure);// for
																													// export
																													// test
					}
				}
			}
			// 根据条件获取到文件下载路径,下载文件到服务器的downloadDirectory文件夹
			List<ExamFile> examFiles = examFileService.findExamFileListByExportPaperInfoModel(exportModel);
			if (examFiles != null && examFiles.size() > 0) {
				for (int i = 0; i < examFiles.size(); i++) {
					ExamFile examFile = examFiles.get(i);
					File file = new File(downloadDir + File.separator + examFile.getFileName());
					// 通用存储
					FileStorageUtil.saveUrlAs(FileStorageUtil.realPath(examFile.getFilePath()), file);

					if (examFile.getExamFileType() == ExamFileType.PAPER) {
						if(StringUtils.isBlank(examFile.getPaperId())) {
							throw new StatusException("错误的旧数据，请重新生成一次文件");
						}
						downloadAudio(examFile.getPaperId(), examFile, downloadDir, orgId);
					}
				}
			}
			// 创建压缩文件名称
			String zipFileName = exportModel.getExamId();
			// 将downloadDirectory文件夹压缩成zip文件,存放到zipDirectory文件夹中
			FileDisposeUtil.fileToZip(downloadDir, downZipDir, zipFileName);
			// 下载zip文件到客户端
			FileDisposeUtil.downloadFile(zipFileName + ".zip", downZipDir + File.separator + zipFileName + ".zip",
					response);
		} finally {
			// 删除文件夹
			FileUtils.deleteQuietly(new File(downloadDir));
			FileUtils.deleteQuietly(new File(downZipDir));
		}
	}

	/**
	 * 下载试卷音频文件
	 *
	 * @throws Exception
	 */
	private void downloadAudio(String paperId, ExamFile examFile, String downloadDir, String orgId) throws Exception {
		ExportPaperAbstractService exportPaperAbstractService = PaperUtil.getByRootOrgId(orgId);
		DownloadPaperDto dto = new DownloadPaperDto();
		dto.setPaperId(paperId);
		dto.setSeqMode(PaperSeqMode.MODE3);
		PaperExp paperExp = exportPaperAbstractService.initPaperExp(dto);
		// 下载考试说明
		if (StringUtils.isNotBlank(paperExp.getExamRemark())) {
			downExamRemark(paperExp, downloadDir, examFile);
		}
		// 取到所有大题
		List<PaperDetailExp> paperDetailExps = paperExp.getPaperDetails();
		if (paperDetailExps != null && paperDetailExps.size() > 0) {
			for (PaperDetailExp paperDetailExp : paperDetailExps) {
				// 取到所有小题
				List<PaperDetailUnitExp> paperDetailUnitExps = paperDetailExp.getPaperDetailUnits();
				if (paperDetailUnitExps != null && paperDetailUnitExps.size() > 0) {
					for (PaperDetailUnitExp unit : paperDetailUnitExps) {
						if (unit.getQuestion().getHasAudio() != null && unit.getQuestion().getHasAudio()) {
							List<QuestionAudio> questionAudios = questionAudioService
									.findQuestionAudiosByQuestionId(unit.getQuestion().getId());
							for (QuestionAudio audio : questionAudios) {
								String audioFileName = audio.getId() + "_"
										+ exportPaperAbstractService.getAudioFileName(audio, unit, paperDetailExp);
//                                UpYun upyun = new UpYun(sysProperty.getBucketName(), sysProperty.getUserName(), sysProperty.getPassword());
								File file = new File(downloadDir + File.separator + audioFileName);
//                                upyun.readFile(audio.getFileUrl(), file);
								// 通用存储
								FileStorageUtil.saveUrlAs(FileStorageUtil.realPath(audio.getFileUrl()), file);
							}
						}
					}
				}
			}
		}
	}

	/**
	 * 下载考试说明
	 *
	 * @param zipFileName
	 * @throws Exception
	 */
	public void downExamRemark(PaperExp paperExp, String zipFileName, ExamFile examFile) throws Exception {
//        //1.考试说明html转成word
//        String title = "<p style=\"text-align:center\"><span style=\"font-size:26px\"><span style=\"font-family:宋体\">考&nbsp;试&nbsp;说&nbsp;明</span></span></p>";
//        WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
//        String html = title + ImageUtils.reSizeImg(paperExp.getExamRemark());
//        DocxProcessUtil.html2Docx(wordMLPackage, CommonUtils.formatHtml(html));
//        //2.导出考试说明word
		File directory = new File(zipFileName + File.separator);
		String fileName = paperExp.getName() + "_" + paperExp.getCourse().getName() + "_"
				+ paperExp.getCourse().getCode() + "_" + examFile.getGroupCode() + TEMP_FILE_NAME;
//        Docx4J.save(wordMLPackage, file);
		ExportPaperUtil.createExamRemarkDocFile(directory, fileName, paperExp.getExamRemark());
	}

	/**
	 * 计算取得音频文件名称
	 *
	 * @param audio
	 * @param unit
	 * @return
	 */
	@SuppressWarnings("unused")
	private String getAudioFileName(QuestionAudio audio, PaperDetailUnit unit) {
		String questionAudioId = audio.getId();
		StringBuffer audioFileName = new StringBuffer(unit.getPaperDetail().getNumber() + "_" + unit.getNumber() + "_");
		Question question = unit.getQuestion();
		List<String> idvaluesBody = CommonUtils.getTagANames(question.getQuesBody());
		if (idvaluesBody.contains(questionAudioId)) {
			audioFileName.append("1");// 题干
			audioFileName.append("_");
			int index = idvaluesBody.indexOf(questionAudioId);
			audioFileName.append(index + 1);
		} else {
			List<QuesOption> options = question.getQuesOptions();
			if (options != null && options.size() > 0) {
				for (QuesOption option : options) {
					List<String> idvaluesOption = CommonUtils.getTagANames(option.getOptionBody());
					if (idvaluesOption.contains(questionAudioId)) {
						audioFileName.append("2");// 选项
						audioFileName.append("_");
						audioFileName.append(CommonUtils.getOptionNum(Integer.parseInt(option.getNumber()) - 1));
						audioFileName.append("_");
						int index = idvaluesOption.indexOf(questionAudioId);
						audioFileName.append(index + 1);
						break;
					}
				}
			}
		}
		audioFileName.append(".");
		audioFileName.append(audio.getFileSuffixes());
		return audioFileName.toString();
	}

	/**
	 * 查询该考试下是否所有课程都制定了调卷规则
	 *
	 * @param examId
	 */
	private Map<String, String> checkAllCourseByExamId(String examId, ExportType exportType) {
		Map<String, String> paperIdMap = new HashMap<>();
		List<ExamCourseRelationBean> examCourseDtoList = new ArrayList<>();
		GetExamCourseListReq req = new GetExamCourseListReq();
		req.setExamId(Long.valueOf(examId));
		// req.setExamId(299L);//for export test
		req.setCourseEnable(true);
		Long start = 1l;
		int count = 0;
		while (true) {
			req.setStart(start);
			GetExamCourseListResp resp = examCloudService.getExamCourseList(req);
			examCourseDtoList.addAll(resp.getRelationList());
			if (start.equals(resp.getNext())) {
				break;
			} else {
				start = resp.getNext();
			}
			count++;
			if (count > 1000) {
				throw new StatusException("Q-", "考试下课程的数据量过大");
			}
		}

		for (ExamCourseRelationBean examCourseDto : examCourseDtoList) {
			ExtractConfig condition = new ExtractConfig();
			condition.setExamId(examCourseDto.getExamId());
			// condition.setExamId(606L);//for export online
			condition.setCourseCode(examCourseDto.getCourseCode());

			ExtractConfig extractConfig = extractConfigService.findConfig(condition);
//            if (extractConfig == null) {
//                logger.warn("examId:" + examId + " courseCode:" + examCourseDto.getCourseCode());
//                continue;
//            }

			if (extractConfig == null) {
				throw new RuntimeException("该考试下的课程“" + examCourseDto.getCourseName() + "”没有制定调卷规则,不能批量导出,请保存调卷规则生成文件");
			}
			if (extractConfig.getIfFinish() == null || extractConfig.getIfFinish() == 0) {
				throw new RuntimeException("该考试下的课程“" + examCourseDto.getCourseName() + "”考试文件没有生成,不能批量导出,请保存调卷规则生成文件");
			}
			checkExamFileExists(examId, examCourseDto.getCourseCode(), exportType, examCourseDto.getCourseName());

			List<ExamPaper> examPapers = extractConfig.getExamPaperList();
			if (examPapers == null || examPapers.size() < 1) {
				throw new RuntimeException("该考试下的课程“" + examCourseDto.getCourseName() + "”没有绑定试卷。");
			}
			for (ExamPaper examPaper : examPapers) {
				String paperId = examPaper.getPaper().getId();
				paperIdMap.put(paperId, examPaper.getGroupCode());
			}

			/*
			 * Map<String, String> finishedPaperIdMap =
			 * extractConfig.getFinishedPaperIdMap(); Set<Entry<String, String>> entry =
			 * finishedPaperIdMap.entrySet(); Iterator<Entry<String, String>> iterator =
			 * entry.iterator(); while (iterator.hasNext()) { Entry<String, String> next =
			 * iterator.next(); //paperId为key,paperType为value
			 * paperIdMap.put(next.getValue(), next.getKey()); }
			 */
		}
		return paperIdMap;
	}

	/**
	 * 检查试卷文件是否存在
	 *
	 * @param examId
	 */
	private void checkExamFileExists(String examId, String code, ExportType exportType, String name) {
		ExamFile examFileCondition = new ExamFile();
		examFileCondition.setExamId(examId);
		examFileCondition.setCourseId(code);

		List<ExamFile> examfiles = examFileService.findExamFileListByExamFile(examFileCondition);

		// 检查是否都生成了试卷文件
		boolean paperFlag = false;
		if (exportType == ExportType.NORMAL) {
			for (ExamFile examFile : examfiles) {
				if (examFile.getExamFileType() == ExamFileType.PAPER) {
					paperFlag = true;
				}
			}
		} else {
			for (ExamFile examFile : examfiles) {
				if (examFile.getExamFileType() == ExamFileType.COMPUTERTEST_PACKAGE) {
					paperFlag = true;
				}
			}
		}

		if (!paperFlag) {
			String message = exportType == ExportType.NORMAL ? "考试文件" : "机考数据包";
			throw new RuntimeException("该考试下的课程“" + name + "”" + message + "没有生成,不能批量导出,请重新保存调卷规则生成");
		}
	}

	/**
	 * 将该考试下的所有课程试卷的结构生成到一张Excel表中
	 *
	 * @param examName
	 * @param paperIds
	 * @param exportStructure
	 * @throws Exception
	 */
	private void makePaperStructure(String downloadDir, String examName, Map<String, String> paperIds,
			ExportStructure exportStructure) throws Exception {
		LOG.info("正在批量生成试卷结构...");
		List<QuestionTypeNum> questionTypeNums = exportStructure.getQuestionTypeNums();
		// 客观题集合
		List<ObjectiveQuestionStructure> objectiveQuestionStructureList = new ArrayList<>();
		// 主观题集合
		List<SubjectiveQuestionStructure> subjectiveQuestionStructureList = new ArrayList<>();

		ExportPaperAbstractService exportPaperAbstractService = PaperUtil.getByRootOrgId(exportStructure.getOrgId());
		Set<Entry<String, String>> entrySet = paperIds.entrySet();
		Iterator<Entry<String, String>> iterator = entrySet.iterator();

		int index = 1;
		while (iterator.hasNext()) {
			Entry<String, String> entry = iterator.next();
			String paperId = entry.getKey();
			String paperType = entry.getValue();
			LOG.info(index + " - 处理试卷:" + paperId);

			DownloadPaperDto dto = new DownloadPaperDto();
			dto.setPaperId(paperId);
			dto.setSeqMode(PaperSeqMode.MODE3);
			PaperExp paperExp = initPaperExpService.initPaperExp(dto);// for export test
			LOG.info("处理客观题...");
			// 添加客观题
			List<PaperDetailExp> objectiveDetails = exportPaperAbstractService.getAllObjectiveDetails(paperExp);
			// 得到补齐后的客观题大题
			List<PaperDetailExp> paperDetailExps = exportPaperAbstractService.fillObjectiveQuestions(objectiveDetails,
					questionTypeNums);
			List<ObjectiveQuestionStructure> objectiveList = new ArrayList<>();
			for (PaperDetailExp paperDetailExp : paperDetailExps) {
				for (PaperDetailUnitExp unit : paperDetailExp.getPaperDetailUnits()) {
					objectiveList.add(new ObjectiveQuestionStructure(paperExp, paperDetailExp, unit, paperType));
				}
			}
			objectiveQuestionStructureList.addAll(objectiveList);
			LOG.info("处理客观题完成");
			// 添加主观题
			LOG.info("处理主观题...");
			List<PaperDetailExp> subjectiveDetails = exportPaperAbstractService.getAllSubjectiveDetails(paperExp);
			List<SubjectiveQuestionStructure> subjectiveList = new ArrayList<>();
			for (PaperDetailExp paperDetailExp : subjectiveDetails) {
				for (PaperDetailUnitExp unit : paperDetailExp.getPaperDetailUnits()) {
					subjectiveList.add(new SubjectiveQuestionStructure(paperExp, paperDetailExp, unit, paperType));
				}
			}
			subjectiveQuestionStructureList.addAll(subjectiveList);
			LOG.info("处理主观题完成");
			index++;
		}

		ExcelWriter objectiveExcelExporter = new ExcelWriter(ObjectiveQuestionStructure.class);
		String keguanFileName = examName + "_客观题.xlsx";
		try (FileOutputStream out1 = getFileOutputStream(downloadDir, keguanFileName);) {
			objectiveExcelExporter.write(keguanFileName, objectiveQuestionStructureList, out1);
		} catch (IOException e) {
			LOG.error(e.getMessage(), e);
		}

		ExcelWriter subjectiveExcelExporter = new ExcelWriter(SubjectiveQuestionStructure.class);
		String zhuguanFileName = examName + "_主观题.xlsx";
		try (FileOutputStream out2 = getFileOutputStream(downloadDir, zhuguanFileName);) {
			subjectiveExcelExporter.write(zhuguanFileName, subjectiveQuestionStructureList, out2);
		} catch (IOException e) {
			LOG.error(e.getMessage(), e);
		}

		LOG.info("批量生成试卷结构完成");
	}

	private FileOutputStream getFileOutputStream(String downloadDir, String fileName) throws IOException {
		File directory = new File(downloadDir);
		if (!directory.exists()) {
			directory.mkdirs();
		}
		File file = new File(downloadDir + File.separator + fileName);
		if (!file.exists()) {
			IoUtils.createFile(file);
		}
		return new FileOutputStream(file);
	}

}