package com.ruoyi.ueditorConfig.upload;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.ueditorConfig.define.AppInfo;
import com.ruoyi.ueditorConfig.define.BaseState;
import com.ruoyi.ueditorConfig.define.FileType;
import com.ruoyi.ueditorConfig.define.State;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

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



public class BinaryUploader {

    static Logger logger = LoggerFactory.getLogger(BinaryUploader.class);

	public static final State save(HttpServletRequest request, Map<String, Object> conf) {

		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 {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile mf = multipartRequest.getFile("upfile");
			String orgName = mf.getOriginalFilename();// 获取文件名
			String suffix = FileType.getSuffixByFilename(orgName);
			if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
				return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
			}
			// 上传文件路径
			String filePath = RuoYiConfig.getUploadPath();
			// 上传并返回新文件名称
			String fileName = FileUploadUtils.upload(filePath, mf);
			String url = getUrl(request) + fileName;
			State state = new BaseState(true);
			state.putInfo( "size", mf.getSize());
			state.putInfo( "title", orgName);//文件名填入此处
			state.putInfo( "group", "");//所属group填入此处
			state.putInfo( "url", url);//文件访问的url填入此处
			state.putInfo("type", suffix);
			state.putInfo("original", orgName);
			return state;
		} catch (Exception e) {
			return new BaseState(false, AppInfo.PARSE_REQUEST_ERROR);
		}
	}
	private static boolean validType(String type, String[] allowTypes) {
		List<String> list = Arrays.asList(allowTypes);

		return list.contains(type);
	}

	/**
	 * 获取完整的请求路径，包括：域名，端口，上下文访问路径
	 *
	 * @return 服务地址
	 */
	public static String getUrl(HttpServletRequest request)
	{
		return getDomain(request);
	}

	public static String getDomain(HttpServletRequest request)
	{
		StringBuffer url = request.getRequestURL();
		String contextPath = request.getServletContext().getContextPath();
		return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();
	}
}
