package com.app.admin.common.ueditor.upload;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import com.app.admin.common.ueditor.PathFormat;
import com.app.admin.common.ueditor.define.AppInfo;
import com.app.admin.common.ueditor.define.BaseState;
import com.app.admin.common.ueditor.define.FileType;
import com.app.admin.common.ueditor.define.State;
import com.app.component.sysconfig.service.SysConfigService;
import com.app.framework.core.utils.file.UploadUtil;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class BinaryUploader {

	public static final State save(HttpServletRequest request,
			Map<String, Object> conf) {
		FileItemStream fileStream = null;
		boolean isAjaxUpload = request.getHeader( "X_Requested_With" ) != null;

		if (!ServletFileUpload.isMultipartContent(request)) {
			return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);
		}

		ServletFileUpload upload = new ServletFileUpload(
				new DiskFileItemFactory());

        if ( isAjaxUpload ) {
            upload.setHeaderEncoding( "UTF-8" );
        }

		try {
			FileItemIterator iterator = upload.getItemIterator(request);

			while (iterator.hasNext()) {
				fileStream = iterator.next();

				if (!fileStream.isFormField())
					break;
				fileStream = null;
			}

			if (fileStream == null) {
				return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);
			}

			String originFileName = fileStream.getName();
			String suffix = FileType.getSuffixByFilename(originFileName);

			if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
				return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
			}

			originFileName = originFileName.substring(0, originFileName.length() - suffix.length());
			long maxSize = ((Long) conf.get("maxSize")).longValue();
			String savePath = (String) conf.get("savePath");
			String filename = (String) conf.get("filename");

			savePath = PathFormat.parse(savePath, filename);

			SysConfigService sysConfigService = SpringUtil.getBean(SysConfigService.class);
			JSONObject object = sysConfigService.getJson("UploadFile");
			UploadUtil.init(object.getString("uploadPath"), object.getString("baseUrl"));

			StringBuilder uPath = new StringBuilder();
			uPath.append(UploadUtil.getUploadPath(savePath)).append(suffix);

			InputStream is = fileStream.openStream();
			State storageState = StorageManager.saveFileByInputStream(is, uPath.toString(), maxSize);
			is.close();

			if (storageState.isSuccess()) {
				StringBuilder new_file_url = new StringBuilder();
				new_file_url.append(UploadUtil.getBaseUrl(request, savePath)).append(suffix);

				storageState.putInfo("url", new_file_url.toString());
				storageState.putInfo("type", suffix);
				storageState.putInfo("original", originFileName + suffix);
			}

			return storageState;
		} catch (FileUploadException e) {
			return new BaseState(false, AppInfo.PARSE_REQUEST_ERROR);
		} catch (IOException e) {
		}
		return new BaseState(false, AppInfo.IO_ERROR);
	}

	private static boolean validType(String type, String[] allowTypes) {
		List<String> list = Arrays.asList(allowTypes);

		return list.contains(type);
	}
}
