package com.ym.mec.biz.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.ym.mec.common.entity.UploadReturnBean;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.thirdparty.storage.StoragePluginContext;
import com.ym.mec.thirdparty.storage.provider.KS3StoragePlugin;
import com.ym.mec.util.upload.UploadUtil;

/** 
 * 上传工具服务层实现类
 */
@Service
public class UploadFileService {

	@Autowired
	private StoragePluginContext storagePluginContext;

	/** 最大上传大小，单位kb */
	@Value("${common.upload.maxSize:153600}")
	private int maxSize;

	/** 支持的扩展名 */
	@Value("${common.upload.supportExtensions:jpg,jpeg,gif,png,mp3,mid,midi,aac,m4a,mp4}")
	private String supportExtensions;

	/** 文件根目录 */
	@Value("/var/tmp/")
	private String fileRoot;

	public UploadReturnBean uploadFile(InputStream in, String ext) {

		UploadReturnBean uploadReturn = new UploadReturnBean("", false, "");
		String fileName = UploadUtil.getFileName(ext);

		String supportType = supportExtensions;
		if (!UploadUtil.validateImgFile(ext, supportType)) {
			uploadReturn.setMessage("上传图片格式错误,目前只支持" + supportType);
			return uploadReturn;
		}

		String root = fileRoot;
		if (StringUtils.isBlank(root)) {
			uploadReturn.setMessage("上传临时目录没有配置");
			return uploadReturn;
		}

		String staticFloder = "";

		String folder = UploadUtil.getFileFloder();
		String filePath = UploadUtil.getFilePath(root, staticFloder, folder);
		File file = uploadFile(in, filePath, fileName);
		if (maxSize > 0 && maxSize < file.length() / 1024) {
			FileUtils.deleteQuietly(file);
			uploadReturn.setMessage("超出允许的大小(" + (maxSize / 1024) + "M)限制");
			return uploadReturn;
		}

		//String url = storagePlugin.uploadFile(staticFloder + folder, file);
		String url = storagePluginContext.uploadFile(KS3StoragePlugin.PLUGIN_NAME,staticFloder + folder, file);

		FileUtils.deleteQuietly(file);

		uploadReturn.setStatus(true);
		uploadReturn.setUrl(url);
		return uploadReturn;
	}

	public void setMaxSize(int maxSize) {
		this.maxSize = maxSize;
	}

	/**
	 * 上传文件的工具方法
	 * @param in
	 * @param path
	 * @return
	 */
	private File uploadFile(InputStream inputStream, String filePath, String fileName) {
		File file = new File(filePath + "/" + fileName);
		try {
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			FileOutputStream fos = new FileOutputStream(file);
			IOUtils.copy(inputStream, fos);
			if (!file.exists() || file.length() == 0) {
				throw new BizException("图片上传出现错误，请重新上传");
			}
		} catch (IOException e) {
			throw new BizException("图片上传失败", e);
		} finally {
			IOUtils.closeQuietly(inputStream);
		}
		return file;
	}

}
