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

import com.uas.platform.b2b.core.util.PathUtils;
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.HttpUtils;
import com.uas.platform.b2b.support.SystemSession;
import com.uas.platform.b2b.temporary.model.FileUrl;
import com.uas.platform.core.util.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.IOException;
import java.util.*;

@Service
public class AttachServiceImpl implements AttachService {

	@Autowired
	private AttachDao attachDao;

	/**
	 * 文件大小
	 */
	private final Integer MAX_FILE_SIZE = 100 * 1024 * 1024;

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

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

	public Attach upload(FileUpload uploadItem, String description) {
		String filename = uploadItem.getFile().getOriginalFilename();
		long size = uploadItem.getFile().getSize();
		if(size >  MAX_FILE_SIZE) {
			// 是否限制文件上传大小
		}
		String path = null;
        try {
            path = HttpUtils.upload(FileUrl.FILE_UPLOAD, uploadItem.getFile(), null);
        } catch (Exception e) {
            e.printStackTrace();
        }
		Attach attach = new Attach(filename, path, description, size, new Date());
		return attach;
	}

	@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>();
			String[] sources = null;
			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);
						// multi sources
						sources = params.get("sourceId").toString().split(",");
						for (String sr : sources) {
							Attach attach = new Attach(String.valueOf(params.get("name")), fileMap.get(entry), description, file.length(),
									new Date());
							attach = attachDao.save(attach);
							attach.setSourceId(sr);
							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 = PathUtils.getFilePath() + "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;
	}

}
