package cn.wisenergy.web.admin.controller.app;

import cn.wisenergy.common.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author 86187
 * @ Description:
 * @ Author     : 86187
 * @ Date       : 2021/2/3 17:05
 */
@Api(tags = "图片上传")
@RestController
@RequestMapping("/pic")
@Slf4j
public class FileUploadController {

    /**
     * 请求 url 中的资源映射，不推荐写死在代码中，最好提供可配置，如 /upload_flowChart/**
     */
    @Value("${uploadFile.resourceHandler}")
    private String resourceHandler;

    /**
     * 上传文件保存的本地目录，使用@Value获取全局配置文件中配置的属性值，如 D:/java/upload_flowChart/
     */
    @Value("${uploadFile.location}")
    private String uploadImagesLocation;

    /**
     * 允许上传的格式
     */
    private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg", ".jpeg", ".gif", ".png"};

    @ApiOperation(value = "文件上传", notes = "文件上传")
    @PostMapping(value = "/upload", headers = "content-type=multipart/form-data")
    public R file(
            @ApiParam(required = true, value = "上传文件")
            @RequestParam("file") MultipartFile file,
            HttpServletRequest request) {

        boolean isLegal = true;

        if (file.isEmpty()) {
            // 上传文件为空
            return R.error("上传文件不能为空");
        }
        for (String type : IMAGE_TYPE) {
            if (StringUtils.endsWithIgnoreCase(file.getOriginalFilename(), type)) {
                isLegal = false;
                break;
            }
        }
        if (isLegal) {
            return R.error("上传文件类型不符合");
        }
        File folder = new File(uploadImagesLocation);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String oldName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString().substring(4,9) + oldName;
        try {
            file.transferTo(new File(folder, newName));
            String url = "/upload_flowChart/" + newName;
            return R.ok(200, url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.error("上传文件失败！");
    }
}
