package com.softwarebr.nunu.web.api;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import com.aliyun.oss.model.PutObjectResult;
import com.baidu.ueditor.ActionEnter;
import com.baidu.ueditor.ConfigManager;
import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.State;
import com.brframework.commonoss.core.AliYunOSSClient;
import com.brframework.commonweb.utils.RequestResponseUtils;
import com.brframework.commonweb.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URISyntaxException;
import java.util.UUID;

/**
 * @author xu
 * @date 2020/1/2 17:56
 */
@RestController
@RequestMapping("/api/ueditor")
@Slf4j
public class ApiUediterController {

    @Autowired
    AliYunOSSClient ossClient;

    /**
     * 获取Ueditor的配置文件
     * @return
     */
    @RequestMapping(value = "/action", method = {RequestMethod.GET, RequestMethod.POST})
    public void getConfig(HttpServletRequest request ,HttpServletResponse response,
                          @RequestParam(value = "action") String action) throws IOException, NoSuchFieldException, IllegalAccessException, URISyntaxException, ServletException {
        switch (action){
            case "config":
                config(request, response);
                break;
            case "uploadimage":
            case "uploadvideo":
            case "uploadfile":
                uploadfile(request, response);
                break;
            case "uploadscrawl":
                uploadscrawl(request, response);
                break;
            case "catchimage":
                break;
            case "listfile":
                break;
            case "listimage":
                break;
            default:
                break;
        }

    }

    private void config(HttpServletRequest request, HttpServletResponse response) throws URISyntaxException, NoSuchFieldException, IllegalAccessException {
        log.info(getClass().getClassLoader().getResource("").getPath());
        File file = new File(System.getProperty("java.io.tmpdir") + File.separator + "config.json");
        file.deleteOnExit();
        log.info("path = " + file.getPath());
        FileUtil.writeFromStream(getClass().getClassLoader().getResourceAsStream("config.json"), file);
        ActionEnter actionEnter = new ActionEnter(ServletUtils.request(), ServletUtils.request()
                .getServletContext().getRealPath(""));
        Field configManager = actionEnter.getClass().getDeclaredField("configManager");
        configManager.setAccessible(true);
        configManager.set(actionEnter, ConfigManager.getInstance("", "", file.getPath()));
        RequestResponseUtils.writer(response, actionEnter.exec()
                , "application/json");
    }

    private void uploadfile(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        Part file = request.getPart("upfile");
        String fileName = UUID.randomUUID().toString();
        String fileType = file.getSubmittedFileName().substring(file.getSubmittedFileName().indexOf("."));
        String bucket = ossClient.getDefaultBucketName();
        PutObjectResult result = ossClient.putObject(bucket, "nunu/" + fileName + fileType, file.getInputStream());
        String fileUrl = ossClient.genUrl("nunu/" + fileName + fileType);
        State state = new BaseState();
        state.putInfo("size", file.getSize());
        state.putInfo("title", file.getName());
        state.putInfo("url", fileUrl);
        state.putInfo("type", fileType);
        state.putInfo("original", file.getSubmittedFileName());
        RequestResponseUtils.writer(response, state.toJSONString()
                , "application/json");
    }

    private void uploadscrawl(HttpServletRequest request, HttpServletResponse response){
        byte[] codec = Base64.decode(request.getParameter("upfile"));
        String fileName = UUID.randomUUID().toString();
        String bucket = ossClient.getDefaultBucketName();
        ossClient.putObject(bucket, "nunu/" + fileName + ".jpg",
                new ByteArrayInputStream(codec));
        String fileUrl = ossClient.genUrl("nunu/" + fileName + ".jpg");
        State state = new BaseState();
        state.putInfo("size", codec.length);
        state.putInfo("title", fileName);
        state.putInfo("url", fileUrl);
        state.putInfo("type", ".jpg");
        state.putInfo("original", fileName);
        RequestResponseUtils.writer(response, state.toJSONString()
                , "application/json");
    }


    /**
     * Ueditor上传文件
     * 这里以上传图片为例，图片上传后，imgPath将存储图片的保存路径，返回到编辑器中做展示
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public void upload(HttpServletResponse response, @RequestParam("file") MultipartFile file) {
        String result = "";
        if(!file.isEmpty()) {
            String originalFileName = file.getOriginalFilename();

            String imgPath = "";
            result = "{\n" +
                    "    \"state\": \"SUCCESS\",\n" +
                    "    \"url\": \"" + imgPath + "\",\n" +
                    "    \"title\": \"" + originalFileName + "\",\n" +
                    "    \"original\": \"" + originalFileName + "\"\n" +
                    "}";
            RequestResponseUtils.writer(response, imgPath
                    , "application/json");
        }
    }

}
