package com.jzdsh.auto.app.controller.admin.ueditor;

import com.jfinal.kit.LogKit;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.upload.UploadFile;
import com.jzdsh.auto.app.controller.BaseController;
import com.jzdsh.util.CommonCons;

/**
 * @ProjectName: auto
 * @Package: com.jzdsh.auto.app.controller.admin.ueditor
 * @ClassName: UeditorController
 * @Author: Jzdsh
 * @Description: 富文本
 * @Date: 2020/3/25 15:45
 * @Version: 1.0
 */
public class UeditorController extends BaseController {


    public void ueditor( ) {


        if ("config".equals(getPara("action"))) {
            render("/assets/ueditor/jsp/config.json");
            return;
        }
        String uploadType = getPara("uploadType");
        if (StrKit.isBlank(uploadType)) {
            renderJson("state", "上传类型参数缺失");
            return;
        }

        UploadFile uploadFile = null;
        try {
            // "upfile" 来自 config.json 中的 imageFieldName 配置项
            String uploadPath = "";
            Integer maxPostSize = 51200000;
            if ("uploadimage".equals(getPara("action"))) {
                uploadPath = "/ue/img/";
                maxPostSize = 1024 * 1024 * 10;
            } else if ("uploadvideo".equals(getPara("action"))) {
                uploadPath = "/ue/video/";
                maxPostSize = 1024 * 1024 * 50;
            } else if ("uploadfile".equals(getPara("action"))) {
                uploadPath = "/ue/file/";
                maxPostSize = 1024 * 1024 * 10;
            }


            uploadFile = getFile("upfile", uploadPath, maxPostSize);

            String fileName = uploadFile.getFileName( );
            String extName = ImageKit.getExtName(fileName);

            long size = uploadFile.getFile( ).length( );

            /**
             * ueditor 要求的返回格式：
             * {"state": "SUCCESS",
             * "title": "1465008328293017063.png",
             * "original": "2222.png",
             * "type": ".png",
             * "url": "/ueditor/jsp/upload/image/20160604/1465008328293017063.png",
             * "size": "185984" }
             */
            // renderJson(ret);
            renderJson(
                    Ret.create("state", "SUCCESS")
                            .set("url", CommonCons.PROJECT_NAME + "/upload" + uploadPath + uploadFile.getFileName( ))
                            .set("title", uploadFile.getFileName( ))
                            .set("original", uploadFile.getOriginalFileName( ))
                            .set("type", extName)
                            .set("size", size));
        } catch (com.jfinal.upload.ExceededSizeException ex) {
            renderJson("state", "上传图片只允许 200K 大小");
        } catch (Exception e) {
            if (uploadFile != null) {
                uploadFile.getFile( ).delete( );
            }

            renderJson("state", "上传图片出现未知异常，请告知管理员：" + e.getMessage( ));
            LogKit.error(e.getMessage( ), e);
        }
    }
}
