package cn.myapps.runtime.ueditor.controller;

import cn.myapps.common.util.StringUtil;
import cn.myapps.runtime.ueditor.UeditorActionEnter;
import cn.myapps.common.util.PropertyUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * html File Upload RESTful 接口
 * @a
 * uthor oliver
 */
@Api(tags = "html文件上传文件执行模块")
@Controller
@RequestMapping(value = "/api")
public class HtmlEditUploadController {



    /**
     * html编辑器文件上传
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("/runtime/html/edit/upload")
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    @ApiOperation(value = "html编辑器文件上传", notes = "html编辑器文件上传")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "action", value = "操作", required = true, paramType = "query", dataType = "string")
    })
    public void uploadHtmlEidt(@RequestParam String action, MultipartFile upfile, HttpServletRequest request, HttpServletResponse response) throws Exception {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy" + File.separator + "MM-dd");
        Date date = new Date();
        String rootPath = PropertyUtil.getPath();
        String url1 = "";
        JSONObject json1 = null;
        if (action.equals("uploadimage") || action.equals("uploadfile")) {
            json1 = new JSONObject();
            String fileName = upfile.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
            String uuid = UUID.randomUUID().toString();
            String relativePath = "";
            String uploadFolderPath = "";
            String filePathTemp = "";
            if (action.equals("uploadimage")) {
                filePathTemp = File.separator + "uploads" + File.separator + "htmlfield" + File.separator + "image" + File.separator + dateFormat.format(date);
                uploadFolderPath = rootPath + filePathTemp;

            } else if (action.equals("uploadfile")) {
                filePathTemp = File.separator + "uploads" + File.separator + "htmlfield" + File.separator + "file" + File.separator + dateFormat.format(date);
                uploadFolderPath = rootPath + filePathTemp;

            }
            relativePath = filePathTemp + File.separator + UUID.randomUUID() + File.separator + fileName;

            String uploadFilePath = uploadFolderPath + File.separator + UUID.randomUUID() + File.separator + fileName;


            File uploadFolder = new File(uploadFolderPath);
            if (!uploadFolder.exists()) {
                uploadFolder.mkdirs();
            }
            File uploadFile = new File(uploadFilePath);
            uploadFile.createNewFile();
            upfile.transferTo(uploadFile);

            json1.put("state", "SUCCESS");
            json1.put("original", fileName);
            json1.put("size", String.valueOf(upfile.getSize()));
            // json1.put("title", uuid + suffix);
            json1.put("title", fileName);
            json1.put("type", suffix);
            json1.put("url", relativePath.replaceAll("\\\\", "/"));
//    		return map;
        }
        request.setCharacterEncoding("utf-8");
        if (json1 == null) {
            response.setHeader("Content-Type", "text/json");

            String result = new UeditorActionEnter(request, rootPath).exec();

            JSONObject json = JSONObject.fromObject(result);

            String url = (String) json.get("url");
            String contextPath = request.getContextPath();

            if (!StringUtil.isBlank(url)) {
                url = contextPath + url;
                json.put("url", url);
            }
            json1 = json;
        }
        try {
            PrintWriter writer = response.getWriter();
            writer.write(json1.toString());
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

