package com.dayou.controller;

import com.alibaba.fastjson.JSON;
import com.dayou.annotation.IgnoreAuth;
import com.dayou.common.RestResponse;
import com.dayou.configuration.DfsConfig;
import com.dayou.exception.ErrorCode;
import com.dayou.exception.file.InvalidExtensionException;
import com.dayou.ueditor.ActionEnter;
import com.dayou.ueditor.define.UeRespoVO;
import com.dayou.utils.FileUploadUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

import static com.dayou.constants.JwtConstants.RESOURCE_PREFIX;
import static com.dayou.exception.ErrorCode.DEFAULTERROR;
import static com.dayou.exception.ErrorCode.FILE_EXT_ERROR;


/**
 * 文件上传
 *
 * @author wucl
 * @since 2023-2-7
 */
@Slf4j
@RestController
@IgnoreAuth
public class FileController {

    private static final Pattern PORTPATTERN = Pattern.compile(":\\d+");

    @Autowired
    private DfsConfig dfsConfig;

    @Autowired
    private ActionEnter actionEnter;

    @Value("${server.port:80}")
    private Integer port;

    @Value("${ueditor.urlPrefix}")
    private String urlprefix;

    /**
     * 通用上传请求
     */
    @PostMapping("upload")
    public RestResponse upload(MultipartFile file) {
        try {
            // 上传文件路径
            String filePath = dfsConfig.getPath();
            // 上传并返回新文件名称
            String fileName = null;
            fileName = FileUploadUtils.upload(filePath, file);
            String url = dfsConfig.getDomain() + fileName;
            Map map = new HashMap();
            map.put("fileName", fileName);
            map.put("url", url);
            return RestResponse.data(map);
        } catch (Exception e) {
            log.error("upload error", e);
            ErrorCode.throwBusinessException(DEFAULTERROR);
        }

        return RestResponse.error();
    }

    /**
     * 百度富文本编辑器后端适配接口
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/ueditor/exec")
    @IgnoreAuth
    public String exe(HttpServletRequest request) {
        String res = actionEnter.exec(request);
        //是在上传 不是回调校验
        if (request.getParameter("callback") == null && res.contains("SUCCESS")) {
            UeRespoVO ueRespoVO = JSON.parseObject(res, UeRespoVO.class);
            // 上传文件路径
            String filePath = dfsConfig.getPath();
            String pathname = filePath + ueRespoVO.getUrl();
            new File(pathname);
            res = JSON.toJSONString(ueRespoVO);
        } else {
            //根基实际url动态替换 url
            StringBuffer url = request.getRequestURL();
            String contextPath = request.getServletContext().getContextPath();
            String realUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();

            String replacementURL = realUrl + RESOURCE_PREFIX;
            boolean hasPort = PORTPATTERN.matcher(replacementURL).find();

            if (!hasPort) {
                if (contextPath == null) {
                    String[] split = replacementURL.split(RESOURCE_PREFIX);
                    replacementURL = split[0] + ":" + port + RESOURCE_PREFIX;
                } else {
                    String[] split = replacementURL.split(contextPath);
                    replacementURL = split[0] + ":" + port + contextPath + split[1];
                }
            }
            res = res.replaceAll(urlprefix, replacementURL);
        }
        return res;
    }

}