package com.jpsoft.shinestar.modules.common.controller;

import com.jpsoft.shinestar.config.OSSConfig;
import com.jpsoft.shinestar.modules.common.utils.OSSUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/tinymce")
public class TinymceController {
    @Autowired
    private OSSConfig ossConfig;

    @RequestMapping(value = "/upload", method = RequestMethod.POST)  
    @ResponseBody  
    public Map<String, String> upload(HttpServletRequest request,HttpServletResponse response,@RequestParam MultipartFile upfile) throws IOException {
	    Map<String, String> result = new HashMap<>();

	    if (request.getMethod().equals("OPTIONS")){
            response.setStatus(202);
            return result;
        }

    	String retImgUrl = "";
		String subFolder ="/editor";

		try {
            retImgUrl = OSSUtil.upload(ossConfig,subFolder,upfile.getOriginalFilename(),upfile.getInputStream());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

    	String oldFileName= upfile.getOriginalFilename();

    	//返回类型
        if(StringUtils.isNotEmpty(retImgUrl)){
	    	result.put("url", retImgUrl);
	        result.put("size", String.valueOf(upfile.getSize()));  
	        result.put("type", oldFileName.substring(oldFileName.lastIndexOf(".")));
	        result.put("title", oldFileName.substring(0,oldFileName.lastIndexOf(".")));
	        result.put("original", oldFileName.substring(0,oldFileName.lastIndexOf(".")));//文件名称
	        result.put("state", STATE_SUCESS);
        }

        return result;  
    }

    private final static String STATE_SUCESS = "SUCCESS";
}