package com.sunda.spmsweb.ordercontroller;

import com.sunda.spmscommon.ResponseResult;
import com.sunda.spmsorder.service.IFileOperationService;
import com.sunda.spmsweb.util.FileUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
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.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.UUID;

/**
 * @program: spms-file
 * @description: MultipleImageUpload
 * @author: Wayne Wu
 * @create: 2021-07-09 09:21
 **/
@RestController
@RequestMapping("/image")
@Api(tags = "图片服务接口", description = "图片服务接口")
public class MultipleImageUpload {

    final String localPath = System.getProperties().getProperty("user.dir") + "/picture";
    @Autowired
    IFileOperationService iFileOperationService;

    @RequestMapping(value = "/getImage", produces = MediaType.IMAGE_JPEG_VALUE)
    @ApiOperation(value = "获取上传图片", notes = "获取上传图片 \n" +
            "示例 fileName = 398483e5e3164d52a54e004c11faa6a3.png,b575f03021344a1290f16ce0f5146f46.png,ca3e4ae1331f474fb9d00f4f0e61d4f8.jpg",
            httpMethod = "GET")
    public byte[] getImage(String fileName) throws Exception{
        File file = new File("picture/" + fileName);
        if (file.exists()){
            FileInputStream inputStream = new FileInputStream(file);
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes, 0, inputStream.available());
            return bytes;
        }
        return null;
    }

    @RequestMapping("/multipleImageUpload")
    @ApiOperation(value = "上传多张图片", notes = "上传多张图片", httpMethod = "POST")
    public ResponseResult multipleImageUpload(@RequestParam("uploadFiles") MultipartFile[] files){
        System.out.println("上传的图片数：" + files.length);
        String resultList = "";
        //循环保存文件
        for (MultipartFile file : files) {
            //一个文件上传的结果；上传结果信息
            if (file.getSize() / 1000 > 1000){
                System.out.println("图片大小不能超过1000KB");
            } else{
                //判断上传文件格式
                String fileType = file.getContentType();
                System.out.println("\nfileType =======" + fileType);
                if (fileType == null){
                    return null;
                }
                if ("image/jpg".equals(fileType) || "image/png".equals(fileType) || "image/jpeg".equals(fileType)) {
                    // 要上传的目标文件存放的绝对路径
                    //上传后保存的文件名(需要防止图片重名导致的文件覆盖)；获取文件名；
                    String fileName = file.getOriginalFilename();
                    //获取文件后缀名
                    String suffixName = fileName.substring(fileName.lastIndexOf("."));
                    //重新生成文件名
                    fileName = UUID.randomUUID().toString().replaceAll("-", "").toLowerCase() + suffixName;
                    System.out.println("fileName ========" + fileName);
                    if (FileUtils.upload(file, localPath, fileName)) {
                        //文件存放的相对路径
                        String relativePath = fileName;
                        if (resultList.length() == 0){
                            resultList = fileName;
                        } else {
                            resultList = resultList + "," + fileName;
                        }
                    } else{
                        System.out.println("图片上传失败");
                    }
                } else{
                    System.out.println("图片格式不正确");
                    //return ResponseResult.error("图片格式不正确");
                }
            }
        }
        if (resultList.length() > 0){
            return ResponseResult.success().add("imageNames", resultList);
        }
        return ResponseResult.error();
    }

    @RequestMapping(value = "/deleteImages")
    @ApiOperation(value = "删除图片", notes = "删除图片 \n" +
            "示例参数，多个文件名逗号分割，示例 fileNames = 398483e5e3164d52a54e004c11faa6a3.png,b575f03021344a1290f16ce0f5146f46.png",
            httpMethod = "GET")
    public ResponseResult deleteImage(String fileNames) throws Exception{
        if (fileNames == null || fileNames.length() == 0){
            return ResponseResult.error("请求参数不能为空");
        }
        String [] fileList = fileNames.split(",");
        for (String filename : fileList){
            if (filename.length() > 0){
                File file = new File("picture/" + filename);
                if (file.exists()) {
                    if (file.delete()) {
                        System.out.println(filename + " 删除成功");
                    }else {
                        System.out.println(filename + " 删除失败");
                    }
                }else {
                    System.out.println(filename + " 文件不存在");
                }
            }

        }
        return ResponseResult.success();
    }

    @RequestMapping("/uploadMaterialPic")
    @ApiOperation(value = "上传非目录物料申请图片", notes = "请求参数示例：{ avatar: file}", httpMethod = "POST")
    @ResponseBody
    public ResponseResult uploadMaterialPic(@RequestParam(value = "avatar") MultipartFile avatar){
        if (avatar.isEmpty()) {
            return ResponseResult.error("不能上传空文件");
        }else {
            // 另存文件名
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            Calendar calendar = Calendar.getInstance();
            String fileName = df.format(calendar.getTime()) + avatar.getOriginalFilename();
            // 1.附件缓存路径
            String filePath = iFileOperationService.saveMaterialApplicationPic(avatar, fileName);
            System.out.println("fileName" + filePath);
            // 2.上传附件至minIO文件服务器
            String fileUrl = iFileOperationService.fileUploader(fileName, filePath);
            return ResponseResult.success()
                    .add("imageUrl",fileUrl);
        }
    }

}
