package com.ghy.web.controller.tool;

import com.ghy.common.core.domain.AjaxResult;
import com.ghy.common.utils.QiniuUtils;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
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.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 七牛云
 *
 * @author clunt
 */
@Api
@Controller
@RequestMapping("/tool/qiniu")
public class QiniuController {

    private static final Logger logger = LoggerFactory.getLogger(QiniuController.class);

    /**
     * 七牛云上传（单个）
     */
    @PostMapping(value = "/upload")
    @ResponseBody
    public AjaxResult uploadFile(@RequestParam(value = "uploadFile", required = false) MultipartFile file) {
        try {
            // 上传后返回的文件路径
            String fileUrl = QiniuUtils.upload(file.getBytes());
            logger.info("upload return url is : " + fileUrl);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", fileUrl);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 七牛云上传（单个）
     */
    @PostMapping(value = "/dept/upload")
    @ResponseBody
    @ApiOperation("七牛云上传接口")
    public AjaxResult uploadFile(HttpServletRequest request, HttpServletResponse response) {
        try {
            String name = request.getParameter("name");
            // 转型为MultipartHttpRequest：
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            // 获得实际：
            MultipartFile file= multipartRequest.getFile(name);
            // 上传后返回的文件路径
            String fileUrl = QiniuUtils.upload(file.getBytes());
            logger.info("upload return url is : " + fileUrl);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", fileUrl);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

}
