package com.xunwang.file.controller;

import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.xunwang.commonutils.R;
import io.netty.handler.codec.base64.Base64Encoder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.imageio.stream.FileImageInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

@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("文件上传失败！");
        }

    }

    @ApiOperation("根据路径返回图片base64编码")
    @PostMapping("download")
    public String download(@RequestBody String filePath) {
        byte[] data = null;
        FileImageInputStream input = null;
        String encode = "";
        try {
            input = new FileImageInputStream(new File(filePath));
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int numBytesRead = 0;
            while ((numBytesRead = input.read(buf)) != -1) {
                output.write(buf, 0, numBytesRead);
            }
            data = output.toByteArray();
            output.close();
            input.close();

            // 将字节数组转为base64
            encode = Base64.encodeBase64String(data).replaceAll("/[\\r\\n]/g", "");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return encode;
    }
}
