package com.xunwang.file.controller;

import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.xunwang.commonutils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@ApiSupport(author = "Long")
@Api("文件相关")
@RestController
@RequestMapping("/file")
public class FileUpload {

    @Value("${define.windows.path}")
    private String windowsPath;

    @ApiOperation("上传文件接口")
    @PostMapping("upload")
    public R upload(@RequestParam("file") MultipartFile file) {
        // 根据日期划分目录
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String formatDate = dateFormat.format(new Date());

        String newPath = windowsPath + "\\" + formatDate;
        // 如果目录不存在创建
        File uploadDir = new File(newPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
        // 获取原始文件名
        String originalFilename = file.getOriginalFilename();
        // 获取原始文件后缀名
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));

        // 重新生成名字
        String fileName = UUID.randomUUID().toString() + suffixName;
        File localFile = new File(newPath + "\\" + fileName);
        try {
            // 将上传的文件保存到本地
            file.transferTo(localFile);
            Map<String, Object> hashMap = new HashMap<>();
            hashMap.put("path", newPath);
            hashMap.put("fileName", fileName);
            return R.ok().data(hashMap);

        } catch (Exception e) {
            e.printStackTrace();
            return R.error().message("文件上传失败！");
        }

    }
}
