package com.uas.platform.b2b.service.impl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.uas.platform.b2b.core.BaseUtil;
import com.uas.platform.b2b.dao.AttachDao;
import com.uas.platform.b2b.model.Attach;
import com.uas.platform.b2b.model.FileUpload;
import com.uas.platform.b2b.service.AttachService;
import com.uas.platform.b2b.support.SystemSession;
import com.uas.platform.core.util.FileUtils;

@Service
public class AttachServiceImpl implements AttachService {

	@Autowired
	private AttachDao attachDao;

	@Override
	public Attach getAttach(Long id) {
		return attachDao.findOne(id);
	}

	@Override
	public Attach save(Attach attach) {
		return attachDao.save(attach);
	}

	@Override
	public Attach uploadAndSave(FileUpload uploadItem, String parentDir, String description) {
		return save(upload(uploadItem, parentDir, description));
	}

	@Override
	public Attach upload(FileUpload uploadItem, String parentDir, String description) {
		String filename = uploadItem.getFile().getOriginalFilename();
		long size = uploadItem.getFile().getSize();
		if (size > 104857600) {
			return null;// 文件过大，上传失败
		}
		String path = randomFileName(filename, parentDir);
		File file = new File(path);
		BufferedOutputStream bos = null;
		BufferedInputStream bis = null;
		try {
			bos = new BufferedOutputStream(new FileOutputStream(file));
			bis = new BufferedInputStream(uploadItem.getFile().getInputStream());
			int c;
			while ((c = bis.read()) != -1) {
				bos.write(c);
				bos.flush();
			}
			bis.close();
			bos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new Attach(filename, path, description, size);
	}

	public String randomFileName(String fileName, String parentDir) {
		String uuid = UUID.randomUUID().toString().replaceAll("\\-", "");
		String suffix = (fileName != null && fileName.indexOf(".") != -1) ? fileName
				.substring(fileName.lastIndexOf("."), fileName.length()) : "";
		return getDir(parentDir) + File.separator + uuid + suffix;
	}

	@Override
	public List<Attach> uploadZipAndSave(FileUpload uploadItem, String parentDir, String description,
			Map<String, Map<String, Object>> entryParams) {
		Map<String, String> fileMap = uploadZip(uploadItem, parentDir, description);
		if (fileMap != null) {
			List<Attach> attachs = new ArrayList<Attach>();
			for (String entry : fileMap.keySet()) {
				if (entryParams.containsKey(entry)) {
					File file = new File(fileMap.get(entry));
					if (file.exists()) {
						Map<String, Object> params = entryParams.get(entry);
						Attach attach = new Attach(String.valueOf(params.get("name")), fileMap.get(entry), description, file.length());
						attach = attachDao.save(attach);
						attach.setSourceId(Long.parseLong(params.get("sourceId").toString()));
						attachs.add(attach);
					}
				}
			}
			return attachs;
		}
		return null;
	}

	@Override
	public Map<String, String> uploadZip(FileUpload uploadItem, String parentDir, String description) {
		String unzipDir = getDir(parentDir);
		try {
			List<String> entries = FileUtils.unzip(uploadItem.getFile().getInputStream(), unzipDir);
			if (!CollectionUtils.isEmpty(entries)) {
				Map<String, String> fileMap = new HashMap<String, String>();
				for (String entry : entries) {
					fileMap.put(entry, unzipDir + File.separator + entry);
				}
				return fileMap;
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} catch (Error e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 文件路径
	 * 
	 * @param parentDir
	 * @return
	 */
	private String getDir(String parentDir) {
		String path = BaseUtil.FILEPATH + "postattach";
		File dir = new File(path);
		if (!dir.isDirectory())
			dir.mkdir();
		path += File.separator + parentDir;
		dir = new File(path);
		if (!dir.isDirectory())
			dir.mkdir();
		if (SystemSession.getUser() != null) {
			path += File.separator + SystemSession.getUser().getEnterprise().getUu();
			dir = new File(path);
			if (!dir.isDirectory())
				dir.mkdir();
		}
		return path;
	}

}
