package org.enfi.modules.visitor.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.net.multipart.UploadFile;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.annotations.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.enfi.common.api.vo.Result;
import org.enfi.common.aspect.annotation.AutoLog;
import org.enfi.common.aspect.annotation.PrintLnTime;
import org.enfi.common.exception.EnFiBootException;
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 java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @Description:
 * @ClassName: UploadController
 * @Author: wanghao
 * @date: 2021.11.13 16:55
 * @version: 1.0
 */
@Slf4j
@Api(tags = "文件上传")
@ApiSupport(order = 4, author = "WangHao")
@RestController
@RequestMapping("/upload")
public class UploadController {

    @Value("${upload.path}")
    private String path;
    @Value("${upload.url-perfix}")
    private String urlPerfix;
    @Value("${upload.local-path}")
    private String localPath;
    @Value("${upload.local-perfix}")
    private String localPerfix;
    @Value("${upload.img-url}")
    private String imgUrl;

    @AutoLog("上传文件")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "上传文件", notes = "上传文件")
    @PostMapping("/upload")
    @SneakyThrows
    @PrintLnTime
    public Result<?> upload(@RequestParam MultipartFile file) {
        if (file.isEmpty()) {
            throw new EnFiBootException("文件不能为空");
        }
        String os = System.getProperty("os.name").toLowerCase();
        String usrPath = ((os.indexOf("win") != -1) ? localPath : (os.indexOf("lin") != -1) ? path : localPath);
        String usrPerfix = ((os.indexOf("win") != -1) ? localPerfix : (os.indexOf("lin") != -1) ? imgUrl : localPerfix);
        String fileName = file.getOriginalFilename();
        String realFileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddhhmmssSSS")) + fileName;
        String realPath = usrPath + realFileName;
        File dest = new File(realPath);
        if (FileUtil.exist(dest)) {
            throw new EnFiBootException("文件已存在");
        }
        File overFile = FileUtil.writeBytes(file.getBytes(), realPath);
        if (overFile.length() < 0) {
            throw new EnFiBootException("文件上传失败");
        }
        return Result.OK("上传成功", usrPerfix + realFileName);
    }
}
