package com.ruoyi.ueditorConfig;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.web.controller.common.CommonController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;


/**
 * 用于处理关于ueditor插件相关的请求
 * @author Guoqing
 * @date 2017-11-29
 *
 */
@RestController
@RequestMapping("/sys/ueditor")
public class UeditorController {

	@Autowired
	private ServerConfig serverConfig;
	@Autowired
	private CommonController commonController;

	@RequestMapping(value = "/exec")
	public String config(HttpServletRequest request, HttpServletResponse response, String action, MultipartFile[] upfile) throws Exception {
		if (action.equals("config")) {
			request.setCharacterEncoding("utf-8");
			response.setHeader("Content-Type", "text/html");
			PrintWriter printWriter = response.getWriter();
			String rootPath = request.getRealPath("/");
			printWriter.write(new ActionEnter(request, rootPath).exec());
			printWriter.flush();
			printWriter.close();
		} else if (action.equals("uploadimage")) {
			Map<String, Object> result = new HashMap<String, Object>();
			for (MultipartFile multipartFile : upfile) {
				AjaxResult ajaxResult = commonController.uploadFile(multipartFile);
				result.put("title", multipartFile.getOriginalFilename());
				result.put("original", multipartFile.getOriginalFilename());
				result.put("state", "SUCCESS");
				result.put("url", ajaxResult.get("url"));
				return JSON.toJSONString(result);
			}
			return null;
		}else if(action.equals("uploadvideo")){
			Map<String, Object> result = new HashMap<String, Object>();
			for (MultipartFile multipartFile : upfile) {
				AjaxResult ajaxResult = commonController.uploadFile(multipartFile);
				result.put("title", multipartFile.getOriginalFilename());
				result.put("original", multipartFile.getOriginalFilename());
				result.put("state", "SUCCESS");
				result.put("url", ajaxResult.get("url"));
				return JSON.toJSONString(result);
			}
		}else{
			Map<String, Object> result = new HashMap<String, Object>();
			for (MultipartFile multipartFile : upfile) {
				AjaxResult ajaxResult = commonController.uploadFile(multipartFile);
				result.put("title", multipartFile.getOriginalFilename());
				result.put("original", multipartFile.getOriginalFilename());
				result.put("state", "SUCCESS");
				result.put("url", ajaxResult.get("url"));
				return JSON.toJSONString(result);
			}
		}
		return null;
	}

}
